blob: 76ea889dc5053858d49ae5170d5c39c16351276c [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
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057#include <android-base/stringprintf.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <input/Keyboard.h>
59#include <input/VirtualKeyMap.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
61#define INDENT " "
62#define INDENT2 " "
63#define INDENT3 " "
64#define INDENT4 " "
65#define INDENT5 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
71// --- Constants ---
72
73// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
74static const size_t MAX_SLOTS = 32;
75
Michael Wright842500e2015-03-13 17:32:02 -070076// Maximum amount of latency to add to touch events while waiting for data from an
77// external stylus.
Michael Wright5e17a5d2015-04-21 22:45:13 +010078static const nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
Michael Wright842500e2015-03-13 17:32:02 -070079
Michael Wright43fd19f2015-04-21 19:02:58 +010080// Maximum amount of time to wait on touch data before pushing out new pressure data.
81static const nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
82
83// Artificial latency on synthetic events created from stylus data without corresponding touch
84// data.
85static const nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
86
Michael Wrightd02c5b62014-02-10 15:10:22 -080087// --- Static Functions ---
88
89template<typename T>
90inline static T abs(const T& value) {
91 return value < 0 ? - value : value;
92}
93
94template<typename T>
95inline static T min(const T& a, const T& b) {
96 return a < b ? a : b;
97}
98
99template<typename T>
100inline static void swap(T& a, T& b) {
101 T temp = a;
102 a = b;
103 b = temp;
104}
105
106inline static float avg(float x, float y) {
107 return (x + y) / 2;
108}
109
110inline static float distance(float x1, float y1, float x2, float y2) {
111 return hypotf(x1 - x2, y1 - y2);
112}
113
114inline static int32_t signExtendNybble(int32_t value) {
115 return value >= 8 ? value - 16 : value;
116}
117
118static inline const char* toString(bool value) {
119 return value ? "true" : "false";
120}
121
122static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
123 const int32_t map[][4], size_t mapSize) {
124 if (orientation != DISPLAY_ORIENTATION_0) {
125 for (size_t i = 0; i < mapSize; i++) {
126 if (value == map[i][0]) {
127 return map[i][orientation];
128 }
129 }
130 }
131 return value;
132}
133
134static const int32_t keyCodeRotationMap[][4] = {
135 // key codes enumerated counter-clockwise with the original (unrotated) key first
136 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
137 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
138 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
139 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
140 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jim Millere7a57d12016-06-22 15:58:31 -0700141 { AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
142 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT },
143 { AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
144 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN },
145 { AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
146 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT },
147 { AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
148 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP },
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149};
150static const size_t keyCodeRotationMapSize =
151 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
152
Ivan Podogovb9afef32017-02-13 15:34:32 +0000153static int32_t rotateStemKey(int32_t value, int32_t orientation,
154 const int32_t map[][2], size_t mapSize) {
155 if (orientation == DISPLAY_ORIENTATION_180) {
156 for (size_t i = 0; i < mapSize; i++) {
157 if (value == map[i][0]) {
158 return map[i][1];
159 }
160 }
161 }
162 return value;
163}
164
165// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
166static int32_t stemKeyRotationMap[][2] = {
167 // key codes enumerated with the original (unrotated) key first
168 // no rotation, 180 degree rotation
169 { AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
170 { AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
171 { AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
172 { AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
173};
174static const size_t stemKeyRotationMapSize =
175 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
176
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000178 keyCode = rotateStemKey(keyCode, orientation,
179 stemKeyRotationMap, stemKeyRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 return rotateValueUsingRotationMap(keyCode, orientation,
181 keyCodeRotationMap, keyCodeRotationMapSize);
182}
183
184static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
185 float temp;
186 switch (orientation) {
187 case DISPLAY_ORIENTATION_90:
188 temp = *deltaX;
189 *deltaX = *deltaY;
190 *deltaY = -temp;
191 break;
192
193 case DISPLAY_ORIENTATION_180:
194 *deltaX = -*deltaX;
195 *deltaY = -*deltaY;
196 break;
197
198 case DISPLAY_ORIENTATION_270:
199 temp = *deltaX;
200 *deltaX = -*deltaY;
201 *deltaY = temp;
202 break;
203 }
204}
205
206static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
207 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
208}
209
210// Returns true if the pointer should be reported as being down given the specified
211// button states. This determines whether the event is reported as a touch event.
212static bool isPointerDown(int32_t buttonState) {
213 return buttonState &
214 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
215 | AMOTION_EVENT_BUTTON_TERTIARY);
216}
217
218static float calculateCommonVector(float a, float b) {
219 if (a > 0 && b > 0) {
220 return a < b ? a : b;
221 } else if (a < 0 && b < 0) {
222 return a > b ? a : b;
223 } else {
224 return 0;
225 }
226}
227
228static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
229 nsecs_t when, int32_t deviceId, uint32_t source,
230 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
231 int32_t buttonState, int32_t keyCode) {
232 if (
233 (action == AKEY_EVENT_ACTION_DOWN
234 && !(lastButtonState & buttonState)
235 && (currentButtonState & buttonState))
236 || (action == AKEY_EVENT_ACTION_UP
237 && (lastButtonState & buttonState)
238 && !(currentButtonState & buttonState))) {
239 NotifyKeyArgs args(when, deviceId, source, policyFlags,
240 action, 0, keyCode, 0, context->getGlobalMetaState(), when);
241 context->getListener()->notifyKey(&args);
242 }
243}
244
245static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
246 nsecs_t when, int32_t deviceId, uint32_t source,
247 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
248 synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
249 lastButtonState, currentButtonState,
250 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
251 synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
252 lastButtonState, currentButtonState,
253 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
254}
255
256
257// --- InputReaderConfiguration ---
258
Santos Cordonfa5cf462017-04-05 10:37:00 -0700259bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType,
260 const String8* uniqueDisplayId, DisplayViewport* outViewport) const {
261 const DisplayViewport* viewport = NULL;
262 if (viewportType == ViewportType::VIEWPORT_VIRTUAL && uniqueDisplayId != NULL) {
Michael Spangf88ea9b2017-09-05 20:17:16 -0400263 for (const DisplayViewport& currentViewport : mVirtualDisplays) {
Santos Cordonfa5cf462017-04-05 10:37:00 -0700264 if (currentViewport.uniqueId == *uniqueDisplayId) {
265 viewport = &currentViewport;
266 break;
267 }
268 }
269 } else if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
270 viewport = &mExternalDisplay;
271 } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
272 viewport = &mInternalDisplay;
273 }
274
275 if (viewport != NULL && viewport->displayId >= 0) {
276 *outViewport = *viewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800277 return true;
278 }
279 return false;
280}
281
Santos Cordonfa5cf462017-04-05 10:37:00 -0700282void InputReaderConfiguration::setPhysicalDisplayViewport(ViewportType viewportType,
283 const DisplayViewport& viewport) {
284 if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
285 mExternalDisplay = viewport;
286 } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
287 mInternalDisplay = viewport;
288 }
289}
290
291void InputReaderConfiguration::setVirtualDisplayViewports(
292 const Vector<DisplayViewport>& viewports) {
293 mVirtualDisplays = viewports;
294}
295
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800296void InputReaderConfiguration::dump(std::string& dump) const {
297 dump += INDENT4 "ViewportInternal:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700298 dumpViewport(dump, mInternalDisplay);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800299 dump += INDENT4 "ViewportExternal:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700300 dumpViewport(dump, mExternalDisplay);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800301 dump += INDENT4 "ViewportVirtual:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700302 for (const DisplayViewport& viewport : mVirtualDisplays) {
303 dumpViewport(dump, viewport);
304 }
305}
306
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800307void InputReaderConfiguration::dumpViewport(std::string& dump, const DisplayViewport& viewport) const {
308 dump += StringPrintf(INDENT5 "Viewport: displayId=%d, orientation=%d, uniqueId='%s', "
Santos Cordonfa5cf462017-04-05 10:37:00 -0700309 "logicalFrame=[%d, %d, %d, %d], "
310 "physicalFrame=[%d, %d, %d, %d], "
311 "deviceSize=[%d, %d]\n",
312 viewport.displayId, viewport.orientation, viewport.uniqueId.c_str(),
313 viewport.logicalLeft, viewport.logicalTop,
314 viewport.logicalRight, viewport.logicalBottom,
315 viewport.physicalLeft, viewport.physicalTop,
316 viewport.physicalRight, viewport.physicalBottom,
317 viewport.deviceWidth, viewport.deviceHeight);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800318}
319
320
Jason Gereckeaf126fb2012-05-10 14:22:47 -0700321// -- TouchAffineTransformation --
322void TouchAffineTransformation::applyTo(float& x, float& y) const {
323 float newX, newY;
324 newX = x * x_scale + y * x_ymix + x_offset;
325 newY = x * y_xmix + y * y_scale + y_offset;
326
327 x = newX;
328 y = newY;
329}
330
331
Michael Wrightd02c5b62014-02-10 15:10:22 -0800332// --- InputReader ---
333
334InputReader::InputReader(const sp<EventHubInterface>& eventHub,
335 const sp<InputReaderPolicyInterface>& policy,
336 const sp<InputListenerInterface>& listener) :
337 mContext(this), mEventHub(eventHub), mPolicy(policy),
338 mGlobalMetaState(0), mGeneration(1),
339 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
340 mConfigurationChangesToRefresh(0) {
341 mQueuedListener = new QueuedInputListener(listener);
342
343 { // acquire lock
344 AutoMutex _l(mLock);
345
346 refreshConfigurationLocked(0);
347 updateGlobalMetaStateLocked();
348 } // release lock
349}
350
351InputReader::~InputReader() {
352 for (size_t i = 0; i < mDevices.size(); i++) {
353 delete mDevices.valueAt(i);
354 }
355}
356
357void InputReader::loopOnce() {
358 int32_t oldGeneration;
359 int32_t timeoutMillis;
360 bool inputDevicesChanged = false;
361 Vector<InputDeviceInfo> inputDevices;
362 { // acquire lock
363 AutoMutex _l(mLock);
364
365 oldGeneration = mGeneration;
366 timeoutMillis = -1;
367
368 uint32_t changes = mConfigurationChangesToRefresh;
369 if (changes) {
370 mConfigurationChangesToRefresh = 0;
371 timeoutMillis = 0;
372 refreshConfigurationLocked(changes);
373 } else if (mNextTimeout != LLONG_MAX) {
374 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
375 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
376 }
377 } // release lock
378
379 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
380
381 { // acquire lock
382 AutoMutex _l(mLock);
383 mReaderIsAliveCondition.broadcast();
384
385 if (count) {
386 processEventsLocked(mEventBuffer, count);
387 }
388
389 if (mNextTimeout != LLONG_MAX) {
390 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
391 if (now >= mNextTimeout) {
392#if DEBUG_RAW_EVENTS
393 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
394#endif
395 mNextTimeout = LLONG_MAX;
396 timeoutExpiredLocked(now);
397 }
398 }
399
400 if (oldGeneration != mGeneration) {
401 inputDevicesChanged = true;
402 getInputDevicesLocked(inputDevices);
403 }
404 } // release lock
405
406 // Send out a message that the describes the changed input devices.
407 if (inputDevicesChanged) {
408 mPolicy->notifyInputDevicesChanged(inputDevices);
409 }
410
411 // Flush queued events out to the listener.
412 // This must happen outside of the lock because the listener could potentially call
413 // back into the InputReader's methods, such as getScanCodeState, or become blocked
414 // on another thread similarly waiting to acquire the InputReader lock thereby
415 // resulting in a deadlock. This situation is actually quite plausible because the
416 // listener is actually the input dispatcher, which calls into the window manager,
417 // which occasionally calls into the input reader.
418 mQueuedListener->flush();
419}
420
421void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
422 for (const RawEvent* rawEvent = rawEvents; count;) {
423 int32_t type = rawEvent->type;
424 size_t batchSize = 1;
425 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
426 int32_t deviceId = rawEvent->deviceId;
427 while (batchSize < count) {
428 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
429 || rawEvent[batchSize].deviceId != deviceId) {
430 break;
431 }
432 batchSize += 1;
433 }
434#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700435 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800436#endif
437 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
438 } else {
439 switch (rawEvent->type) {
440 case EventHubInterface::DEVICE_ADDED:
441 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
442 break;
443 case EventHubInterface::DEVICE_REMOVED:
444 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
445 break;
446 case EventHubInterface::FINISHED_DEVICE_SCAN:
447 handleConfigurationChangedLocked(rawEvent->when);
448 break;
449 default:
450 ALOG_ASSERT(false); // can't happen
451 break;
452 }
453 }
454 count -= batchSize;
455 rawEvent += batchSize;
456 }
457}
458
459void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
460 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
461 if (deviceIndex >= 0) {
462 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
463 return;
464 }
465
466 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
467 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
468 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
469
470 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
471 device->configure(when, &mConfig, 0);
472 device->reset(when);
473
474 if (device->isIgnored()) {
475 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
476 identifier.name.string());
477 } else {
478 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
479 identifier.name.string(), device->getSources());
480 }
481
482 mDevices.add(deviceId, device);
483 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700484
485 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
486 notifyExternalStylusPresenceChanged();
487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488}
489
490void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
491 InputDevice* device = NULL;
492 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
493 if (deviceIndex < 0) {
494 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
495 return;
496 }
497
498 device = mDevices.valueAt(deviceIndex);
499 mDevices.removeItemsAt(deviceIndex, 1);
500 bumpGenerationLocked();
501
502 if (device->isIgnored()) {
503 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
504 device->getId(), device->getName().string());
505 } else {
506 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
507 device->getId(), device->getName().string(), device->getSources());
508 }
509
Michael Wright842500e2015-03-13 17:32:02 -0700510 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
511 notifyExternalStylusPresenceChanged();
512 }
513
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514 device->reset(when);
515 delete device;
516}
517
518InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
519 const InputDeviceIdentifier& identifier, uint32_t classes) {
520 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
521 controllerNumber, identifier, classes);
522
523 // External devices.
524 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
525 device->setExternal(true);
526 }
527
Tim Kilbourn063ff532015-04-08 10:26:18 -0700528 // Devices with mics.
529 if (classes & INPUT_DEVICE_CLASS_MIC) {
530 device->setMic(true);
531 }
532
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 // Switch-like devices.
534 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
535 device->addMapper(new SwitchInputMapper(device));
536 }
537
Prashant Malani1941ff52015-08-11 18:29:28 -0700538 // Scroll wheel-like devices.
539 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
540 device->addMapper(new RotaryEncoderInputMapper(device));
541 }
542
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 // Vibrator-like devices.
544 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
545 device->addMapper(new VibratorInputMapper(device));
546 }
547
548 // Keyboard-like devices.
549 uint32_t keyboardSource = 0;
550 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
551 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
552 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
553 }
554 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
555 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
556 }
557 if (classes & INPUT_DEVICE_CLASS_DPAD) {
558 keyboardSource |= AINPUT_SOURCE_DPAD;
559 }
560 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
561 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
562 }
563
564 if (keyboardSource != 0) {
565 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
566 }
567
568 // Cursor-like devices.
569 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
570 device->addMapper(new CursorInputMapper(device));
571 }
572
573 // Touchscreens and touchpad devices.
574 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
575 device->addMapper(new MultiTouchInputMapper(device));
576 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
577 device->addMapper(new SingleTouchInputMapper(device));
578 }
579
580 // Joystick-like devices.
581 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
582 device->addMapper(new JoystickInputMapper(device));
583 }
584
Michael Wright842500e2015-03-13 17:32:02 -0700585 // External stylus-like devices.
586 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
587 device->addMapper(new ExternalStylusInputMapper(device));
588 }
589
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590 return device;
591}
592
593void InputReader::processEventsForDeviceLocked(int32_t deviceId,
594 const RawEvent* rawEvents, size_t count) {
595 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
596 if (deviceIndex < 0) {
597 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
598 return;
599 }
600
601 InputDevice* device = mDevices.valueAt(deviceIndex);
602 if (device->isIgnored()) {
603 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
604 return;
605 }
606
607 device->process(rawEvents, count);
608}
609
610void InputReader::timeoutExpiredLocked(nsecs_t when) {
611 for (size_t i = 0; i < mDevices.size(); i++) {
612 InputDevice* device = mDevices.valueAt(i);
613 if (!device->isIgnored()) {
614 device->timeoutExpired(when);
615 }
616 }
617}
618
619void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
620 // Reset global meta state because it depends on the list of all configured devices.
621 updateGlobalMetaStateLocked();
622
623 // Enqueue configuration changed.
624 NotifyConfigurationChangedArgs args(when);
625 mQueuedListener->notifyConfigurationChanged(&args);
626}
627
628void InputReader::refreshConfigurationLocked(uint32_t changes) {
629 mPolicy->getReaderConfiguration(&mConfig);
630 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
631
632 if (changes) {
633 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
634 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
635
636 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
637 mEventHub->requestReopenDevices();
638 } else {
639 for (size_t i = 0; i < mDevices.size(); i++) {
640 InputDevice* device = mDevices.valueAt(i);
641 device->configure(now, &mConfig, changes);
642 }
643 }
644 }
645}
646
647void InputReader::updateGlobalMetaStateLocked() {
648 mGlobalMetaState = 0;
649
650 for (size_t i = 0; i < mDevices.size(); i++) {
651 InputDevice* device = mDevices.valueAt(i);
652 mGlobalMetaState |= device->getMetaState();
653 }
654}
655
656int32_t InputReader::getGlobalMetaStateLocked() {
657 return mGlobalMetaState;
658}
659
Michael Wright842500e2015-03-13 17:32:02 -0700660void InputReader::notifyExternalStylusPresenceChanged() {
661 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
662}
663
664void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
665 for (size_t i = 0; i < mDevices.size(); i++) {
666 InputDevice* device = mDevices.valueAt(i);
667 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
668 outDevices.push();
669 device->getDeviceInfo(&outDevices.editTop());
670 }
671 }
672}
673
674void InputReader::dispatchExternalStylusState(const StylusState& state) {
675 for (size_t i = 0; i < mDevices.size(); i++) {
676 InputDevice* device = mDevices.valueAt(i);
677 device->updateExternalStylusState(state);
678 }
679}
680
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
682 mDisableVirtualKeysTimeout = time;
683}
684
685bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
686 InputDevice* device, int32_t keyCode, int32_t scanCode) {
687 if (now < mDisableVirtualKeysTimeout) {
688 ALOGI("Dropping virtual key from device %s because virtual keys are "
689 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
690 device->getName().string(),
691 (mDisableVirtualKeysTimeout - now) * 0.000001,
692 keyCode, scanCode);
693 return true;
694 } else {
695 return false;
696 }
697}
698
699void InputReader::fadePointerLocked() {
700 for (size_t i = 0; i < mDevices.size(); i++) {
701 InputDevice* device = mDevices.valueAt(i);
702 device->fadePointer();
703 }
704}
705
706void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
707 if (when < mNextTimeout) {
708 mNextTimeout = when;
709 mEventHub->wake();
710 }
711}
712
713int32_t InputReader::bumpGenerationLocked() {
714 return ++mGeneration;
715}
716
717void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
718 AutoMutex _l(mLock);
719 getInputDevicesLocked(outInputDevices);
720}
721
722void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
723 outInputDevices.clear();
724
725 size_t numDevices = mDevices.size();
726 for (size_t i = 0; i < numDevices; i++) {
727 InputDevice* device = mDevices.valueAt(i);
728 if (!device->isIgnored()) {
729 outInputDevices.push();
730 device->getDeviceInfo(&outInputDevices.editTop());
731 }
732 }
733}
734
735int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
736 int32_t keyCode) {
737 AutoMutex _l(mLock);
738
739 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
740}
741
742int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
743 int32_t scanCode) {
744 AutoMutex _l(mLock);
745
746 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
747}
748
749int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
750 AutoMutex _l(mLock);
751
752 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
753}
754
755int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
756 GetStateFunc getStateFunc) {
757 int32_t result = AKEY_STATE_UNKNOWN;
758 if (deviceId >= 0) {
759 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
760 if (deviceIndex >= 0) {
761 InputDevice* device = mDevices.valueAt(deviceIndex);
762 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
763 result = (device->*getStateFunc)(sourceMask, code);
764 }
765 }
766 } else {
767 size_t numDevices = mDevices.size();
768 for (size_t i = 0; i < numDevices; i++) {
769 InputDevice* device = mDevices.valueAt(i);
770 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
771 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
772 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
773 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
774 if (currentResult >= AKEY_STATE_DOWN) {
775 return currentResult;
776 } else if (currentResult == AKEY_STATE_UP) {
777 result = currentResult;
778 }
779 }
780 }
781 }
782 return result;
783}
784
Andrii Kulian763a3a42016-03-08 10:46:16 -0800785void InputReader::toggleCapsLockState(int32_t deviceId) {
786 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
787 if (deviceIndex < 0) {
788 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
789 return;
790 }
791
792 InputDevice* device = mDevices.valueAt(deviceIndex);
793 if (device->isIgnored()) {
794 return;
795 }
796
797 device->updateMetaState(AKEYCODE_CAPS_LOCK);
798}
799
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
801 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
802 AutoMutex _l(mLock);
803
804 memset(outFlags, 0, numCodes);
805 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
806}
807
808bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
809 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
810 bool result = false;
811 if (deviceId >= 0) {
812 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
813 if (deviceIndex >= 0) {
814 InputDevice* device = mDevices.valueAt(deviceIndex);
815 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
816 result = device->markSupportedKeyCodes(sourceMask,
817 numCodes, keyCodes, outFlags);
818 }
819 }
820 } else {
821 size_t numDevices = mDevices.size();
822 for (size_t i = 0; i < numDevices; i++) {
823 InputDevice* device = mDevices.valueAt(i);
824 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
825 result |= device->markSupportedKeyCodes(sourceMask,
826 numCodes, keyCodes, outFlags);
827 }
828 }
829 }
830 return result;
831}
832
833void InputReader::requestRefreshConfiguration(uint32_t changes) {
834 AutoMutex _l(mLock);
835
836 if (changes) {
837 bool needWake = !mConfigurationChangesToRefresh;
838 mConfigurationChangesToRefresh |= changes;
839
840 if (needWake) {
841 mEventHub->wake();
842 }
843 }
844}
845
846void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
847 ssize_t repeat, int32_t token) {
848 AutoMutex _l(mLock);
849
850 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
851 if (deviceIndex >= 0) {
852 InputDevice* device = mDevices.valueAt(deviceIndex);
853 device->vibrate(pattern, patternSize, repeat, token);
854 }
855}
856
857void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
858 AutoMutex _l(mLock);
859
860 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
861 if (deviceIndex >= 0) {
862 InputDevice* device = mDevices.valueAt(deviceIndex);
863 device->cancelVibrate(token);
864 }
865}
866
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700867bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
868 AutoMutex _l(mLock);
869
870 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
871 if (deviceIndex >= 0) {
872 InputDevice* device = mDevices.valueAt(deviceIndex);
873 return device->isEnabled();
874 }
875 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
876 return false;
877}
878
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800879void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 AutoMutex _l(mLock);
881
882 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800883 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800885 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886
887 for (size_t i = 0; i < mDevices.size(); i++) {
888 mDevices.valueAt(i)->dump(dump);
889 }
890
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800891 dump += INDENT "Configuration:\n";
892 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
894 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800895 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800897 dump += mConfig.excludedDeviceNames.itemAt(i).string();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800899 dump += "]\n";
900 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 mConfig.virtualKeyQuietTime * 0.000001f);
902
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800903 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
905 mConfig.pointerVelocityControlParameters.scale,
906 mConfig.pointerVelocityControlParameters.lowThreshold,
907 mConfig.pointerVelocityControlParameters.highThreshold,
908 mConfig.pointerVelocityControlParameters.acceleration);
909
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800910 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
912 mConfig.wheelVelocityControlParameters.scale,
913 mConfig.wheelVelocityControlParameters.lowThreshold,
914 mConfig.wheelVelocityControlParameters.highThreshold,
915 mConfig.wheelVelocityControlParameters.acceleration);
916
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800917 dump += StringPrintf(INDENT2 "PointerGesture:\n");
918 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800920 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800922 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800924 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800926 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800928 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800930 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800932 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800934 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800936 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800938 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800940 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700942
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800943 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700944 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945}
946
947void InputReader::monitor() {
948 // Acquire and release the lock to ensure that the reader has not deadlocked.
949 mLock.lock();
950 mEventHub->wake();
951 mReaderIsAliveCondition.wait(mLock);
952 mLock.unlock();
953
954 // Check the EventHub
955 mEventHub->monitor();
956}
957
958
959// --- InputReader::ContextImpl ---
960
961InputReader::ContextImpl::ContextImpl(InputReader* reader) :
962 mReader(reader) {
963}
964
965void InputReader::ContextImpl::updateGlobalMetaState() {
966 // lock is already held by the input loop
967 mReader->updateGlobalMetaStateLocked();
968}
969
970int32_t InputReader::ContextImpl::getGlobalMetaState() {
971 // lock is already held by the input loop
972 return mReader->getGlobalMetaStateLocked();
973}
974
975void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
976 // lock is already held by the input loop
977 mReader->disableVirtualKeysUntilLocked(time);
978}
979
980bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
981 InputDevice* device, int32_t keyCode, int32_t scanCode) {
982 // lock is already held by the input loop
983 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
984}
985
986void InputReader::ContextImpl::fadePointer() {
987 // lock is already held by the input loop
988 mReader->fadePointerLocked();
989}
990
991void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
992 // lock is already held by the input loop
993 mReader->requestTimeoutAtTimeLocked(when);
994}
995
996int32_t InputReader::ContextImpl::bumpGeneration() {
997 // lock is already held by the input loop
998 return mReader->bumpGenerationLocked();
999}
1000
Michael Wright842500e2015-03-13 17:32:02 -07001001void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
1002 // lock is already held by whatever called refreshConfigurationLocked
1003 mReader->getExternalStylusDevicesLocked(outDevices);
1004}
1005
1006void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
1007 mReader->dispatchExternalStylusState(state);
1008}
1009
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
1011 return mReader->mPolicy.get();
1012}
1013
1014InputListenerInterface* InputReader::ContextImpl::getListener() {
1015 return mReader->mQueuedListener.get();
1016}
1017
1018EventHubInterface* InputReader::ContextImpl::getEventHub() {
1019 return mReader->mEventHub.get();
1020}
1021
1022
1023// --- InputReaderThread ---
1024
1025InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
1026 Thread(/*canCallJava*/ true), mReader(reader) {
1027}
1028
1029InputReaderThread::~InputReaderThread() {
1030}
1031
1032bool InputReaderThread::threadLoop() {
1033 mReader->loopOnce();
1034 return true;
1035}
1036
1037
1038// --- InputDevice ---
1039
1040InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
1041 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
1042 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
1043 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -07001044 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045}
1046
1047InputDevice::~InputDevice() {
1048 size_t numMappers = mMappers.size();
1049 for (size_t i = 0; i < numMappers; i++) {
1050 delete mMappers[i];
1051 }
1052 mMappers.clear();
1053}
1054
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001055bool InputDevice::isEnabled() {
1056 return getEventHub()->isDeviceEnabled(mId);
1057}
1058
1059void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1060 if (isEnabled() == enabled) {
1061 return;
1062 }
1063
1064 if (enabled) {
1065 getEventHub()->enableDevice(mId);
1066 reset(when);
1067 } else {
1068 reset(when);
1069 getEventHub()->disableDevice(mId);
1070 }
1071 // Must change generation to flag this device as changed
1072 bumpGeneration();
1073}
1074
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001075void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 InputDeviceInfo deviceInfo;
1077 getDeviceInfo(& deviceInfo);
1078
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001079 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 deviceInfo.getDisplayName().string());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001081 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1082 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
1083 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1084 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1085 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086
1087 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1088 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001089 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 for (size_t i = 0; i < ranges.size(); i++) {
1091 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1092 const char* label = getAxisLabel(range.axis);
1093 char name[32];
1094 if (label) {
1095 strncpy(name, label, sizeof(name));
1096 name[sizeof(name) - 1] = '\0';
1097 } else {
1098 snprintf(name, sizeof(name), "%d", range.axis);
1099 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001100 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1102 name, range.source, range.min, range.max, range.flat, range.fuzz,
1103 range.resolution);
1104 }
1105 }
1106
1107 size_t numMappers = mMappers.size();
1108 for (size_t i = 0; i < numMappers; i++) {
1109 InputMapper* mapper = mMappers[i];
1110 mapper->dump(dump);
1111 }
1112}
1113
1114void InputDevice::addMapper(InputMapper* mapper) {
1115 mMappers.add(mapper);
1116}
1117
1118void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1119 mSources = 0;
1120
1121 if (!isIgnored()) {
1122 if (!changes) { // first time only
1123 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1124 }
1125
1126 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1127 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1128 sp<KeyCharacterMap> keyboardLayout =
1129 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1130 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1131 bumpGeneration();
1132 }
1133 }
1134 }
1135
1136 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1137 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1138 String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
1139 if (mAlias != alias) {
1140 mAlias = alias;
1141 bumpGeneration();
1142 }
1143 }
1144 }
1145
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001146 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1147 ssize_t index = config->disabledDevices.indexOf(mId);
1148 bool enabled = index < 0;
1149 setEnabled(enabled, when);
1150 }
1151
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 size_t numMappers = mMappers.size();
1153 for (size_t i = 0; i < numMappers; i++) {
1154 InputMapper* mapper = mMappers[i];
1155 mapper->configure(when, config, changes);
1156 mSources |= mapper->getSources();
1157 }
1158 }
1159}
1160
1161void InputDevice::reset(nsecs_t when) {
1162 size_t numMappers = mMappers.size();
1163 for (size_t i = 0; i < numMappers; i++) {
1164 InputMapper* mapper = mMappers[i];
1165 mapper->reset(when);
1166 }
1167
1168 mContext->updateGlobalMetaState();
1169
1170 notifyReset(when);
1171}
1172
1173void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1174 // Process all of the events in order for each mapper.
1175 // We cannot simply ask each mapper to process them in bulk because mappers may
1176 // have side-effects that must be interleaved. For example, joystick movement events and
1177 // gamepad button presses are handled by different mappers but they should be dispatched
1178 // in the order received.
1179 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001180 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001182 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1184 rawEvent->when);
1185#endif
1186
1187 if (mDropUntilNextSync) {
1188 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1189 mDropUntilNextSync = false;
1190#if DEBUG_RAW_EVENTS
1191 ALOGD("Recovered from input event buffer overrun.");
1192#endif
1193 } else {
1194#if DEBUG_RAW_EVENTS
1195 ALOGD("Dropped input event while waiting for next input sync.");
1196#endif
1197 }
1198 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
1199 ALOGI("Detected input event buffer overrun for device %s.", getName().string());
1200 mDropUntilNextSync = true;
1201 reset(rawEvent->when);
1202 } else {
1203 for (size_t i = 0; i < numMappers; i++) {
1204 InputMapper* mapper = mMappers[i];
1205 mapper->process(rawEvent);
1206 }
1207 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001208 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 }
1210}
1211
1212void InputDevice::timeoutExpired(nsecs_t when) {
1213 size_t numMappers = mMappers.size();
1214 for (size_t i = 0; i < numMappers; i++) {
1215 InputMapper* mapper = mMappers[i];
1216 mapper->timeoutExpired(when);
1217 }
1218}
1219
Michael Wright842500e2015-03-13 17:32:02 -07001220void InputDevice::updateExternalStylusState(const StylusState& state) {
1221 size_t numMappers = mMappers.size();
1222 for (size_t i = 0; i < numMappers; i++) {
1223 InputMapper* mapper = mMappers[i];
1224 mapper->updateExternalStylusState(state);
1225 }
1226}
1227
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1229 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001230 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231 size_t numMappers = mMappers.size();
1232 for (size_t i = 0; i < numMappers; i++) {
1233 InputMapper* mapper = mMappers[i];
1234 mapper->populateDeviceInfo(outDeviceInfo);
1235 }
1236}
1237
1238int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1239 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1240}
1241
1242int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1243 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1244}
1245
1246int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1247 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1248}
1249
1250int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1251 int32_t result = AKEY_STATE_UNKNOWN;
1252 size_t numMappers = mMappers.size();
1253 for (size_t i = 0; i < numMappers; i++) {
1254 InputMapper* mapper = mMappers[i];
1255 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1256 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1257 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1258 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1259 if (currentResult >= AKEY_STATE_DOWN) {
1260 return currentResult;
1261 } else if (currentResult == AKEY_STATE_UP) {
1262 result = currentResult;
1263 }
1264 }
1265 }
1266 return result;
1267}
1268
1269bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1270 const int32_t* keyCodes, uint8_t* outFlags) {
1271 bool result = false;
1272 size_t numMappers = mMappers.size();
1273 for (size_t i = 0; i < numMappers; i++) {
1274 InputMapper* mapper = mMappers[i];
1275 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1276 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1277 }
1278 }
1279 return result;
1280}
1281
1282void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1283 int32_t token) {
1284 size_t numMappers = mMappers.size();
1285 for (size_t i = 0; i < numMappers; i++) {
1286 InputMapper* mapper = mMappers[i];
1287 mapper->vibrate(pattern, patternSize, repeat, token);
1288 }
1289}
1290
1291void InputDevice::cancelVibrate(int32_t token) {
1292 size_t numMappers = mMappers.size();
1293 for (size_t i = 0; i < numMappers; i++) {
1294 InputMapper* mapper = mMappers[i];
1295 mapper->cancelVibrate(token);
1296 }
1297}
1298
Jeff Brownc9aa6282015-02-11 19:03:28 -08001299void InputDevice::cancelTouch(nsecs_t when) {
1300 size_t numMappers = mMappers.size();
1301 for (size_t i = 0; i < numMappers; i++) {
1302 InputMapper* mapper = mMappers[i];
1303 mapper->cancelTouch(when);
1304 }
1305}
1306
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307int32_t InputDevice::getMetaState() {
1308 int32_t result = 0;
1309 size_t numMappers = mMappers.size();
1310 for (size_t i = 0; i < numMappers; i++) {
1311 InputMapper* mapper = mMappers[i];
1312 result |= mapper->getMetaState();
1313 }
1314 return result;
1315}
1316
Andrii Kulian763a3a42016-03-08 10:46:16 -08001317void InputDevice::updateMetaState(int32_t keyCode) {
1318 size_t numMappers = mMappers.size();
1319 for (size_t i = 0; i < numMappers; i++) {
1320 mMappers[i]->updateMetaState(keyCode);
1321 }
1322}
1323
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324void InputDevice::fadePointer() {
1325 size_t numMappers = mMappers.size();
1326 for (size_t i = 0; i < numMappers; i++) {
1327 InputMapper* mapper = mMappers[i];
1328 mapper->fadePointer();
1329 }
1330}
1331
1332void InputDevice::bumpGeneration() {
1333 mGeneration = mContext->bumpGeneration();
1334}
1335
1336void InputDevice::notifyReset(nsecs_t when) {
1337 NotifyDeviceResetArgs args(when, mId);
1338 mContext->getListener()->notifyDeviceReset(&args);
1339}
1340
1341
1342// --- CursorButtonAccumulator ---
1343
1344CursorButtonAccumulator::CursorButtonAccumulator() {
1345 clearButtons();
1346}
1347
1348void CursorButtonAccumulator::reset(InputDevice* device) {
1349 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1350 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1351 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1352 mBtnBack = device->isKeyPressed(BTN_BACK);
1353 mBtnSide = device->isKeyPressed(BTN_SIDE);
1354 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1355 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1356 mBtnTask = device->isKeyPressed(BTN_TASK);
1357}
1358
1359void CursorButtonAccumulator::clearButtons() {
1360 mBtnLeft = 0;
1361 mBtnRight = 0;
1362 mBtnMiddle = 0;
1363 mBtnBack = 0;
1364 mBtnSide = 0;
1365 mBtnForward = 0;
1366 mBtnExtra = 0;
1367 mBtnTask = 0;
1368}
1369
1370void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1371 if (rawEvent->type == EV_KEY) {
1372 switch (rawEvent->code) {
1373 case BTN_LEFT:
1374 mBtnLeft = rawEvent->value;
1375 break;
1376 case BTN_RIGHT:
1377 mBtnRight = rawEvent->value;
1378 break;
1379 case BTN_MIDDLE:
1380 mBtnMiddle = rawEvent->value;
1381 break;
1382 case BTN_BACK:
1383 mBtnBack = rawEvent->value;
1384 break;
1385 case BTN_SIDE:
1386 mBtnSide = rawEvent->value;
1387 break;
1388 case BTN_FORWARD:
1389 mBtnForward = rawEvent->value;
1390 break;
1391 case BTN_EXTRA:
1392 mBtnExtra = rawEvent->value;
1393 break;
1394 case BTN_TASK:
1395 mBtnTask = rawEvent->value;
1396 break;
1397 }
1398 }
1399}
1400
1401uint32_t CursorButtonAccumulator::getButtonState() const {
1402 uint32_t result = 0;
1403 if (mBtnLeft) {
1404 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1405 }
1406 if (mBtnRight) {
1407 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1408 }
1409 if (mBtnMiddle) {
1410 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1411 }
1412 if (mBtnBack || mBtnSide) {
1413 result |= AMOTION_EVENT_BUTTON_BACK;
1414 }
1415 if (mBtnForward || mBtnExtra) {
1416 result |= AMOTION_EVENT_BUTTON_FORWARD;
1417 }
1418 return result;
1419}
1420
1421
1422// --- CursorMotionAccumulator ---
1423
1424CursorMotionAccumulator::CursorMotionAccumulator() {
1425 clearRelativeAxes();
1426}
1427
1428void CursorMotionAccumulator::reset(InputDevice* device) {
1429 clearRelativeAxes();
1430}
1431
1432void CursorMotionAccumulator::clearRelativeAxes() {
1433 mRelX = 0;
1434 mRelY = 0;
1435}
1436
1437void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1438 if (rawEvent->type == EV_REL) {
1439 switch (rawEvent->code) {
1440 case REL_X:
1441 mRelX = rawEvent->value;
1442 break;
1443 case REL_Y:
1444 mRelY = rawEvent->value;
1445 break;
1446 }
1447 }
1448}
1449
1450void CursorMotionAccumulator::finishSync() {
1451 clearRelativeAxes();
1452}
1453
1454
1455// --- CursorScrollAccumulator ---
1456
1457CursorScrollAccumulator::CursorScrollAccumulator() :
1458 mHaveRelWheel(false), mHaveRelHWheel(false) {
1459 clearRelativeAxes();
1460}
1461
1462void CursorScrollAccumulator::configure(InputDevice* device) {
1463 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1464 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1465}
1466
1467void CursorScrollAccumulator::reset(InputDevice* device) {
1468 clearRelativeAxes();
1469}
1470
1471void CursorScrollAccumulator::clearRelativeAxes() {
1472 mRelWheel = 0;
1473 mRelHWheel = 0;
1474}
1475
1476void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1477 if (rawEvent->type == EV_REL) {
1478 switch (rawEvent->code) {
1479 case REL_WHEEL:
1480 mRelWheel = rawEvent->value;
1481 break;
1482 case REL_HWHEEL:
1483 mRelHWheel = rawEvent->value;
1484 break;
1485 }
1486 }
1487}
1488
1489void CursorScrollAccumulator::finishSync() {
1490 clearRelativeAxes();
1491}
1492
1493
1494// --- TouchButtonAccumulator ---
1495
1496TouchButtonAccumulator::TouchButtonAccumulator() :
1497 mHaveBtnTouch(false), mHaveStylus(false) {
1498 clearButtons();
1499}
1500
1501void TouchButtonAccumulator::configure(InputDevice* device) {
1502 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1503 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1504 || device->hasKey(BTN_TOOL_RUBBER)
1505 || device->hasKey(BTN_TOOL_BRUSH)
1506 || device->hasKey(BTN_TOOL_PENCIL)
1507 || device->hasKey(BTN_TOOL_AIRBRUSH);
1508}
1509
1510void TouchButtonAccumulator::reset(InputDevice* device) {
1511 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1512 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001513 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1514 mBtnStylus2 =
1515 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1517 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1518 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1519 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1520 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1521 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1522 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1523 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1524 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1525 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1526 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1527}
1528
1529void TouchButtonAccumulator::clearButtons() {
1530 mBtnTouch = 0;
1531 mBtnStylus = 0;
1532 mBtnStylus2 = 0;
1533 mBtnToolFinger = 0;
1534 mBtnToolPen = 0;
1535 mBtnToolRubber = 0;
1536 mBtnToolBrush = 0;
1537 mBtnToolPencil = 0;
1538 mBtnToolAirbrush = 0;
1539 mBtnToolMouse = 0;
1540 mBtnToolLens = 0;
1541 mBtnToolDoubleTap = 0;
1542 mBtnToolTripleTap = 0;
1543 mBtnToolQuadTap = 0;
1544}
1545
1546void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1547 if (rawEvent->type == EV_KEY) {
1548 switch (rawEvent->code) {
1549 case BTN_TOUCH:
1550 mBtnTouch = rawEvent->value;
1551 break;
1552 case BTN_STYLUS:
1553 mBtnStylus = rawEvent->value;
1554 break;
1555 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001556 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 mBtnStylus2 = rawEvent->value;
1558 break;
1559 case BTN_TOOL_FINGER:
1560 mBtnToolFinger = rawEvent->value;
1561 break;
1562 case BTN_TOOL_PEN:
1563 mBtnToolPen = rawEvent->value;
1564 break;
1565 case BTN_TOOL_RUBBER:
1566 mBtnToolRubber = rawEvent->value;
1567 break;
1568 case BTN_TOOL_BRUSH:
1569 mBtnToolBrush = rawEvent->value;
1570 break;
1571 case BTN_TOOL_PENCIL:
1572 mBtnToolPencil = rawEvent->value;
1573 break;
1574 case BTN_TOOL_AIRBRUSH:
1575 mBtnToolAirbrush = rawEvent->value;
1576 break;
1577 case BTN_TOOL_MOUSE:
1578 mBtnToolMouse = rawEvent->value;
1579 break;
1580 case BTN_TOOL_LENS:
1581 mBtnToolLens = rawEvent->value;
1582 break;
1583 case BTN_TOOL_DOUBLETAP:
1584 mBtnToolDoubleTap = rawEvent->value;
1585 break;
1586 case BTN_TOOL_TRIPLETAP:
1587 mBtnToolTripleTap = rawEvent->value;
1588 break;
1589 case BTN_TOOL_QUADTAP:
1590 mBtnToolQuadTap = rawEvent->value;
1591 break;
1592 }
1593 }
1594}
1595
1596uint32_t TouchButtonAccumulator::getButtonState() const {
1597 uint32_t result = 0;
1598 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001599 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 }
1601 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001602 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 }
1604 return result;
1605}
1606
1607int32_t TouchButtonAccumulator::getToolType() const {
1608 if (mBtnToolMouse || mBtnToolLens) {
1609 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1610 }
1611 if (mBtnToolRubber) {
1612 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1613 }
1614 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1615 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1616 }
1617 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1618 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1619 }
1620 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1621}
1622
1623bool TouchButtonAccumulator::isToolActive() const {
1624 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1625 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1626 || mBtnToolMouse || mBtnToolLens
1627 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1628}
1629
1630bool TouchButtonAccumulator::isHovering() const {
1631 return mHaveBtnTouch && !mBtnTouch;
1632}
1633
1634bool TouchButtonAccumulator::hasStylus() const {
1635 return mHaveStylus;
1636}
1637
1638
1639// --- RawPointerAxes ---
1640
1641RawPointerAxes::RawPointerAxes() {
1642 clear();
1643}
1644
1645void RawPointerAxes::clear() {
1646 x.clear();
1647 y.clear();
1648 pressure.clear();
1649 touchMajor.clear();
1650 touchMinor.clear();
1651 toolMajor.clear();
1652 toolMinor.clear();
1653 orientation.clear();
1654 distance.clear();
1655 tiltX.clear();
1656 tiltY.clear();
1657 trackingId.clear();
1658 slot.clear();
1659}
1660
1661
1662// --- RawPointerData ---
1663
1664RawPointerData::RawPointerData() {
1665 clear();
1666}
1667
1668void RawPointerData::clear() {
1669 pointerCount = 0;
1670 clearIdBits();
1671}
1672
1673void RawPointerData::copyFrom(const RawPointerData& other) {
1674 pointerCount = other.pointerCount;
1675 hoveringIdBits = other.hoveringIdBits;
1676 touchingIdBits = other.touchingIdBits;
1677
1678 for (uint32_t i = 0; i < pointerCount; i++) {
1679 pointers[i] = other.pointers[i];
1680
1681 int id = pointers[i].id;
1682 idToIndex[id] = other.idToIndex[id];
1683 }
1684}
1685
1686void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1687 float x = 0, y = 0;
1688 uint32_t count = touchingIdBits.count();
1689 if (count) {
1690 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1691 uint32_t id = idBits.clearFirstMarkedBit();
1692 const Pointer& pointer = pointerForId(id);
1693 x += pointer.x;
1694 y += pointer.y;
1695 }
1696 x /= count;
1697 y /= count;
1698 }
1699 *outX = x;
1700 *outY = y;
1701}
1702
1703
1704// --- CookedPointerData ---
1705
1706CookedPointerData::CookedPointerData() {
1707 clear();
1708}
1709
1710void CookedPointerData::clear() {
1711 pointerCount = 0;
1712 hoveringIdBits.clear();
1713 touchingIdBits.clear();
1714}
1715
1716void CookedPointerData::copyFrom(const CookedPointerData& other) {
1717 pointerCount = other.pointerCount;
1718 hoveringIdBits = other.hoveringIdBits;
1719 touchingIdBits = other.touchingIdBits;
1720
1721 for (uint32_t i = 0; i < pointerCount; i++) {
1722 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1723 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1724
1725 int id = pointerProperties[i].id;
1726 idToIndex[id] = other.idToIndex[id];
1727 }
1728}
1729
1730
1731// --- SingleTouchMotionAccumulator ---
1732
1733SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1734 clearAbsoluteAxes();
1735}
1736
1737void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1738 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1739 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1740 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1741 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1742 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1743 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1744 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1745}
1746
1747void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1748 mAbsX = 0;
1749 mAbsY = 0;
1750 mAbsPressure = 0;
1751 mAbsToolWidth = 0;
1752 mAbsDistance = 0;
1753 mAbsTiltX = 0;
1754 mAbsTiltY = 0;
1755}
1756
1757void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1758 if (rawEvent->type == EV_ABS) {
1759 switch (rawEvent->code) {
1760 case ABS_X:
1761 mAbsX = rawEvent->value;
1762 break;
1763 case ABS_Y:
1764 mAbsY = rawEvent->value;
1765 break;
1766 case ABS_PRESSURE:
1767 mAbsPressure = rawEvent->value;
1768 break;
1769 case ABS_TOOL_WIDTH:
1770 mAbsToolWidth = rawEvent->value;
1771 break;
1772 case ABS_DISTANCE:
1773 mAbsDistance = rawEvent->value;
1774 break;
1775 case ABS_TILT_X:
1776 mAbsTiltX = rawEvent->value;
1777 break;
1778 case ABS_TILT_Y:
1779 mAbsTiltY = rawEvent->value;
1780 break;
1781 }
1782 }
1783}
1784
1785
1786// --- MultiTouchMotionAccumulator ---
1787
1788MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1789 mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
1790 mHaveStylus(false) {
1791}
1792
1793MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1794 delete[] mSlots;
1795}
1796
1797void MultiTouchMotionAccumulator::configure(InputDevice* device,
1798 size_t slotCount, bool usingSlotsProtocol) {
1799 mSlotCount = slotCount;
1800 mUsingSlotsProtocol = usingSlotsProtocol;
1801 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1802
1803 delete[] mSlots;
1804 mSlots = new Slot[slotCount];
1805}
1806
1807void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1808 // Unfortunately there is no way to read the initial contents of the slots.
1809 // So when we reset the accumulator, we must assume they are all zeroes.
1810 if (mUsingSlotsProtocol) {
1811 // Query the driver for the current slot index and use it as the initial slot
1812 // before we start reading events from the device. It is possible that the
1813 // current slot index will not be the same as it was when the first event was
1814 // written into the evdev buffer, which means the input mapper could start
1815 // out of sync with the initial state of the events in the evdev buffer.
1816 // In the extremely unlikely case that this happens, the data from
1817 // two slots will be confused until the next ABS_MT_SLOT event is received.
1818 // This can cause the touch point to "jump", but at least there will be
1819 // no stuck touches.
1820 int32_t initialSlot;
1821 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1822 ABS_MT_SLOT, &initialSlot);
1823 if (status) {
1824 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1825 initialSlot = -1;
1826 }
1827 clearSlots(initialSlot);
1828 } else {
1829 clearSlots(-1);
1830 }
1831}
1832
1833void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1834 if (mSlots) {
1835 for (size_t i = 0; i < mSlotCount; i++) {
1836 mSlots[i].clear();
1837 }
1838 }
1839 mCurrentSlot = initialSlot;
1840}
1841
1842void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1843 if (rawEvent->type == EV_ABS) {
1844 bool newSlot = false;
1845 if (mUsingSlotsProtocol) {
1846 if (rawEvent->code == ABS_MT_SLOT) {
1847 mCurrentSlot = rawEvent->value;
1848 newSlot = true;
1849 }
1850 } else if (mCurrentSlot < 0) {
1851 mCurrentSlot = 0;
1852 }
1853
1854 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1855#if DEBUG_POINTERS
1856 if (newSlot) {
1857 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001858 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001859 mCurrentSlot, mSlotCount - 1);
1860 }
1861#endif
1862 } else {
1863 Slot* slot = &mSlots[mCurrentSlot];
1864
1865 switch (rawEvent->code) {
1866 case ABS_MT_POSITION_X:
1867 slot->mInUse = true;
1868 slot->mAbsMTPositionX = rawEvent->value;
1869 break;
1870 case ABS_MT_POSITION_Y:
1871 slot->mInUse = true;
1872 slot->mAbsMTPositionY = rawEvent->value;
1873 break;
1874 case ABS_MT_TOUCH_MAJOR:
1875 slot->mInUse = true;
1876 slot->mAbsMTTouchMajor = rawEvent->value;
1877 break;
1878 case ABS_MT_TOUCH_MINOR:
1879 slot->mInUse = true;
1880 slot->mAbsMTTouchMinor = rawEvent->value;
1881 slot->mHaveAbsMTTouchMinor = true;
1882 break;
1883 case ABS_MT_WIDTH_MAJOR:
1884 slot->mInUse = true;
1885 slot->mAbsMTWidthMajor = rawEvent->value;
1886 break;
1887 case ABS_MT_WIDTH_MINOR:
1888 slot->mInUse = true;
1889 slot->mAbsMTWidthMinor = rawEvent->value;
1890 slot->mHaveAbsMTWidthMinor = true;
1891 break;
1892 case ABS_MT_ORIENTATION:
1893 slot->mInUse = true;
1894 slot->mAbsMTOrientation = rawEvent->value;
1895 break;
1896 case ABS_MT_TRACKING_ID:
1897 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1898 // The slot is no longer in use but it retains its previous contents,
1899 // which may be reused for subsequent touches.
1900 slot->mInUse = false;
1901 } else {
1902 slot->mInUse = true;
1903 slot->mAbsMTTrackingId = rawEvent->value;
1904 }
1905 break;
1906 case ABS_MT_PRESSURE:
1907 slot->mInUse = true;
1908 slot->mAbsMTPressure = rawEvent->value;
1909 break;
1910 case ABS_MT_DISTANCE:
1911 slot->mInUse = true;
1912 slot->mAbsMTDistance = rawEvent->value;
1913 break;
1914 case ABS_MT_TOOL_TYPE:
1915 slot->mInUse = true;
1916 slot->mAbsMTToolType = rawEvent->value;
1917 slot->mHaveAbsMTToolType = true;
1918 break;
1919 }
1920 }
1921 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1922 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1923 mCurrentSlot += 1;
1924 }
1925}
1926
1927void MultiTouchMotionAccumulator::finishSync() {
1928 if (!mUsingSlotsProtocol) {
1929 clearSlots(-1);
1930 }
1931}
1932
1933bool MultiTouchMotionAccumulator::hasStylus() const {
1934 return mHaveStylus;
1935}
1936
1937
1938// --- MultiTouchMotionAccumulator::Slot ---
1939
1940MultiTouchMotionAccumulator::Slot::Slot() {
1941 clear();
1942}
1943
1944void MultiTouchMotionAccumulator::Slot::clear() {
1945 mInUse = false;
1946 mHaveAbsMTTouchMinor = false;
1947 mHaveAbsMTWidthMinor = false;
1948 mHaveAbsMTToolType = false;
1949 mAbsMTPositionX = 0;
1950 mAbsMTPositionY = 0;
1951 mAbsMTTouchMajor = 0;
1952 mAbsMTTouchMinor = 0;
1953 mAbsMTWidthMajor = 0;
1954 mAbsMTWidthMinor = 0;
1955 mAbsMTOrientation = 0;
1956 mAbsMTTrackingId = -1;
1957 mAbsMTPressure = 0;
1958 mAbsMTDistance = 0;
1959 mAbsMTToolType = 0;
1960}
1961
1962int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1963 if (mHaveAbsMTToolType) {
1964 switch (mAbsMTToolType) {
1965 case MT_TOOL_FINGER:
1966 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1967 case MT_TOOL_PEN:
1968 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1969 }
1970 }
1971 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1972}
1973
1974
1975// --- InputMapper ---
1976
1977InputMapper::InputMapper(InputDevice* device) :
1978 mDevice(device), mContext(device->getContext()) {
1979}
1980
1981InputMapper::~InputMapper() {
1982}
1983
1984void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1985 info->addSource(getSources());
1986}
1987
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001988void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989}
1990
1991void InputMapper::configure(nsecs_t when,
1992 const InputReaderConfiguration* config, uint32_t changes) {
1993}
1994
1995void InputMapper::reset(nsecs_t when) {
1996}
1997
1998void InputMapper::timeoutExpired(nsecs_t when) {
1999}
2000
2001int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2002 return AKEY_STATE_UNKNOWN;
2003}
2004
2005int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2006 return AKEY_STATE_UNKNOWN;
2007}
2008
2009int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2010 return AKEY_STATE_UNKNOWN;
2011}
2012
2013bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2014 const int32_t* keyCodes, uint8_t* outFlags) {
2015 return false;
2016}
2017
2018void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2019 int32_t token) {
2020}
2021
2022void InputMapper::cancelVibrate(int32_t token) {
2023}
2024
Jeff Brownc9aa6282015-02-11 19:03:28 -08002025void InputMapper::cancelTouch(nsecs_t when) {
2026}
2027
Michael Wrightd02c5b62014-02-10 15:10:22 -08002028int32_t InputMapper::getMetaState() {
2029 return 0;
2030}
2031
Andrii Kulian763a3a42016-03-08 10:46:16 -08002032void InputMapper::updateMetaState(int32_t keyCode) {
2033}
2034
Michael Wright842500e2015-03-13 17:32:02 -07002035void InputMapper::updateExternalStylusState(const StylusState& state) {
2036
2037}
2038
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039void InputMapper::fadePointer() {
2040}
2041
2042status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2043 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2044}
2045
2046void InputMapper::bumpGeneration() {
2047 mDevice->bumpGeneration();
2048}
2049
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002050void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 const RawAbsoluteAxisInfo& axis, const char* name) {
2052 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002053 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2055 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002056 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 }
2058}
2059
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002060void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2061 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2062 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2063 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2064 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002065}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002066
2067// --- SwitchInputMapper ---
2068
2069SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002070 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071}
2072
2073SwitchInputMapper::~SwitchInputMapper() {
2074}
2075
2076uint32_t SwitchInputMapper::getSources() {
2077 return AINPUT_SOURCE_SWITCH;
2078}
2079
2080void SwitchInputMapper::process(const RawEvent* rawEvent) {
2081 switch (rawEvent->type) {
2082 case EV_SW:
2083 processSwitch(rawEvent->code, rawEvent->value);
2084 break;
2085
2086 case EV_SYN:
2087 if (rawEvent->code == SYN_REPORT) {
2088 sync(rawEvent->when);
2089 }
2090 }
2091}
2092
2093void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2094 if (switchCode >= 0 && switchCode < 32) {
2095 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002096 mSwitchValues |= 1 << switchCode;
2097 } else {
2098 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 }
2100 mUpdatedSwitchMask |= 1 << switchCode;
2101 }
2102}
2103
2104void SwitchInputMapper::sync(nsecs_t when) {
2105 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002106 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002107 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 getListener()->notifySwitch(&args);
2109
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 mUpdatedSwitchMask = 0;
2111 }
2112}
2113
2114int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2115 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2116}
2117
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002118void SwitchInputMapper::dump(std::string& dump) {
2119 dump += INDENT2 "Switch Input Mapper:\n";
2120 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002121}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002122
2123// --- VibratorInputMapper ---
2124
2125VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2126 InputMapper(device), mVibrating(false) {
2127}
2128
2129VibratorInputMapper::~VibratorInputMapper() {
2130}
2131
2132uint32_t VibratorInputMapper::getSources() {
2133 return 0;
2134}
2135
2136void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2137 InputMapper::populateDeviceInfo(info);
2138
2139 info->setVibrator(true);
2140}
2141
2142void VibratorInputMapper::process(const RawEvent* rawEvent) {
2143 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2144}
2145
2146void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2147 int32_t token) {
2148#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002149 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 for (size_t i = 0; i < patternSize; i++) {
2151 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002152 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002154 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002156 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002157 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158#endif
2159
2160 mVibrating = true;
2161 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2162 mPatternSize = patternSize;
2163 mRepeat = repeat;
2164 mToken = token;
2165 mIndex = -1;
2166
2167 nextStep();
2168}
2169
2170void VibratorInputMapper::cancelVibrate(int32_t token) {
2171#if DEBUG_VIBRATOR
2172 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2173#endif
2174
2175 if (mVibrating && mToken == token) {
2176 stopVibrating();
2177 }
2178}
2179
2180void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2181 if (mVibrating) {
2182 if (when >= mNextStepTime) {
2183 nextStep();
2184 } else {
2185 getContext()->requestTimeoutAtTime(mNextStepTime);
2186 }
2187 }
2188}
2189
2190void VibratorInputMapper::nextStep() {
2191 mIndex += 1;
2192 if (size_t(mIndex) >= mPatternSize) {
2193 if (mRepeat < 0) {
2194 // We are done.
2195 stopVibrating();
2196 return;
2197 }
2198 mIndex = mRepeat;
2199 }
2200
2201 bool vibratorOn = mIndex & 1;
2202 nsecs_t duration = mPattern[mIndex];
2203 if (vibratorOn) {
2204#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002205 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002206#endif
2207 getEventHub()->vibrate(getDeviceId(), duration);
2208 } else {
2209#if DEBUG_VIBRATOR
2210 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2211#endif
2212 getEventHub()->cancelVibrate(getDeviceId());
2213 }
2214 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2215 mNextStepTime = now + duration;
2216 getContext()->requestTimeoutAtTime(mNextStepTime);
2217#if DEBUG_VIBRATOR
2218 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2219#endif
2220}
2221
2222void VibratorInputMapper::stopVibrating() {
2223 mVibrating = false;
2224#if DEBUG_VIBRATOR
2225 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2226#endif
2227 getEventHub()->cancelVibrate(getDeviceId());
2228}
2229
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002230void VibratorInputMapper::dump(std::string& dump) {
2231 dump += INDENT2 "Vibrator Input Mapper:\n";
2232 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233}
2234
2235
2236// --- KeyboardInputMapper ---
2237
2238KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2239 uint32_t source, int32_t keyboardType) :
2240 InputMapper(device), mSource(source),
2241 mKeyboardType(keyboardType) {
2242}
2243
2244KeyboardInputMapper::~KeyboardInputMapper() {
2245}
2246
2247uint32_t KeyboardInputMapper::getSources() {
2248 return mSource;
2249}
2250
2251void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2252 InputMapper::populateDeviceInfo(info);
2253
2254 info->setKeyboardType(mKeyboardType);
2255 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2256}
2257
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002258void KeyboardInputMapper::dump(std::string& dump) {
2259 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002261 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2262 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2263 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2264 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2265 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266}
2267
2268
2269void KeyboardInputMapper::configure(nsecs_t when,
2270 const InputReaderConfiguration* config, uint32_t changes) {
2271 InputMapper::configure(when, config, changes);
2272
2273 if (!changes) { // first time only
2274 // Configure basic parameters.
2275 configureParameters();
2276 }
2277
2278 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2279 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2280 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002281 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 mOrientation = v.orientation;
2283 } else {
2284 mOrientation = DISPLAY_ORIENTATION_0;
2285 }
2286 } else {
2287 mOrientation = DISPLAY_ORIENTATION_0;
2288 }
2289 }
2290}
2291
Ivan Podogovb9afef32017-02-13 15:34:32 +00002292static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2293 int32_t mapped = 0;
2294 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2295 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2296 if (stemKeyRotationMap[i][0] == keyCode) {
2297 stemKeyRotationMap[i][1] = mapped;
2298 return;
2299 }
2300 }
2301 }
2302}
2303
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304void KeyboardInputMapper::configureParameters() {
2305 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002306 const PropertyMap& config = getDevice()->getConfiguration();
2307 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 mParameters.orientationAware);
2309
2310 mParameters.hasAssociatedDisplay = false;
2311 if (mParameters.orientationAware) {
2312 mParameters.hasAssociatedDisplay = true;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002313
2314 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2315 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2316 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2317 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002318 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002319
2320 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002321 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002322 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002323}
2324
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002325void KeyboardInputMapper::dumpParameters(std::string& dump) {
2326 dump += INDENT3 "Parameters:\n";
2327 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002328 toString(mParameters.hasAssociatedDisplay));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002329 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002331 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002332 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333}
2334
2335void KeyboardInputMapper::reset(nsecs_t when) {
2336 mMetaState = AMETA_NONE;
2337 mDownTime = 0;
2338 mKeyDowns.clear();
2339 mCurrentHidUsage = 0;
2340
2341 resetLedState();
2342
2343 InputMapper::reset(when);
2344}
2345
2346void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2347 switch (rawEvent->type) {
2348 case EV_KEY: {
2349 int32_t scanCode = rawEvent->code;
2350 int32_t usageCode = mCurrentHidUsage;
2351 mCurrentHidUsage = 0;
2352
2353 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002354 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
2356 break;
2357 }
2358 case EV_MSC: {
2359 if (rawEvent->code == MSC_SCAN) {
2360 mCurrentHidUsage = rawEvent->value;
2361 }
2362 break;
2363 }
2364 case EV_SYN: {
2365 if (rawEvent->code == SYN_REPORT) {
2366 mCurrentHidUsage = 0;
2367 }
2368 }
2369 }
2370}
2371
2372bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2373 return scanCode < BTN_MOUSE
2374 || scanCode >= KEY_OK
2375 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2376 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2377}
2378
Michael Wright58ba9882017-07-26 16:19:11 +01002379bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2380 switch (keyCode) {
2381 case AKEYCODE_MEDIA_PLAY:
2382 case AKEYCODE_MEDIA_PAUSE:
2383 case AKEYCODE_MEDIA_PLAY_PAUSE:
2384 case AKEYCODE_MUTE:
2385 case AKEYCODE_HEADSETHOOK:
2386 case AKEYCODE_MEDIA_STOP:
2387 case AKEYCODE_MEDIA_NEXT:
2388 case AKEYCODE_MEDIA_PREVIOUS:
2389 case AKEYCODE_MEDIA_REWIND:
2390 case AKEYCODE_MEDIA_RECORD:
2391 case AKEYCODE_MEDIA_FAST_FORWARD:
2392 case AKEYCODE_MEDIA_SKIP_FORWARD:
2393 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2394 case AKEYCODE_MEDIA_STEP_FORWARD:
2395 case AKEYCODE_MEDIA_STEP_BACKWARD:
2396 case AKEYCODE_MEDIA_AUDIO_TRACK:
2397 case AKEYCODE_VOLUME_UP:
2398 case AKEYCODE_VOLUME_DOWN:
2399 case AKEYCODE_VOLUME_MUTE:
2400 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2401 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2402 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2403 return true;
2404 }
2405 return false;
2406}
2407
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002408void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2409 int32_t usageCode) {
2410 int32_t keyCode;
2411 int32_t keyMetaState;
2412 uint32_t policyFlags;
2413
2414 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2415 &keyCode, &keyMetaState, &policyFlags)) {
2416 keyCode = AKEYCODE_UNKNOWN;
2417 keyMetaState = mMetaState;
2418 policyFlags = 0;
2419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420
2421 if (down) {
2422 // Rotate key codes according to orientation if needed.
2423 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2424 keyCode = rotateKeyCode(keyCode, mOrientation);
2425 }
2426
2427 // Add key down.
2428 ssize_t keyDownIndex = findKeyDown(scanCode);
2429 if (keyDownIndex >= 0) {
2430 // key repeat, be sure to use same keycode as before in case of rotation
2431 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2432 } else {
2433 // key down
2434 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2435 && mContext->shouldDropVirtualKey(when,
2436 getDevice(), keyCode, scanCode)) {
2437 return;
2438 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002439 if (policyFlags & POLICY_FLAG_GESTURE) {
2440 mDevice->cancelTouch(when);
2441 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442
2443 mKeyDowns.push();
2444 KeyDown& keyDown = mKeyDowns.editTop();
2445 keyDown.keyCode = keyCode;
2446 keyDown.scanCode = scanCode;
2447 }
2448
2449 mDownTime = when;
2450 } else {
2451 // Remove key down.
2452 ssize_t keyDownIndex = findKeyDown(scanCode);
2453 if (keyDownIndex >= 0) {
2454 // key up, be sure to use same keycode as before in case of rotation
2455 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2456 mKeyDowns.removeAt(size_t(keyDownIndex));
2457 } else {
2458 // key was not actually down
2459 ALOGI("Dropping key up from device %s because the key was not down. "
2460 "keyCode=%d, scanCode=%d",
2461 getDeviceName().string(), keyCode, scanCode);
2462 return;
2463 }
2464 }
2465
Andrii Kulian763a3a42016-03-08 10:46:16 -08002466 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002467 // If global meta state changed send it along with the key.
2468 // If it has not changed then we'll use what keymap gave us,
2469 // since key replacement logic might temporarily reset a few
2470 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002471 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002472 }
2473
2474 nsecs_t downTime = mDownTime;
2475
2476 // Key down on external an keyboard should wake the device.
2477 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2478 // For internal keyboards, the key layout file should specify the policy flags for
2479 // each wake key individually.
2480 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002481 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002482 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002483 }
2484
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002485 if (mParameters.handlesKeyRepeat) {
2486 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2487 }
2488
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2490 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002491 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492 getListener()->notifyKey(&args);
2493}
2494
2495ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2496 size_t n = mKeyDowns.size();
2497 for (size_t i = 0; i < n; i++) {
2498 if (mKeyDowns[i].scanCode == scanCode) {
2499 return i;
2500 }
2501 }
2502 return -1;
2503}
2504
2505int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2506 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2507}
2508
2509int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2510 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2511}
2512
2513bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2514 const int32_t* keyCodes, uint8_t* outFlags) {
2515 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2516}
2517
2518int32_t KeyboardInputMapper::getMetaState() {
2519 return mMetaState;
2520}
2521
Andrii Kulian763a3a42016-03-08 10:46:16 -08002522void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2523 updateMetaStateIfNeeded(keyCode, false);
2524}
2525
2526bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2527 int32_t oldMetaState = mMetaState;
2528 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2529 bool metaStateChanged = oldMetaState != newMetaState;
2530 if (metaStateChanged) {
2531 mMetaState = newMetaState;
2532 updateLedState(false);
2533
2534 getContext()->updateGlobalMetaState();
2535 }
2536
2537 return metaStateChanged;
2538}
2539
Michael Wrightd02c5b62014-02-10 15:10:22 -08002540void KeyboardInputMapper::resetLedState() {
2541 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2542 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2543 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2544
2545 updateLedState(true);
2546}
2547
2548void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2549 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2550 ledState.on = false;
2551}
2552
2553void KeyboardInputMapper::updateLedState(bool reset) {
2554 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2555 AMETA_CAPS_LOCK_ON, reset);
2556 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2557 AMETA_NUM_LOCK_ON, reset);
2558 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2559 AMETA_SCROLL_LOCK_ON, reset);
2560}
2561
2562void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2563 int32_t led, int32_t modifier, bool reset) {
2564 if (ledState.avail) {
2565 bool desiredState = (mMetaState & modifier) != 0;
2566 if (reset || ledState.on != desiredState) {
2567 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2568 ledState.on = desiredState;
2569 }
2570 }
2571}
2572
2573
2574// --- CursorInputMapper ---
2575
2576CursorInputMapper::CursorInputMapper(InputDevice* device) :
2577 InputMapper(device) {
2578}
2579
2580CursorInputMapper::~CursorInputMapper() {
2581}
2582
2583uint32_t CursorInputMapper::getSources() {
2584 return mSource;
2585}
2586
2587void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2588 InputMapper::populateDeviceInfo(info);
2589
2590 if (mParameters.mode == Parameters::MODE_POINTER) {
2591 float minX, minY, maxX, maxY;
2592 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2593 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2594 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2595 }
2596 } else {
2597 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2598 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2599 }
2600 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2601
2602 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2603 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2604 }
2605 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2606 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2607 }
2608}
2609
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002610void CursorInputMapper::dump(std::string& dump) {
2611 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002612 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002613 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2614 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2615 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2616 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2617 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002619 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002621 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2622 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2623 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2624 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2625 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2626 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627}
2628
2629void CursorInputMapper::configure(nsecs_t when,
2630 const InputReaderConfiguration* config, uint32_t changes) {
2631 InputMapper::configure(when, config, changes);
2632
2633 if (!changes) { // first time only
2634 mCursorScrollAccumulator.configure(getDevice());
2635
2636 // Configure basic parameters.
2637 configureParameters();
2638
2639 // Configure device mode.
2640 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002641 case Parameters::MODE_POINTER_RELATIVE:
2642 // Should not happen during first time configuration.
2643 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2644 mParameters.mode = Parameters::MODE_POINTER;
2645 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 case Parameters::MODE_POINTER:
2647 mSource = AINPUT_SOURCE_MOUSE;
2648 mXPrecision = 1.0f;
2649 mYPrecision = 1.0f;
2650 mXScale = 1.0f;
2651 mYScale = 1.0f;
2652 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2653 break;
2654 case Parameters::MODE_NAVIGATION:
2655 mSource = AINPUT_SOURCE_TRACKBALL;
2656 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2657 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2658 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2659 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2660 break;
2661 }
2662
2663 mVWheelScale = 1.0f;
2664 mHWheelScale = 1.0f;
2665 }
2666
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002667 if ((!changes && config->pointerCapture)
2668 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2669 if (config->pointerCapture) {
2670 if (mParameters.mode == Parameters::MODE_POINTER) {
2671 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2672 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2673 // Keep PointerController around in order to preserve the pointer position.
2674 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2675 } else {
2676 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2677 }
2678 } else {
2679 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2680 mParameters.mode = Parameters::MODE_POINTER;
2681 mSource = AINPUT_SOURCE_MOUSE;
2682 } else {
2683 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2684 }
2685 }
2686 bumpGeneration();
2687 if (changes) {
2688 getDevice()->notifyReset(when);
2689 }
2690 }
2691
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2693 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2694 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2695 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2696 }
2697
2698 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2699 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2700 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002701 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 mOrientation = v.orientation;
2703 } else {
2704 mOrientation = DISPLAY_ORIENTATION_0;
2705 }
2706 } else {
2707 mOrientation = DISPLAY_ORIENTATION_0;
2708 }
2709 bumpGeneration();
2710 }
2711}
2712
2713void CursorInputMapper::configureParameters() {
2714 mParameters.mode = Parameters::MODE_POINTER;
2715 String8 cursorModeString;
2716 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2717 if (cursorModeString == "navigation") {
2718 mParameters.mode = Parameters::MODE_NAVIGATION;
2719 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2720 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2721 }
2722 }
2723
2724 mParameters.orientationAware = false;
2725 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2726 mParameters.orientationAware);
2727
2728 mParameters.hasAssociatedDisplay = false;
2729 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2730 mParameters.hasAssociatedDisplay = true;
2731 }
2732}
2733
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002734void CursorInputMapper::dumpParameters(std::string& dump) {
2735 dump += INDENT3 "Parameters:\n";
2736 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737 toString(mParameters.hasAssociatedDisplay));
2738
2739 switch (mParameters.mode) {
2740 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002741 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002743 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002744 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002745 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002747 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002748 break;
2749 default:
2750 ALOG_ASSERT(false);
2751 }
2752
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002753 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754 toString(mParameters.orientationAware));
2755}
2756
2757void CursorInputMapper::reset(nsecs_t when) {
2758 mButtonState = 0;
2759 mDownTime = 0;
2760
2761 mPointerVelocityControl.reset();
2762 mWheelXVelocityControl.reset();
2763 mWheelYVelocityControl.reset();
2764
2765 mCursorButtonAccumulator.reset(getDevice());
2766 mCursorMotionAccumulator.reset(getDevice());
2767 mCursorScrollAccumulator.reset(getDevice());
2768
2769 InputMapper::reset(when);
2770}
2771
2772void CursorInputMapper::process(const RawEvent* rawEvent) {
2773 mCursorButtonAccumulator.process(rawEvent);
2774 mCursorMotionAccumulator.process(rawEvent);
2775 mCursorScrollAccumulator.process(rawEvent);
2776
2777 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2778 sync(rawEvent->when);
2779 }
2780}
2781
2782void CursorInputMapper::sync(nsecs_t when) {
2783 int32_t lastButtonState = mButtonState;
2784 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2785 mButtonState = currentButtonState;
2786
2787 bool wasDown = isPointerDown(lastButtonState);
2788 bool down = isPointerDown(currentButtonState);
2789 bool downChanged;
2790 if (!wasDown && down) {
2791 mDownTime = when;
2792 downChanged = true;
2793 } else if (wasDown && !down) {
2794 downChanged = true;
2795 } else {
2796 downChanged = false;
2797 }
2798 nsecs_t downTime = mDownTime;
2799 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002800 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2801 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802
2803 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2804 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2805 bool moved = deltaX != 0 || deltaY != 0;
2806
2807 // Rotate delta according to orientation if needed.
2808 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2809 && (deltaX != 0.0f || deltaY != 0.0f)) {
2810 rotateDelta(mOrientation, &deltaX, &deltaY);
2811 }
2812
2813 // Move the pointer.
2814 PointerProperties pointerProperties;
2815 pointerProperties.clear();
2816 pointerProperties.id = 0;
2817 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2818
2819 PointerCoords pointerCoords;
2820 pointerCoords.clear();
2821
2822 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2823 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2824 bool scrolled = vscroll != 0 || hscroll != 0;
2825
2826 mWheelYVelocityControl.move(when, NULL, &vscroll);
2827 mWheelXVelocityControl.move(when, &hscroll, NULL);
2828
2829 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2830
2831 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002832 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 if (moved || scrolled || buttonsChanged) {
2834 mPointerController->setPresentation(
2835 PointerControllerInterface::PRESENTATION_POINTER);
2836
2837 if (moved) {
2838 mPointerController->move(deltaX, deltaY);
2839 }
2840
2841 if (buttonsChanged) {
2842 mPointerController->setButtonState(currentButtonState);
2843 }
2844
2845 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2846 }
2847
2848 float x, y;
2849 mPointerController->getPosition(&x, &y);
2850 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2851 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002852 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2853 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 displayId = ADISPLAY_ID_DEFAULT;
2855 } else {
2856 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2857 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2858 displayId = ADISPLAY_ID_NONE;
2859 }
2860
2861 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2862
2863 // Moving an external trackball or mouse should wake the device.
2864 // We don't do this for internal cursor devices to prevent them from waking up
2865 // the device in your pocket.
2866 // TODO: Use the input device configuration to control this behavior more finely.
2867 uint32_t policyFlags = 0;
2868 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002869 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 }
2871
2872 // Synthesize key down from buttons if needed.
2873 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2874 policyFlags, lastButtonState, currentButtonState);
2875
2876 // Send motion event.
2877 if (downChanged || moved || scrolled || buttonsChanged) {
2878 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002879 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002880 int32_t motionEventAction;
2881 if (downChanged) {
2882 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002883 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2885 } else {
2886 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2887 }
2888
Michael Wright7b159c92015-05-14 14:48:03 +01002889 if (buttonsReleased) {
2890 BitSet32 released(buttonsReleased);
2891 while (!released.isEmpty()) {
2892 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2893 buttonState &= ~actionButton;
2894 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2895 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2896 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2897 displayId, 1, &pointerProperties, &pointerCoords,
2898 mXPrecision, mYPrecision, downTime);
2899 getListener()->notifyMotion(&releaseArgs);
2900 }
2901 }
2902
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002904 motionEventAction, 0, 0, metaState, currentButtonState,
2905 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 displayId, 1, &pointerProperties, &pointerCoords,
2907 mXPrecision, mYPrecision, downTime);
2908 getListener()->notifyMotion(&args);
2909
Michael Wright7b159c92015-05-14 14:48:03 +01002910 if (buttonsPressed) {
2911 BitSet32 pressed(buttonsPressed);
2912 while (!pressed.isEmpty()) {
2913 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2914 buttonState |= actionButton;
2915 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2916 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2917 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2918 displayId, 1, &pointerProperties, &pointerCoords,
2919 mXPrecision, mYPrecision, downTime);
2920 getListener()->notifyMotion(&pressArgs);
2921 }
2922 }
2923
2924 ALOG_ASSERT(buttonState == currentButtonState);
2925
Michael Wrightd02c5b62014-02-10 15:10:22 -08002926 // Send hover move after UP to tell the application that the mouse is hovering now.
2927 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002928 && (mSource == AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002930 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002931 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2932 displayId, 1, &pointerProperties, &pointerCoords,
2933 mXPrecision, mYPrecision, downTime);
2934 getListener()->notifyMotion(&hoverArgs);
2935 }
2936
2937 // Send scroll events.
2938 if (scrolled) {
2939 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2940 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2941
2942 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002943 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944 AMOTION_EVENT_EDGE_FLAG_NONE,
2945 displayId, 1, &pointerProperties, &pointerCoords,
2946 mXPrecision, mYPrecision, downTime);
2947 getListener()->notifyMotion(&scrollArgs);
2948 }
2949 }
2950
2951 // Synthesize key up from buttons if needed.
2952 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2953 policyFlags, lastButtonState, currentButtonState);
2954
2955 mCursorMotionAccumulator.finishSync();
2956 mCursorScrollAccumulator.finishSync();
2957}
2958
2959int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2960 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2961 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2962 } else {
2963 return AKEY_STATE_UNKNOWN;
2964 }
2965}
2966
2967void CursorInputMapper::fadePointer() {
2968 if (mPointerController != NULL) {
2969 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2970 }
2971}
2972
Prashant Malani1941ff52015-08-11 18:29:28 -07002973// --- RotaryEncoderInputMapper ---
2974
2975RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002976 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002977 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2978}
2979
2980RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2981}
2982
2983uint32_t RotaryEncoderInputMapper::getSources() {
2984 return mSource;
2985}
2986
2987void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2988 InputMapper::populateDeviceInfo(info);
2989
2990 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002991 float res = 0.0f;
2992 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2993 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2994 }
2995 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2996 mScalingFactor)) {
2997 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2998 "default to 1.0!\n");
2999 mScalingFactor = 1.0f;
3000 }
3001 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3002 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003003 }
3004}
3005
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003006void RotaryEncoderInputMapper::dump(std::string& dump) {
3007 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
3008 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07003009 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
3010}
3011
3012void RotaryEncoderInputMapper::configure(nsecs_t when,
3013 const InputReaderConfiguration* config, uint32_t changes) {
3014 InputMapper::configure(when, config, changes);
3015 if (!changes) {
3016 mRotaryEncoderScrollAccumulator.configure(getDevice());
3017 }
Ivan Podogovad437252016-09-29 16:29:55 +01003018 if (!changes || (InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
3019 DisplayViewport v;
3020 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
3021 mOrientation = v.orientation;
3022 } else {
3023 mOrientation = DISPLAY_ORIENTATION_0;
3024 }
3025 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003026}
3027
3028void RotaryEncoderInputMapper::reset(nsecs_t when) {
3029 mRotaryEncoderScrollAccumulator.reset(getDevice());
3030
3031 InputMapper::reset(when);
3032}
3033
3034void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3035 mRotaryEncoderScrollAccumulator.process(rawEvent);
3036
3037 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3038 sync(rawEvent->when);
3039 }
3040}
3041
3042void RotaryEncoderInputMapper::sync(nsecs_t when) {
3043 PointerCoords pointerCoords;
3044 pointerCoords.clear();
3045
3046 PointerProperties pointerProperties;
3047 pointerProperties.clear();
3048 pointerProperties.id = 0;
3049 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3050
3051 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3052 bool scrolled = scroll != 0;
3053
3054 // This is not a pointer, so it's not associated with a display.
3055 int32_t displayId = ADISPLAY_ID_NONE;
3056
3057 // Moving the rotary encoder should wake the device (if specified).
3058 uint32_t policyFlags = 0;
3059 if (scrolled && getDevice()->isExternal()) {
3060 policyFlags |= POLICY_FLAG_WAKE;
3061 }
3062
Ivan Podogovad437252016-09-29 16:29:55 +01003063 if (mOrientation == DISPLAY_ORIENTATION_180) {
3064 scroll = -scroll;
3065 }
3066
Prashant Malani1941ff52015-08-11 18:29:28 -07003067 // Send motion event.
3068 if (scrolled) {
3069 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003070 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003071
3072 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
3073 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3074 AMOTION_EVENT_EDGE_FLAG_NONE,
3075 displayId, 1, &pointerProperties, &pointerCoords,
3076 0, 0, 0);
3077 getListener()->notifyMotion(&scrollArgs);
3078 }
3079
3080 mRotaryEncoderScrollAccumulator.finishSync();
3081}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082
3083// --- TouchInputMapper ---
3084
3085TouchInputMapper::TouchInputMapper(InputDevice* device) :
3086 InputMapper(device),
3087 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3088 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
3089 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3090}
3091
3092TouchInputMapper::~TouchInputMapper() {
3093}
3094
3095uint32_t TouchInputMapper::getSources() {
3096 return mSource;
3097}
3098
3099void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3100 InputMapper::populateDeviceInfo(info);
3101
3102 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3103 info->addMotionRange(mOrientedRanges.x);
3104 info->addMotionRange(mOrientedRanges.y);
3105 info->addMotionRange(mOrientedRanges.pressure);
3106
3107 if (mOrientedRanges.haveSize) {
3108 info->addMotionRange(mOrientedRanges.size);
3109 }
3110
3111 if (mOrientedRanges.haveTouchSize) {
3112 info->addMotionRange(mOrientedRanges.touchMajor);
3113 info->addMotionRange(mOrientedRanges.touchMinor);
3114 }
3115
3116 if (mOrientedRanges.haveToolSize) {
3117 info->addMotionRange(mOrientedRanges.toolMajor);
3118 info->addMotionRange(mOrientedRanges.toolMinor);
3119 }
3120
3121 if (mOrientedRanges.haveOrientation) {
3122 info->addMotionRange(mOrientedRanges.orientation);
3123 }
3124
3125 if (mOrientedRanges.haveDistance) {
3126 info->addMotionRange(mOrientedRanges.distance);
3127 }
3128
3129 if (mOrientedRanges.haveTilt) {
3130 info->addMotionRange(mOrientedRanges.tilt);
3131 }
3132
3133 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3134 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3135 0.0f);
3136 }
3137 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3138 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3139 0.0f);
3140 }
3141 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3142 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3143 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3144 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3145 x.fuzz, x.resolution);
3146 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3147 y.fuzz, y.resolution);
3148 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3149 x.fuzz, x.resolution);
3150 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3151 y.fuzz, y.resolution);
3152 }
3153 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3154 }
3155}
3156
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003157void TouchInputMapper::dump(std::string& dump) {
3158 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 dumpParameters(dump);
3160 dumpVirtualKeys(dump);
3161 dumpRawPointerAxes(dump);
3162 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003163 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 dumpSurface(dump);
3165
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003166 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3167 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3168 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3169 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3170 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3171 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3172 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3173 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3174 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3175 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3176 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3177 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3178 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3179 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3180 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3181 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3182 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003184 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3185 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003186 mLastRawState.rawPointerData.pointerCount);
3187 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3188 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003189 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3191 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3192 "toolType=%d, isHovering=%s\n", i,
3193 pointer.id, pointer.x, pointer.y, pointer.pressure,
3194 pointer.touchMajor, pointer.touchMinor,
3195 pointer.toolMajor, pointer.toolMinor,
3196 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3197 pointer.toolType, toString(pointer.isHovering));
3198 }
3199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003200 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3201 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003202 mLastCookedState.cookedPointerData.pointerCount);
3203 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3204 const PointerProperties& pointerProperties =
3205 mLastCookedState.cookedPointerData.pointerProperties[i];
3206 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003207 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3209 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3210 "toolType=%d, isHovering=%s\n", i,
3211 pointerProperties.id,
3212 pointerCoords.getX(),
3213 pointerCoords.getY(),
3214 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3215 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3216 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3217 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3218 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3219 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3220 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3221 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3222 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003223 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224 }
3225
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003226 dump += INDENT3 "Stylus Fusion:\n";
3227 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003228 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003229 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3230 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003231 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003232 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003233 dumpStylusState(dump, mExternalStylusState);
3234
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003236 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3237 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003238 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003239 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003241 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003243 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003245 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 mPointerGestureMaxSwipeWidth);
3247 }
3248}
3249
Santos Cordonfa5cf462017-04-05 10:37:00 -07003250const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3251 switch (deviceMode) {
3252 case DEVICE_MODE_DISABLED:
3253 return "disabled";
3254 case DEVICE_MODE_DIRECT:
3255 return "direct";
3256 case DEVICE_MODE_UNSCALED:
3257 return "unscaled";
3258 case DEVICE_MODE_NAVIGATION:
3259 return "navigation";
3260 case DEVICE_MODE_POINTER:
3261 return "pointer";
3262 }
3263 return "unknown";
3264}
3265
Michael Wrightd02c5b62014-02-10 15:10:22 -08003266void TouchInputMapper::configure(nsecs_t when,
3267 const InputReaderConfiguration* config, uint32_t changes) {
3268 InputMapper::configure(when, config, changes);
3269
3270 mConfig = *config;
3271
3272 if (!changes) { // first time only
3273 // Configure basic parameters.
3274 configureParameters();
3275
3276 // Configure common accumulators.
3277 mCursorScrollAccumulator.configure(getDevice());
3278 mTouchButtonAccumulator.configure(getDevice());
3279
3280 // Configure absolute axis information.
3281 configureRawPointerAxes();
3282
3283 // Prepare input device calibration.
3284 parseCalibration();
3285 resolveCalibration();
3286 }
3287
Michael Wright842500e2015-03-13 17:32:02 -07003288 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003289 // Update location calibration to reflect current settings
3290 updateAffineTransformation();
3291 }
3292
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3294 // Update pointer speed.
3295 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3296 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3297 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3298 }
3299
3300 bool resetNeeded = false;
3301 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3302 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003303 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3304 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003305 // Configure device sources, surface dimensions, orientation and
3306 // scaling factors.
3307 configureSurface(when, &resetNeeded);
3308 }
3309
3310 if (changes && resetNeeded) {
3311 // Send reset, unless this is the first time the device has been configured,
3312 // in which case the reader will call reset itself after all mappers are ready.
3313 getDevice()->notifyReset(when);
3314 }
3315}
3316
Michael Wright842500e2015-03-13 17:32:02 -07003317void TouchInputMapper::resolveExternalStylusPresence() {
3318 Vector<InputDeviceInfo> devices;
3319 mContext->getExternalStylusDevices(devices);
3320 mExternalStylusConnected = !devices.isEmpty();
3321
3322 if (!mExternalStylusConnected) {
3323 resetExternalStylus();
3324 }
3325}
3326
Michael Wrightd02c5b62014-02-10 15:10:22 -08003327void TouchInputMapper::configureParameters() {
3328 // Use the pointer presentation mode for devices that do not support distinct
3329 // multitouch. The spot-based presentation relies on being able to accurately
3330 // locate two or more fingers on the touch pad.
3331 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003332 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333
3334 String8 gestureModeString;
3335 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3336 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003337 if (gestureModeString == "single-touch") {
3338 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3339 } else if (gestureModeString == "multi-touch") {
3340 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003341 } else if (gestureModeString != "default") {
3342 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3343 }
3344 }
3345
3346 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3347 // The device is a touch screen.
3348 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3349 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3350 // The device is a pointing device like a track pad.
3351 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3352 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3353 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3354 // The device is a cursor device with a touch pad attached.
3355 // By default don't use the touch pad to move the pointer.
3356 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3357 } else {
3358 // The device is a touch pad of unknown purpose.
3359 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3360 }
3361
3362 mParameters.hasButtonUnderPad=
3363 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3364
3365 String8 deviceTypeString;
3366 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3367 deviceTypeString)) {
3368 if (deviceTypeString == "touchScreen") {
3369 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3370 } else if (deviceTypeString == "touchPad") {
3371 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3372 } else if (deviceTypeString == "touchNavigation") {
3373 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3374 } else if (deviceTypeString == "pointer") {
3375 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3376 } else if (deviceTypeString != "default") {
3377 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3378 }
3379 }
3380
3381 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3382 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3383 mParameters.orientationAware);
3384
3385 mParameters.hasAssociatedDisplay = false;
3386 mParameters.associatedDisplayIsExternal = false;
3387 if (mParameters.orientationAware
3388 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3389 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3390 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003391 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3392 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3393 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3394 mParameters.uniqueDisplayId);
3395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003397
3398 // Initial downs on external touch devices should wake the device.
3399 // Normally we don't do this for internal touch screens to prevent them from waking
3400 // up in your pocket but you can enable it using the input device configuration.
3401 mParameters.wake = getDevice()->isExternal();
3402 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3403 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003404}
3405
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003406void TouchInputMapper::dumpParameters(std::string& dump) {
3407 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408
3409 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003410 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003411 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003413 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003414 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 break;
3416 default:
3417 assert(false);
3418 }
3419
3420 switch (mParameters.deviceType) {
3421 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003422 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 break;
3424 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003425 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 break;
3427 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003428 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 break;
3430 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003431 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 break;
3433 default:
3434 ALOG_ASSERT(false);
3435 }
3436
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003437 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003438 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003439 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003440 toString(mParameters.associatedDisplayIsExternal),
3441 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003442 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 toString(mParameters.orientationAware));
3444}
3445
3446void TouchInputMapper::configureRawPointerAxes() {
3447 mRawPointerAxes.clear();
3448}
3449
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003450void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3451 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003452 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3453 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3454 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3455 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3456 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3457 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3458 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3459 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3460 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3461 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3462 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3463 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3464 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3465}
3466
Michael Wright842500e2015-03-13 17:32:02 -07003467bool TouchInputMapper::hasExternalStylus() const {
3468 return mExternalStylusConnected;
3469}
3470
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3472 int32_t oldDeviceMode = mDeviceMode;
3473
Michael Wright842500e2015-03-13 17:32:02 -07003474 resolveExternalStylusPresence();
3475
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476 // Determine device mode.
3477 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3478 && mConfig.pointerGesturesEnabled) {
3479 mSource = AINPUT_SOURCE_MOUSE;
3480 mDeviceMode = DEVICE_MODE_POINTER;
3481 if (hasStylus()) {
3482 mSource |= AINPUT_SOURCE_STYLUS;
3483 }
3484 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3485 && mParameters.hasAssociatedDisplay) {
3486 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3487 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003488 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489 mSource |= AINPUT_SOURCE_STYLUS;
3490 }
Michael Wright2f78b682015-06-12 15:25:08 +01003491 if (hasExternalStylus()) {
3492 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3493 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3495 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3496 mDeviceMode = DEVICE_MODE_NAVIGATION;
3497 } else {
3498 mSource = AINPUT_SOURCE_TOUCHPAD;
3499 mDeviceMode = DEVICE_MODE_UNSCALED;
3500 }
3501
3502 // Ensure we have valid X and Y axes.
3503 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3504 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3505 "The device will be inoperable.", getDeviceName().string());
3506 mDeviceMode = DEVICE_MODE_DISABLED;
3507 return;
3508 }
3509
3510 // Raw width and height in the natural orientation.
3511 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3512 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3513
3514 // Get associated display dimensions.
3515 DisplayViewport newViewport;
3516 if (mParameters.hasAssociatedDisplay) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003517 const String8* uniqueDisplayId = NULL;
3518 ViewportType viewportTypeToUse;
3519
3520 if (mParameters.associatedDisplayIsExternal) {
3521 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3522 } else if (!mParameters.uniqueDisplayId.isEmpty()) {
3523 // If the IDC file specified a unique display Id, then it expects to be linked to a
3524 // virtual display with the same unique ID.
3525 uniqueDisplayId = &mParameters.uniqueDisplayId;
3526 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3527 } else {
3528 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3529 }
3530
3531 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3533 "display. The device will be inoperable until the display size "
3534 "becomes available.",
3535 getDeviceName().string());
3536 mDeviceMode = DEVICE_MODE_DISABLED;
3537 return;
3538 }
3539 } else {
3540 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3541 }
3542 bool viewportChanged = mViewport != newViewport;
3543 if (viewportChanged) {
3544 mViewport = newViewport;
3545
3546 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3547 // Convert rotated viewport to natural surface coordinates.
3548 int32_t naturalLogicalWidth, naturalLogicalHeight;
3549 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3550 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3551 int32_t naturalDeviceWidth, naturalDeviceHeight;
3552 switch (mViewport.orientation) {
3553 case DISPLAY_ORIENTATION_90:
3554 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3555 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3556 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3557 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3558 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3559 naturalPhysicalTop = mViewport.physicalLeft;
3560 naturalDeviceWidth = mViewport.deviceHeight;
3561 naturalDeviceHeight = mViewport.deviceWidth;
3562 break;
3563 case DISPLAY_ORIENTATION_180:
3564 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3565 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3566 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3567 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3568 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3569 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3570 naturalDeviceWidth = mViewport.deviceWidth;
3571 naturalDeviceHeight = mViewport.deviceHeight;
3572 break;
3573 case DISPLAY_ORIENTATION_270:
3574 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3575 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3576 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3577 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3578 naturalPhysicalLeft = mViewport.physicalTop;
3579 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3580 naturalDeviceWidth = mViewport.deviceHeight;
3581 naturalDeviceHeight = mViewport.deviceWidth;
3582 break;
3583 case DISPLAY_ORIENTATION_0:
3584 default:
3585 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3586 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3587 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3588 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3589 naturalPhysicalLeft = mViewport.physicalLeft;
3590 naturalPhysicalTop = mViewport.physicalTop;
3591 naturalDeviceWidth = mViewport.deviceWidth;
3592 naturalDeviceHeight = mViewport.deviceHeight;
3593 break;
3594 }
3595
3596 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3597 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3598 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3599 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3600
3601 mSurfaceOrientation = mParameters.orientationAware ?
3602 mViewport.orientation : DISPLAY_ORIENTATION_0;
3603 } else {
3604 mSurfaceWidth = rawWidth;
3605 mSurfaceHeight = rawHeight;
3606 mSurfaceLeft = 0;
3607 mSurfaceTop = 0;
3608 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3609 }
3610 }
3611
3612 // If moving between pointer modes, need to reset some state.
3613 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3614 if (deviceModeChanged) {
3615 mOrientedRanges.clear();
3616 }
3617
3618 // Create pointer controller if needed.
3619 if (mDeviceMode == DEVICE_MODE_POINTER ||
3620 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3621 if (mPointerController == NULL) {
3622 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3623 }
3624 } else {
3625 mPointerController.clear();
3626 }
3627
3628 if (viewportChanged || deviceModeChanged) {
3629 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3630 "display id %d",
3631 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3632 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3633
3634 // Configure X and Y factors.
3635 mXScale = float(mSurfaceWidth) / rawWidth;
3636 mYScale = float(mSurfaceHeight) / rawHeight;
3637 mXTranslate = -mSurfaceLeft;
3638 mYTranslate = -mSurfaceTop;
3639 mXPrecision = 1.0f / mXScale;
3640 mYPrecision = 1.0f / mYScale;
3641
3642 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3643 mOrientedRanges.x.source = mSource;
3644 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3645 mOrientedRanges.y.source = mSource;
3646
3647 configureVirtualKeys();
3648
3649 // Scale factor for terms that are not oriented in a particular axis.
3650 // If the pixels are square then xScale == yScale otherwise we fake it
3651 // by choosing an average.
3652 mGeometricScale = avg(mXScale, mYScale);
3653
3654 // Size of diagonal axis.
3655 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3656
3657 // Size factors.
3658 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3659 if (mRawPointerAxes.touchMajor.valid
3660 && mRawPointerAxes.touchMajor.maxValue != 0) {
3661 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3662 } else if (mRawPointerAxes.toolMajor.valid
3663 && mRawPointerAxes.toolMajor.maxValue != 0) {
3664 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3665 } else {
3666 mSizeScale = 0.0f;
3667 }
3668
3669 mOrientedRanges.haveTouchSize = true;
3670 mOrientedRanges.haveToolSize = true;
3671 mOrientedRanges.haveSize = true;
3672
3673 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3674 mOrientedRanges.touchMajor.source = mSource;
3675 mOrientedRanges.touchMajor.min = 0;
3676 mOrientedRanges.touchMajor.max = diagonalSize;
3677 mOrientedRanges.touchMajor.flat = 0;
3678 mOrientedRanges.touchMajor.fuzz = 0;
3679 mOrientedRanges.touchMajor.resolution = 0;
3680
3681 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3682 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3683
3684 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3685 mOrientedRanges.toolMajor.source = mSource;
3686 mOrientedRanges.toolMajor.min = 0;
3687 mOrientedRanges.toolMajor.max = diagonalSize;
3688 mOrientedRanges.toolMajor.flat = 0;
3689 mOrientedRanges.toolMajor.fuzz = 0;
3690 mOrientedRanges.toolMajor.resolution = 0;
3691
3692 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3693 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3694
3695 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3696 mOrientedRanges.size.source = mSource;
3697 mOrientedRanges.size.min = 0;
3698 mOrientedRanges.size.max = 1.0;
3699 mOrientedRanges.size.flat = 0;
3700 mOrientedRanges.size.fuzz = 0;
3701 mOrientedRanges.size.resolution = 0;
3702 } else {
3703 mSizeScale = 0.0f;
3704 }
3705
3706 // Pressure factors.
3707 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003708 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3710 || mCalibration.pressureCalibration
3711 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3712 if (mCalibration.havePressureScale) {
3713 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003714 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003715 } else if (mRawPointerAxes.pressure.valid
3716 && mRawPointerAxes.pressure.maxValue != 0) {
3717 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3718 }
3719 }
3720
3721 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3722 mOrientedRanges.pressure.source = mSource;
3723 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003724 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003725 mOrientedRanges.pressure.flat = 0;
3726 mOrientedRanges.pressure.fuzz = 0;
3727 mOrientedRanges.pressure.resolution = 0;
3728
3729 // Tilt
3730 mTiltXCenter = 0;
3731 mTiltXScale = 0;
3732 mTiltYCenter = 0;
3733 mTiltYScale = 0;
3734 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3735 if (mHaveTilt) {
3736 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3737 mRawPointerAxes.tiltX.maxValue);
3738 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3739 mRawPointerAxes.tiltY.maxValue);
3740 mTiltXScale = M_PI / 180;
3741 mTiltYScale = M_PI / 180;
3742
3743 mOrientedRanges.haveTilt = true;
3744
3745 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3746 mOrientedRanges.tilt.source = mSource;
3747 mOrientedRanges.tilt.min = 0;
3748 mOrientedRanges.tilt.max = M_PI_2;
3749 mOrientedRanges.tilt.flat = 0;
3750 mOrientedRanges.tilt.fuzz = 0;
3751 mOrientedRanges.tilt.resolution = 0;
3752 }
3753
3754 // Orientation
3755 mOrientationScale = 0;
3756 if (mHaveTilt) {
3757 mOrientedRanges.haveOrientation = true;
3758
3759 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3760 mOrientedRanges.orientation.source = mSource;
3761 mOrientedRanges.orientation.min = -M_PI;
3762 mOrientedRanges.orientation.max = M_PI;
3763 mOrientedRanges.orientation.flat = 0;
3764 mOrientedRanges.orientation.fuzz = 0;
3765 mOrientedRanges.orientation.resolution = 0;
3766 } else if (mCalibration.orientationCalibration !=
3767 Calibration::ORIENTATION_CALIBRATION_NONE) {
3768 if (mCalibration.orientationCalibration
3769 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3770 if (mRawPointerAxes.orientation.valid) {
3771 if (mRawPointerAxes.orientation.maxValue > 0) {
3772 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3773 } else if (mRawPointerAxes.orientation.minValue < 0) {
3774 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3775 } else {
3776 mOrientationScale = 0;
3777 }
3778 }
3779 }
3780
3781 mOrientedRanges.haveOrientation = true;
3782
3783 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3784 mOrientedRanges.orientation.source = mSource;
3785 mOrientedRanges.orientation.min = -M_PI_2;
3786 mOrientedRanges.orientation.max = M_PI_2;
3787 mOrientedRanges.orientation.flat = 0;
3788 mOrientedRanges.orientation.fuzz = 0;
3789 mOrientedRanges.orientation.resolution = 0;
3790 }
3791
3792 // Distance
3793 mDistanceScale = 0;
3794 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3795 if (mCalibration.distanceCalibration
3796 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3797 if (mCalibration.haveDistanceScale) {
3798 mDistanceScale = mCalibration.distanceScale;
3799 } else {
3800 mDistanceScale = 1.0f;
3801 }
3802 }
3803
3804 mOrientedRanges.haveDistance = true;
3805
3806 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3807 mOrientedRanges.distance.source = mSource;
3808 mOrientedRanges.distance.min =
3809 mRawPointerAxes.distance.minValue * mDistanceScale;
3810 mOrientedRanges.distance.max =
3811 mRawPointerAxes.distance.maxValue * mDistanceScale;
3812 mOrientedRanges.distance.flat = 0;
3813 mOrientedRanges.distance.fuzz =
3814 mRawPointerAxes.distance.fuzz * mDistanceScale;
3815 mOrientedRanges.distance.resolution = 0;
3816 }
3817
3818 // Compute oriented precision, scales and ranges.
3819 // Note that the maximum value reported is an inclusive maximum value so it is one
3820 // unit less than the total width or height of surface.
3821 switch (mSurfaceOrientation) {
3822 case DISPLAY_ORIENTATION_90:
3823 case DISPLAY_ORIENTATION_270:
3824 mOrientedXPrecision = mYPrecision;
3825 mOrientedYPrecision = mXPrecision;
3826
3827 mOrientedRanges.x.min = mYTranslate;
3828 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3829 mOrientedRanges.x.flat = 0;
3830 mOrientedRanges.x.fuzz = 0;
3831 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3832
3833 mOrientedRanges.y.min = mXTranslate;
3834 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3835 mOrientedRanges.y.flat = 0;
3836 mOrientedRanges.y.fuzz = 0;
3837 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3838 break;
3839
3840 default:
3841 mOrientedXPrecision = mXPrecision;
3842 mOrientedYPrecision = mYPrecision;
3843
3844 mOrientedRanges.x.min = mXTranslate;
3845 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3846 mOrientedRanges.x.flat = 0;
3847 mOrientedRanges.x.fuzz = 0;
3848 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3849
3850 mOrientedRanges.y.min = mYTranslate;
3851 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3852 mOrientedRanges.y.flat = 0;
3853 mOrientedRanges.y.fuzz = 0;
3854 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3855 break;
3856 }
3857
Jason Gerecke71b16e82014-03-10 09:47:59 -07003858 // Location
3859 updateAffineTransformation();
3860
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861 if (mDeviceMode == DEVICE_MODE_POINTER) {
3862 // Compute pointer gesture detection parameters.
3863 float rawDiagonal = hypotf(rawWidth, rawHeight);
3864 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3865
3866 // Scale movements such that one whole swipe of the touch pad covers a
3867 // given area relative to the diagonal size of the display when no acceleration
3868 // is applied.
3869 // Assume that the touch pad has a square aspect ratio such that movements in
3870 // X and Y of the same number of raw units cover the same physical distance.
3871 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3872 * displayDiagonal / rawDiagonal;
3873 mPointerYMovementScale = mPointerXMovementScale;
3874
3875 // Scale zooms to cover a smaller range of the display than movements do.
3876 // This value determines the area around the pointer that is affected by freeform
3877 // pointer gestures.
3878 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3879 * displayDiagonal / rawDiagonal;
3880 mPointerYZoomScale = mPointerXZoomScale;
3881
3882 // Max width between pointers to detect a swipe gesture is more than some fraction
3883 // of the diagonal axis of the touch pad. Touches that are wider than this are
3884 // translated into freeform gestures.
3885 mPointerGestureMaxSwipeWidth =
3886 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3887
3888 // Abort current pointer usages because the state has changed.
3889 abortPointerUsage(when, 0 /*policyFlags*/);
3890 }
3891
3892 // Inform the dispatcher about the changes.
3893 *outResetNeeded = true;
3894 bumpGeneration();
3895 }
3896}
3897
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003898void TouchInputMapper::dumpSurface(std::string& dump) {
3899 dump += StringPrintf(INDENT3 "Viewport: displayId=%d, orientation=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003900 "logicalFrame=[%d, %d, %d, %d], "
3901 "physicalFrame=[%d, %d, %d, %d], "
3902 "deviceSize=[%d, %d]\n",
3903 mViewport.displayId, mViewport.orientation,
3904 mViewport.logicalLeft, mViewport.logicalTop,
3905 mViewport.logicalRight, mViewport.logicalBottom,
3906 mViewport.physicalLeft, mViewport.physicalTop,
3907 mViewport.physicalRight, mViewport.physicalBottom,
3908 mViewport.deviceWidth, mViewport.deviceHeight);
3909
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003910 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3911 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3912 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3913 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3914 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915}
3916
3917void TouchInputMapper::configureVirtualKeys() {
3918 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3919 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3920
3921 mVirtualKeys.clear();
3922
3923 if (virtualKeyDefinitions.size() == 0) {
3924 return;
3925 }
3926
3927 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3928
3929 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3930 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3931 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3932 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3933
3934 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3935 const VirtualKeyDefinition& virtualKeyDefinition =
3936 virtualKeyDefinitions[i];
3937
3938 mVirtualKeys.add();
3939 VirtualKey& virtualKey = mVirtualKeys.editTop();
3940
3941 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3942 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003943 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003945 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3946 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3948 virtualKey.scanCode);
3949 mVirtualKeys.pop(); // drop the key
3950 continue;
3951 }
3952
3953 virtualKey.keyCode = keyCode;
3954 virtualKey.flags = flags;
3955
3956 // convert the key definition's display coordinates into touch coordinates for a hit box
3957 int32_t halfWidth = virtualKeyDefinition.width / 2;
3958 int32_t halfHeight = virtualKeyDefinition.height / 2;
3959
3960 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3961 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3962 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3963 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3964 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3965 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3966 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3967 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3968 }
3969}
3970
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003971void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003973 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974
3975 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3976 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003977 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003978 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3979 i, virtualKey.scanCode, virtualKey.keyCode,
3980 virtualKey.hitLeft, virtualKey.hitRight,
3981 virtualKey.hitTop, virtualKey.hitBottom);
3982 }
3983 }
3984}
3985
3986void TouchInputMapper::parseCalibration() {
3987 const PropertyMap& in = getDevice()->getConfiguration();
3988 Calibration& out = mCalibration;
3989
3990 // Size
3991 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3992 String8 sizeCalibrationString;
3993 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3994 if (sizeCalibrationString == "none") {
3995 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3996 } else if (sizeCalibrationString == "geometric") {
3997 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3998 } else if (sizeCalibrationString == "diameter") {
3999 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4000 } else if (sizeCalibrationString == "box") {
4001 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4002 } else if (sizeCalibrationString == "area") {
4003 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4004 } else if (sizeCalibrationString != "default") {
4005 ALOGW("Invalid value for touch.size.calibration: '%s'",
4006 sizeCalibrationString.string());
4007 }
4008 }
4009
4010 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4011 out.sizeScale);
4012 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4013 out.sizeBias);
4014 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4015 out.sizeIsSummed);
4016
4017 // Pressure
4018 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4019 String8 pressureCalibrationString;
4020 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4021 if (pressureCalibrationString == "none") {
4022 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4023 } else if (pressureCalibrationString == "physical") {
4024 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4025 } else if (pressureCalibrationString == "amplitude") {
4026 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4027 } else if (pressureCalibrationString != "default") {
4028 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4029 pressureCalibrationString.string());
4030 }
4031 }
4032
4033 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4034 out.pressureScale);
4035
4036 // Orientation
4037 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4038 String8 orientationCalibrationString;
4039 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4040 if (orientationCalibrationString == "none") {
4041 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4042 } else if (orientationCalibrationString == "interpolated") {
4043 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4044 } else if (orientationCalibrationString == "vector") {
4045 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4046 } else if (orientationCalibrationString != "default") {
4047 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4048 orientationCalibrationString.string());
4049 }
4050 }
4051
4052 // Distance
4053 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4054 String8 distanceCalibrationString;
4055 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4056 if (distanceCalibrationString == "none") {
4057 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4058 } else if (distanceCalibrationString == "scaled") {
4059 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4060 } else if (distanceCalibrationString != "default") {
4061 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4062 distanceCalibrationString.string());
4063 }
4064 }
4065
4066 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4067 out.distanceScale);
4068
4069 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4070 String8 coverageCalibrationString;
4071 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4072 if (coverageCalibrationString == "none") {
4073 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4074 } else if (coverageCalibrationString == "box") {
4075 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4076 } else if (coverageCalibrationString != "default") {
4077 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4078 coverageCalibrationString.string());
4079 }
4080 }
4081}
4082
4083void TouchInputMapper::resolveCalibration() {
4084 // Size
4085 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4086 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4087 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4088 }
4089 } else {
4090 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4091 }
4092
4093 // Pressure
4094 if (mRawPointerAxes.pressure.valid) {
4095 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4096 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4097 }
4098 } else {
4099 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4100 }
4101
4102 // Orientation
4103 if (mRawPointerAxes.orientation.valid) {
4104 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4105 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4106 }
4107 } else {
4108 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4109 }
4110
4111 // Distance
4112 if (mRawPointerAxes.distance.valid) {
4113 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4114 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4115 }
4116 } else {
4117 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4118 }
4119
4120 // Coverage
4121 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4122 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4123 }
4124}
4125
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004126void TouchInputMapper::dumpCalibration(std::string& dump) {
4127 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128
4129 // Size
4130 switch (mCalibration.sizeCalibration) {
4131 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004132 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 break;
4134 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004135 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 break;
4137 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004138 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 break;
4140 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004141 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 break;
4143 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004144 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 break;
4146 default:
4147 ALOG_ASSERT(false);
4148 }
4149
4150 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004151 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 mCalibration.sizeScale);
4153 }
4154
4155 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 mCalibration.sizeBias);
4158 }
4159
4160 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004161 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 toString(mCalibration.sizeIsSummed));
4163 }
4164
4165 // Pressure
4166 switch (mCalibration.pressureCalibration) {
4167 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004168 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 break;
4170 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004171 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 break;
4173 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004174 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 break;
4176 default:
4177 ALOG_ASSERT(false);
4178 }
4179
4180 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004181 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 mCalibration.pressureScale);
4183 }
4184
4185 // Orientation
4186 switch (mCalibration.orientationCalibration) {
4187 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004188 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 break;
4190 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 break;
4193 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004194 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 break;
4196 default:
4197 ALOG_ASSERT(false);
4198 }
4199
4200 // Distance
4201 switch (mCalibration.distanceCalibration) {
4202 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004203 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 break;
4205 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004206 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 break;
4208 default:
4209 ALOG_ASSERT(false);
4210 }
4211
4212 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004213 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 mCalibration.distanceScale);
4215 }
4216
4217 switch (mCalibration.coverageCalibration) {
4218 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004219 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 break;
4221 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004222 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 break;
4224 default:
4225 ALOG_ASSERT(false);
4226 }
4227}
4228
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004229void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4230 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004231
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004232 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4233 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4234 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4235 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4236 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4237 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004238}
4239
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004240void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004241 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4242 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004243}
4244
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245void TouchInputMapper::reset(nsecs_t when) {
4246 mCursorButtonAccumulator.reset(getDevice());
4247 mCursorScrollAccumulator.reset(getDevice());
4248 mTouchButtonAccumulator.reset(getDevice());
4249
4250 mPointerVelocityControl.reset();
4251 mWheelXVelocityControl.reset();
4252 mWheelYVelocityControl.reset();
4253
Michael Wright842500e2015-03-13 17:32:02 -07004254 mRawStatesPending.clear();
4255 mCurrentRawState.clear();
4256 mCurrentCookedState.clear();
4257 mLastRawState.clear();
4258 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 mPointerUsage = POINTER_USAGE_NONE;
4260 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004261 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004262 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 mDownTime = 0;
4264
4265 mCurrentVirtualKey.down = false;
4266
4267 mPointerGesture.reset();
4268 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004269 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270
4271 if (mPointerController != NULL) {
4272 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4273 mPointerController->clearSpots();
4274 }
4275
4276 InputMapper::reset(when);
4277}
4278
Michael Wright842500e2015-03-13 17:32:02 -07004279void TouchInputMapper::resetExternalStylus() {
4280 mExternalStylusState.clear();
4281 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004282 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004283 mExternalStylusDataPending = false;
4284}
4285
Michael Wright43fd19f2015-04-21 19:02:58 +01004286void TouchInputMapper::clearStylusDataPendingFlags() {
4287 mExternalStylusDataPending = false;
4288 mExternalStylusFusionTimeout = LLONG_MAX;
4289}
4290
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291void TouchInputMapper::process(const RawEvent* rawEvent) {
4292 mCursorButtonAccumulator.process(rawEvent);
4293 mCursorScrollAccumulator.process(rawEvent);
4294 mTouchButtonAccumulator.process(rawEvent);
4295
4296 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4297 sync(rawEvent->when);
4298 }
4299}
4300
4301void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004302 const RawState* last = mRawStatesPending.isEmpty() ?
4303 &mCurrentRawState : &mRawStatesPending.top();
4304
4305 // Push a new state.
4306 mRawStatesPending.push();
4307 RawState* next = &mRawStatesPending.editTop();
4308 next->clear();
4309 next->when = when;
4310
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004312 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 | mCursorButtonAccumulator.getButtonState();
4314
Michael Wright842500e2015-03-13 17:32:02 -07004315 // Sync scroll
4316 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4317 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 mCursorScrollAccumulator.finishSync();
4319
Michael Wright842500e2015-03-13 17:32:02 -07004320 // Sync touch
4321 syncTouch(when, next);
4322
4323 // Assign pointer ids.
4324 if (!mHavePointerIds) {
4325 assignPointerIds(last, next);
4326 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327
4328#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004329 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4330 "hovering ids 0x%08x -> 0x%08x",
4331 last->rawPointerData.pointerCount,
4332 next->rawPointerData.pointerCount,
4333 last->rawPointerData.touchingIdBits.value,
4334 next->rawPointerData.touchingIdBits.value,
4335 last->rawPointerData.hoveringIdBits.value,
4336 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337#endif
4338
Michael Wright842500e2015-03-13 17:32:02 -07004339 processRawTouches(false /*timeout*/);
4340}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341
Michael Wright842500e2015-03-13 17:32:02 -07004342void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4344 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004345 mCurrentRawState.clear();
4346 mRawStatesPending.clear();
4347 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348 }
4349
Michael Wright842500e2015-03-13 17:32:02 -07004350 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4351 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4352 // touching the current state will only observe the events that have been dispatched to the
4353 // rest of the pipeline.
4354 const size_t N = mRawStatesPending.size();
4355 size_t count;
4356 for(count = 0; count < N; count++) {
4357 const RawState& next = mRawStatesPending[count];
4358
4359 // A failure to assign the stylus id means that we're waiting on stylus data
4360 // and so should defer the rest of the pipeline.
4361 if (assignExternalStylusId(next, timeout)) {
4362 break;
4363 }
4364
4365 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004366 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004367 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004368 if (mCurrentRawState.when < mLastRawState.when) {
4369 mCurrentRawState.when = mLastRawState.when;
4370 }
Michael Wright842500e2015-03-13 17:32:02 -07004371 cookAndDispatch(mCurrentRawState.when);
4372 }
4373 if (count != 0) {
4374 mRawStatesPending.removeItemsAt(0, count);
4375 }
4376
Michael Wright842500e2015-03-13 17:32:02 -07004377 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004378 if (timeout) {
4379 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4380 clearStylusDataPendingFlags();
4381 mCurrentRawState.copyFrom(mLastRawState);
4382#if DEBUG_STYLUS_FUSION
4383 ALOGD("Timeout expired, synthesizing event with new stylus data");
4384#endif
4385 cookAndDispatch(when);
4386 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4387 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4388 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4389 }
Michael Wright842500e2015-03-13 17:32:02 -07004390 }
4391}
4392
4393void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4394 // Always start with a clean state.
4395 mCurrentCookedState.clear();
4396
4397 // Apply stylus buttons to current raw state.
4398 applyExternalStylusButtonState(when);
4399
4400 // Handle policy on initial down or hover events.
4401 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4402 && mCurrentRawState.rawPointerData.pointerCount != 0;
4403
4404 uint32_t policyFlags = 0;
4405 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4406 if (initialDown || buttonsPressed) {
4407 // If this is a touch screen, hide the pointer on an initial down.
4408 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4409 getContext()->fadePointer();
4410 }
4411
4412 if (mParameters.wake) {
4413 policyFlags |= POLICY_FLAG_WAKE;
4414 }
4415 }
4416
4417 // Consume raw off-screen touches before cooking pointer data.
4418 // If touches are consumed, subsequent code will not receive any pointer data.
4419 if (consumeRawTouches(when, policyFlags)) {
4420 mCurrentRawState.rawPointerData.clear();
4421 }
4422
4423 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4424 // with cooked pointer data that has the same ids and indices as the raw data.
4425 // The following code can use either the raw or cooked data, as needed.
4426 cookPointerData();
4427
4428 // Apply stylus pressure to current cooked state.
4429 applyExternalStylusTouchState(when);
4430
4431 // Synthesize key down from raw buttons if needed.
4432 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004433 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004434
4435 // Dispatch the touches either directly or by translation through a pointer on screen.
4436 if (mDeviceMode == DEVICE_MODE_POINTER) {
4437 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4438 !idBits.isEmpty(); ) {
4439 uint32_t id = idBits.clearFirstMarkedBit();
4440 const RawPointerData::Pointer& pointer =
4441 mCurrentRawState.rawPointerData.pointerForId(id);
4442 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4443 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4444 mCurrentCookedState.stylusIdBits.markBit(id);
4445 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4446 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4447 mCurrentCookedState.fingerIdBits.markBit(id);
4448 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4449 mCurrentCookedState.mouseIdBits.markBit(id);
4450 }
4451 }
4452 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4453 !idBits.isEmpty(); ) {
4454 uint32_t id = idBits.clearFirstMarkedBit();
4455 const RawPointerData::Pointer& pointer =
4456 mCurrentRawState.rawPointerData.pointerForId(id);
4457 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4458 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4459 mCurrentCookedState.stylusIdBits.markBit(id);
4460 }
4461 }
4462
4463 // Stylus takes precedence over all tools, then mouse, then finger.
4464 PointerUsage pointerUsage = mPointerUsage;
4465 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4466 mCurrentCookedState.mouseIdBits.clear();
4467 mCurrentCookedState.fingerIdBits.clear();
4468 pointerUsage = POINTER_USAGE_STYLUS;
4469 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4470 mCurrentCookedState.fingerIdBits.clear();
4471 pointerUsage = POINTER_USAGE_MOUSE;
4472 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4473 isPointerDown(mCurrentRawState.buttonState)) {
4474 pointerUsage = POINTER_USAGE_GESTURES;
4475 }
4476
4477 dispatchPointerUsage(when, policyFlags, pointerUsage);
4478 } else {
4479 if (mDeviceMode == DEVICE_MODE_DIRECT
4480 && mConfig.showTouches && mPointerController != NULL) {
4481 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4482 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4483
4484 mPointerController->setButtonState(mCurrentRawState.buttonState);
4485 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4486 mCurrentCookedState.cookedPointerData.idToIndex,
4487 mCurrentCookedState.cookedPointerData.touchingIdBits);
4488 }
4489
Michael Wright8e812822015-06-22 16:18:21 +01004490 if (!mCurrentMotionAborted) {
4491 dispatchButtonRelease(when, policyFlags);
4492 dispatchHoverExit(when, policyFlags);
4493 dispatchTouches(when, policyFlags);
4494 dispatchHoverEnterAndMove(when, policyFlags);
4495 dispatchButtonPress(when, policyFlags);
4496 }
4497
4498 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4499 mCurrentMotionAborted = false;
4500 }
Michael Wright842500e2015-03-13 17:32:02 -07004501 }
4502
4503 // Synthesize key up from raw buttons if needed.
4504 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004505 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004506
4507 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004508 mCurrentRawState.rawVScroll = 0;
4509 mCurrentRawState.rawHScroll = 0;
4510
4511 // Copy current touch to last touch in preparation for the next cycle.
4512 mLastRawState.copyFrom(mCurrentRawState);
4513 mLastCookedState.copyFrom(mCurrentCookedState);
4514}
4515
4516void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004517 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004518 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4519 }
4520}
4521
4522void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004523 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4524 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004525
Michael Wright53dca3a2015-04-23 17:39:53 +01004526 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4527 float pressure = mExternalStylusState.pressure;
4528 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4529 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4530 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4531 }
4532 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4533 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4534
4535 PointerProperties& properties =
4536 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004537 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4538 properties.toolType = mExternalStylusState.toolType;
4539 }
4540 }
4541}
4542
4543bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4544 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4545 return false;
4546 }
4547
4548 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4549 && state.rawPointerData.pointerCount != 0;
4550 if (initialDown) {
4551 if (mExternalStylusState.pressure != 0.0f) {
4552#if DEBUG_STYLUS_FUSION
4553 ALOGD("Have both stylus and touch data, beginning fusion");
4554#endif
4555 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4556 } else if (timeout) {
4557#if DEBUG_STYLUS_FUSION
4558 ALOGD("Timeout expired, assuming touch is not a stylus.");
4559#endif
4560 resetExternalStylus();
4561 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004562 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4563 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004564 }
4565#if DEBUG_STYLUS_FUSION
4566 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004567 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004568#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004569 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004570 return true;
4571 }
4572 }
4573
4574 // Check if the stylus pointer has gone up.
4575 if (mExternalStylusId != -1 &&
4576 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4577#if DEBUG_STYLUS_FUSION
4578 ALOGD("Stylus pointer is going up");
4579#endif
4580 mExternalStylusId = -1;
4581 }
4582
4583 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004584}
4585
4586void TouchInputMapper::timeoutExpired(nsecs_t when) {
4587 if (mDeviceMode == DEVICE_MODE_POINTER) {
4588 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4589 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4590 }
Michael Wright842500e2015-03-13 17:32:02 -07004591 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004592 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004593 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004594 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4595 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004596 }
4597 }
4598}
4599
4600void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004601 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004602 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004603 // We're either in the middle of a fused stream of data or we're waiting on data before
4604 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4605 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004606 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004607 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608 }
4609}
4610
4611bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4612 // Check for release of a virtual key.
4613 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004614 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004615 // Pointer went up while virtual key was down.
4616 mCurrentVirtualKey.down = false;
4617 if (!mCurrentVirtualKey.ignored) {
4618#if DEBUG_VIRTUAL_KEYS
4619 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4620 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4621#endif
4622 dispatchVirtualKey(when, policyFlags,
4623 AKEY_EVENT_ACTION_UP,
4624 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4625 }
4626 return true;
4627 }
4628
Michael Wright842500e2015-03-13 17:32:02 -07004629 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4630 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4631 const RawPointerData::Pointer& pointer =
4632 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4634 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4635 // Pointer is still within the space of the virtual key.
4636 return true;
4637 }
4638 }
4639
4640 // Pointer left virtual key area or another pointer also went down.
4641 // Send key cancellation but do not consume the touch yet.
4642 // This is useful when the user swipes through from the virtual key area
4643 // into the main display surface.
4644 mCurrentVirtualKey.down = false;
4645 if (!mCurrentVirtualKey.ignored) {
4646#if DEBUG_VIRTUAL_KEYS
4647 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4648 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4649#endif
4650 dispatchVirtualKey(when, policyFlags,
4651 AKEY_EVENT_ACTION_UP,
4652 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4653 | AKEY_EVENT_FLAG_CANCELED);
4654 }
4655 }
4656
Michael Wright842500e2015-03-13 17:32:02 -07004657 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4658 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004660 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4661 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4663 // If exactly one pointer went down, check for virtual key hit.
4664 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004665 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4667 if (virtualKey) {
4668 mCurrentVirtualKey.down = true;
4669 mCurrentVirtualKey.downTime = when;
4670 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4671 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4672 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4673 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4674
4675 if (!mCurrentVirtualKey.ignored) {
4676#if DEBUG_VIRTUAL_KEYS
4677 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4678 mCurrentVirtualKey.keyCode,
4679 mCurrentVirtualKey.scanCode);
4680#endif
4681 dispatchVirtualKey(when, policyFlags,
4682 AKEY_EVENT_ACTION_DOWN,
4683 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4684 }
4685 }
4686 }
4687 return true;
4688 }
4689 }
4690
4691 // Disable all virtual key touches that happen within a short time interval of the
4692 // most recent touch within the screen area. The idea is to filter out stray
4693 // virtual key presses when interacting with the touch screen.
4694 //
4695 // Problems we're trying to solve:
4696 //
4697 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4698 // virtual key area that is implemented by a separate touch panel and accidentally
4699 // triggers a virtual key.
4700 //
4701 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4702 // area and accidentally triggers a virtual key. This often happens when virtual keys
4703 // are layed out below the screen near to where the on screen keyboard's space bar
4704 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004705 if (mConfig.virtualKeyQuietTime > 0 &&
4706 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4708 }
4709 return false;
4710}
4711
4712void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4713 int32_t keyEventAction, int32_t keyEventFlags) {
4714 int32_t keyCode = mCurrentVirtualKey.keyCode;
4715 int32_t scanCode = mCurrentVirtualKey.scanCode;
4716 nsecs_t downTime = mCurrentVirtualKey.downTime;
4717 int32_t metaState = mContext->getGlobalMetaState();
4718 policyFlags |= POLICY_FLAG_VIRTUAL;
4719
4720 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4721 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4722 getListener()->notifyKey(&args);
4723}
4724
Michael Wright8e812822015-06-22 16:18:21 +01004725void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4726 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4727 if (!currentIdBits.isEmpty()) {
4728 int32_t metaState = getContext()->getGlobalMetaState();
4729 int32_t buttonState = mCurrentCookedState.buttonState;
4730 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4731 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4732 mCurrentCookedState.cookedPointerData.pointerProperties,
4733 mCurrentCookedState.cookedPointerData.pointerCoords,
4734 mCurrentCookedState.cookedPointerData.idToIndex,
4735 currentIdBits, -1,
4736 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4737 mCurrentMotionAborted = true;
4738 }
4739}
4740
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004742 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4743 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004745 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746
4747 if (currentIdBits == lastIdBits) {
4748 if (!currentIdBits.isEmpty()) {
4749 // No pointer id changes so this is a move event.
4750 // The listener takes care of batching moves so we don't have to deal with that here.
4751 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004752 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004754 mCurrentCookedState.cookedPointerData.pointerProperties,
4755 mCurrentCookedState.cookedPointerData.pointerCoords,
4756 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757 currentIdBits, -1,
4758 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4759 }
4760 } else {
4761 // There may be pointers going up and pointers going down and pointers moving
4762 // all at the same time.
4763 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4764 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4765 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4766 BitSet32 dispatchedIdBits(lastIdBits.value);
4767
4768 // Update last coordinates of pointers that have moved so that we observe the new
4769 // pointer positions at the same time as other pointers that have just gone up.
4770 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004771 mCurrentCookedState.cookedPointerData.pointerProperties,
4772 mCurrentCookedState.cookedPointerData.pointerCoords,
4773 mCurrentCookedState.cookedPointerData.idToIndex,
4774 mLastCookedState.cookedPointerData.pointerProperties,
4775 mLastCookedState.cookedPointerData.pointerCoords,
4776 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004778 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004779 moveNeeded = true;
4780 }
4781
4782 // Dispatch pointer up events.
4783 while (!upIdBits.isEmpty()) {
4784 uint32_t upId = upIdBits.clearFirstMarkedBit();
4785
4786 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004787 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004788 mLastCookedState.cookedPointerData.pointerProperties,
4789 mLastCookedState.cookedPointerData.pointerCoords,
4790 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004791 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792 dispatchedIdBits.clearBit(upId);
4793 }
4794
4795 // Dispatch move events if any of the remaining pointers moved from their old locations.
4796 // Although applications receive new locations as part of individual pointer up
4797 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004798 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4800 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004801 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004802 mCurrentCookedState.cookedPointerData.pointerProperties,
4803 mCurrentCookedState.cookedPointerData.pointerCoords,
4804 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004805 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 }
4807
4808 // Dispatch pointer down events using the new pointer locations.
4809 while (!downIdBits.isEmpty()) {
4810 uint32_t downId = downIdBits.clearFirstMarkedBit();
4811 dispatchedIdBits.markBit(downId);
4812
4813 if (dispatchedIdBits.count() == 1) {
4814 // First pointer is going down. Set down time.
4815 mDownTime = when;
4816 }
4817
4818 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004819 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004820 mCurrentCookedState.cookedPointerData.pointerProperties,
4821 mCurrentCookedState.cookedPointerData.pointerCoords,
4822 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004823 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824 }
4825 }
4826}
4827
4828void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4829 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004830 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4831 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 int32_t metaState = getContext()->getGlobalMetaState();
4833 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004834 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004835 mLastCookedState.cookedPointerData.pointerProperties,
4836 mLastCookedState.cookedPointerData.pointerCoords,
4837 mLastCookedState.cookedPointerData.idToIndex,
4838 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4840 mSentHoverEnter = false;
4841 }
4842}
4843
4844void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004845 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4846 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 int32_t metaState = getContext()->getGlobalMetaState();
4848 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004849 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004850 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004851 mCurrentCookedState.cookedPointerData.pointerProperties,
4852 mCurrentCookedState.cookedPointerData.pointerCoords,
4853 mCurrentCookedState.cookedPointerData.idToIndex,
4854 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4856 mSentHoverEnter = true;
4857 }
4858
4859 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004860 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004861 mCurrentRawState.buttonState, 0,
4862 mCurrentCookedState.cookedPointerData.pointerProperties,
4863 mCurrentCookedState.cookedPointerData.pointerCoords,
4864 mCurrentCookedState.cookedPointerData.idToIndex,
4865 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4867 }
4868}
4869
Michael Wright7b159c92015-05-14 14:48:03 +01004870void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4871 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4872 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4873 const int32_t metaState = getContext()->getGlobalMetaState();
4874 int32_t buttonState = mLastCookedState.buttonState;
4875 while (!releasedButtons.isEmpty()) {
4876 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4877 buttonState &= ~actionButton;
4878 dispatchMotion(when, policyFlags, mSource,
4879 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4880 0, metaState, buttonState, 0,
4881 mCurrentCookedState.cookedPointerData.pointerProperties,
4882 mCurrentCookedState.cookedPointerData.pointerCoords,
4883 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4884 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4885 }
4886}
4887
4888void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4889 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4890 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4891 const int32_t metaState = getContext()->getGlobalMetaState();
4892 int32_t buttonState = mLastCookedState.buttonState;
4893 while (!pressedButtons.isEmpty()) {
4894 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4895 buttonState |= actionButton;
4896 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4897 0, metaState, buttonState, 0,
4898 mCurrentCookedState.cookedPointerData.pointerProperties,
4899 mCurrentCookedState.cookedPointerData.pointerCoords,
4900 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4901 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4902 }
4903}
4904
4905const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4906 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4907 return cookedPointerData.touchingIdBits;
4908 }
4909 return cookedPointerData.hoveringIdBits;
4910}
4911
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004913 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914
Michael Wright842500e2015-03-13 17:32:02 -07004915 mCurrentCookedState.cookedPointerData.clear();
4916 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4917 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4918 mCurrentRawState.rawPointerData.hoveringIdBits;
4919 mCurrentCookedState.cookedPointerData.touchingIdBits =
4920 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921
Michael Wright7b159c92015-05-14 14:48:03 +01004922 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4923 mCurrentCookedState.buttonState = 0;
4924 } else {
4925 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4926 }
4927
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928 // Walk through the the active pointers and map device coordinates onto
4929 // surface coordinates and adjust for display orientation.
4930 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004931 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004932
4933 // Size
4934 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4935 switch (mCalibration.sizeCalibration) {
4936 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4937 case Calibration::SIZE_CALIBRATION_DIAMETER:
4938 case Calibration::SIZE_CALIBRATION_BOX:
4939 case Calibration::SIZE_CALIBRATION_AREA:
4940 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4941 touchMajor = in.touchMajor;
4942 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4943 toolMajor = in.toolMajor;
4944 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4945 size = mRawPointerAxes.touchMinor.valid
4946 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4947 } else if (mRawPointerAxes.touchMajor.valid) {
4948 toolMajor = touchMajor = in.touchMajor;
4949 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4950 ? in.touchMinor : in.touchMajor;
4951 size = mRawPointerAxes.touchMinor.valid
4952 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4953 } else if (mRawPointerAxes.toolMajor.valid) {
4954 touchMajor = toolMajor = in.toolMajor;
4955 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4956 ? in.toolMinor : in.toolMajor;
4957 size = mRawPointerAxes.toolMinor.valid
4958 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4959 } else {
4960 ALOG_ASSERT(false, "No touch or tool axes. "
4961 "Size calibration should have been resolved to NONE.");
4962 touchMajor = 0;
4963 touchMinor = 0;
4964 toolMajor = 0;
4965 toolMinor = 0;
4966 size = 0;
4967 }
4968
4969 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004970 uint32_t touchingCount =
4971 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972 if (touchingCount > 1) {
4973 touchMajor /= touchingCount;
4974 touchMinor /= touchingCount;
4975 toolMajor /= touchingCount;
4976 toolMinor /= touchingCount;
4977 size /= touchingCount;
4978 }
4979 }
4980
4981 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4982 touchMajor *= mGeometricScale;
4983 touchMinor *= mGeometricScale;
4984 toolMajor *= mGeometricScale;
4985 toolMinor *= mGeometricScale;
4986 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4987 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4988 touchMinor = touchMajor;
4989 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4990 toolMinor = toolMajor;
4991 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4992 touchMinor = touchMajor;
4993 toolMinor = toolMajor;
4994 }
4995
4996 mCalibration.applySizeScaleAndBias(&touchMajor);
4997 mCalibration.applySizeScaleAndBias(&touchMinor);
4998 mCalibration.applySizeScaleAndBias(&toolMajor);
4999 mCalibration.applySizeScaleAndBias(&toolMinor);
5000 size *= mSizeScale;
5001 break;
5002 default:
5003 touchMajor = 0;
5004 touchMinor = 0;
5005 toolMajor = 0;
5006 toolMinor = 0;
5007 size = 0;
5008 break;
5009 }
5010
5011 // Pressure
5012 float pressure;
5013 switch (mCalibration.pressureCalibration) {
5014 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5015 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5016 pressure = in.pressure * mPressureScale;
5017 break;
5018 default:
5019 pressure = in.isHovering ? 0 : 1;
5020 break;
5021 }
5022
5023 // Tilt and Orientation
5024 float tilt;
5025 float orientation;
5026 if (mHaveTilt) {
5027 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5028 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5029 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5030 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5031 } else {
5032 tilt = 0;
5033
5034 switch (mCalibration.orientationCalibration) {
5035 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5036 orientation = in.orientation * mOrientationScale;
5037 break;
5038 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5039 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5040 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5041 if (c1 != 0 || c2 != 0) {
5042 orientation = atan2f(c1, c2) * 0.5f;
5043 float confidence = hypotf(c1, c2);
5044 float scale = 1.0f + confidence / 16.0f;
5045 touchMajor *= scale;
5046 touchMinor /= scale;
5047 toolMajor *= scale;
5048 toolMinor /= scale;
5049 } else {
5050 orientation = 0;
5051 }
5052 break;
5053 }
5054 default:
5055 orientation = 0;
5056 }
5057 }
5058
5059 // Distance
5060 float distance;
5061 switch (mCalibration.distanceCalibration) {
5062 case Calibration::DISTANCE_CALIBRATION_SCALED:
5063 distance = in.distance * mDistanceScale;
5064 break;
5065 default:
5066 distance = 0;
5067 }
5068
5069 // Coverage
5070 int32_t rawLeft, rawTop, rawRight, rawBottom;
5071 switch (mCalibration.coverageCalibration) {
5072 case Calibration::COVERAGE_CALIBRATION_BOX:
5073 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5074 rawRight = in.toolMinor & 0x0000ffff;
5075 rawBottom = in.toolMajor & 0x0000ffff;
5076 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5077 break;
5078 default:
5079 rawLeft = rawTop = rawRight = rawBottom = 0;
5080 break;
5081 }
5082
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005083 // Adjust X,Y coords for device calibration
5084 // TODO: Adjust coverage coords?
5085 float xTransformed = in.x, yTransformed = in.y;
5086 mAffineTransform.applyTo(xTransformed, yTransformed);
5087
5088 // Adjust X, Y, and coverage coords for surface orientation.
5089 float x, y;
5090 float left, top, right, bottom;
5091
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 switch (mSurfaceOrientation) {
5093 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005094 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5095 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005096 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5097 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5098 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5099 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5100 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005101 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5103 }
5104 break;
5105 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005106 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5107 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005108 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5109 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5110 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5111 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5112 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005113 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5115 }
5116 break;
5117 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005118 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5119 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5121 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5122 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5123 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5124 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005125 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5127 }
5128 break;
5129 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005130 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5131 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5133 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5134 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5135 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5136 break;
5137 }
5138
5139 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005140 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 out.clear();
5142 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5143 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5144 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5145 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5146 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5147 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5148 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5149 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5150 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5151 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5152 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5153 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5154 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5155 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5156 } else {
5157 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5158 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5159 }
5160
5161 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005162 PointerProperties& properties =
5163 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 uint32_t id = in.id;
5165 properties.clear();
5166 properties.id = id;
5167 properties.toolType = in.toolType;
5168
5169 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005170 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 }
5172}
5173
5174void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5175 PointerUsage pointerUsage) {
5176 if (pointerUsage != mPointerUsage) {
5177 abortPointerUsage(when, policyFlags);
5178 mPointerUsage = pointerUsage;
5179 }
5180
5181 switch (mPointerUsage) {
5182 case POINTER_USAGE_GESTURES:
5183 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5184 break;
5185 case POINTER_USAGE_STYLUS:
5186 dispatchPointerStylus(when, policyFlags);
5187 break;
5188 case POINTER_USAGE_MOUSE:
5189 dispatchPointerMouse(when, policyFlags);
5190 break;
5191 default:
5192 break;
5193 }
5194}
5195
5196void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5197 switch (mPointerUsage) {
5198 case POINTER_USAGE_GESTURES:
5199 abortPointerGestures(when, policyFlags);
5200 break;
5201 case POINTER_USAGE_STYLUS:
5202 abortPointerStylus(when, policyFlags);
5203 break;
5204 case POINTER_USAGE_MOUSE:
5205 abortPointerMouse(when, policyFlags);
5206 break;
5207 default:
5208 break;
5209 }
5210
5211 mPointerUsage = POINTER_USAGE_NONE;
5212}
5213
5214void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5215 bool isTimeout) {
5216 // Update current gesture coordinates.
5217 bool cancelPreviousGesture, finishPreviousGesture;
5218 bool sendEvents = preparePointerGestures(when,
5219 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5220 if (!sendEvents) {
5221 return;
5222 }
5223 if (finishPreviousGesture) {
5224 cancelPreviousGesture = false;
5225 }
5226
5227 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005228 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5229 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005230 if (finishPreviousGesture || cancelPreviousGesture) {
5231 mPointerController->clearSpots();
5232 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005233
5234 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5235 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5236 mPointerGesture.currentGestureIdToIndex,
5237 mPointerGesture.currentGestureIdBits);
5238 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239 } else {
5240 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5241 }
5242
5243 // Show or hide the pointer if needed.
5244 switch (mPointerGesture.currentGestureMode) {
5245 case PointerGesture::NEUTRAL:
5246 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005247 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5248 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249 // Remind the user of where the pointer is after finishing a gesture with spots.
5250 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5251 }
5252 break;
5253 case PointerGesture::TAP:
5254 case PointerGesture::TAP_DRAG:
5255 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5256 case PointerGesture::HOVER:
5257 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005258 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 // Unfade the pointer when the current gesture manipulates the
5260 // area directly under the pointer.
5261 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5262 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 case PointerGesture::FREEFORM:
5264 // Fade the pointer when the current gesture manipulates a different
5265 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005266 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5268 } else {
5269 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5270 }
5271 break;
5272 }
5273
5274 // Send events!
5275 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005276 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277
5278 // Update last coordinates of pointers that have moved so that we observe the new
5279 // pointer positions at the same time as other pointers that have just gone up.
5280 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5281 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5282 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5283 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5284 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5285 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5286 bool moveNeeded = false;
5287 if (down && !cancelPreviousGesture && !finishPreviousGesture
5288 && !mPointerGesture.lastGestureIdBits.isEmpty()
5289 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5290 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5291 & mPointerGesture.lastGestureIdBits.value);
5292 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5293 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5294 mPointerGesture.lastGestureProperties,
5295 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5296 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005297 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 moveNeeded = true;
5299 }
5300 }
5301
5302 // Send motion events for all pointers that went up or were canceled.
5303 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5304 if (!dispatchedGestureIdBits.isEmpty()) {
5305 if (cancelPreviousGesture) {
5306 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005307 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 AMOTION_EVENT_EDGE_FLAG_NONE,
5309 mPointerGesture.lastGestureProperties,
5310 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005311 dispatchedGestureIdBits, -1, 0,
5312 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313
5314 dispatchedGestureIdBits.clear();
5315 } else {
5316 BitSet32 upGestureIdBits;
5317 if (finishPreviousGesture) {
5318 upGestureIdBits = dispatchedGestureIdBits;
5319 } else {
5320 upGestureIdBits.value = dispatchedGestureIdBits.value
5321 & ~mPointerGesture.currentGestureIdBits.value;
5322 }
5323 while (!upGestureIdBits.isEmpty()) {
5324 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5325
5326 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005327 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5329 mPointerGesture.lastGestureProperties,
5330 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5331 dispatchedGestureIdBits, id,
5332 0, 0, mPointerGesture.downTime);
5333
5334 dispatchedGestureIdBits.clearBit(id);
5335 }
5336 }
5337 }
5338
5339 // Send motion events for all pointers that moved.
5340 if (moveNeeded) {
5341 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005342 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5343 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344 mPointerGesture.currentGestureProperties,
5345 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5346 dispatchedGestureIdBits, -1,
5347 0, 0, mPointerGesture.downTime);
5348 }
5349
5350 // Send motion events for all pointers that went down.
5351 if (down) {
5352 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5353 & ~dispatchedGestureIdBits.value);
5354 while (!downGestureIdBits.isEmpty()) {
5355 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5356 dispatchedGestureIdBits.markBit(id);
5357
5358 if (dispatchedGestureIdBits.count() == 1) {
5359 mPointerGesture.downTime = when;
5360 }
5361
5362 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005363 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364 mPointerGesture.currentGestureProperties,
5365 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5366 dispatchedGestureIdBits, id,
5367 0, 0, mPointerGesture.downTime);
5368 }
5369 }
5370
5371 // Send motion events for hover.
5372 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5373 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005374 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5376 mPointerGesture.currentGestureProperties,
5377 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5378 mPointerGesture.currentGestureIdBits, -1,
5379 0, 0, mPointerGesture.downTime);
5380 } else if (dispatchedGestureIdBits.isEmpty()
5381 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5382 // Synthesize a hover move event after all pointers go up to indicate that
5383 // the pointer is hovering again even if the user is not currently touching
5384 // the touch pad. This ensures that a view will receive a fresh hover enter
5385 // event after a tap.
5386 float x, y;
5387 mPointerController->getPosition(&x, &y);
5388
5389 PointerProperties pointerProperties;
5390 pointerProperties.clear();
5391 pointerProperties.id = 0;
5392 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5393
5394 PointerCoords pointerCoords;
5395 pointerCoords.clear();
5396 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5397 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5398
5399 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005400 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005401 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5402 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5403 0, 0, mPointerGesture.downTime);
5404 getListener()->notifyMotion(&args);
5405 }
5406
5407 // Update state.
5408 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5409 if (!down) {
5410 mPointerGesture.lastGestureIdBits.clear();
5411 } else {
5412 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5413 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5414 uint32_t id = idBits.clearFirstMarkedBit();
5415 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5416 mPointerGesture.lastGestureProperties[index].copyFrom(
5417 mPointerGesture.currentGestureProperties[index]);
5418 mPointerGesture.lastGestureCoords[index].copyFrom(
5419 mPointerGesture.currentGestureCoords[index]);
5420 mPointerGesture.lastGestureIdToIndex[id] = index;
5421 }
5422 }
5423}
5424
5425void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5426 // Cancel previously dispatches pointers.
5427 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5428 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005429 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005430 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005431 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005432 AMOTION_EVENT_EDGE_FLAG_NONE,
5433 mPointerGesture.lastGestureProperties,
5434 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5435 mPointerGesture.lastGestureIdBits, -1,
5436 0, 0, mPointerGesture.downTime);
5437 }
5438
5439 // Reset the current pointer gesture.
5440 mPointerGesture.reset();
5441 mPointerVelocityControl.reset();
5442
5443 // Remove any current spots.
5444 if (mPointerController != NULL) {
5445 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5446 mPointerController->clearSpots();
5447 }
5448}
5449
5450bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5451 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5452 *outCancelPreviousGesture = false;
5453 *outFinishPreviousGesture = false;
5454
5455 // Handle TAP timeout.
5456 if (isTimeout) {
5457#if DEBUG_GESTURES
5458 ALOGD("Gestures: Processing timeout");
5459#endif
5460
5461 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5462 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5463 // The tap/drag timeout has not yet expired.
5464 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5465 + mConfig.pointerGestureTapDragInterval);
5466 } else {
5467 // The tap is finished.
5468#if DEBUG_GESTURES
5469 ALOGD("Gestures: TAP finished");
5470#endif
5471 *outFinishPreviousGesture = true;
5472
5473 mPointerGesture.activeGestureId = -1;
5474 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5475 mPointerGesture.currentGestureIdBits.clear();
5476
5477 mPointerVelocityControl.reset();
5478 return true;
5479 }
5480 }
5481
5482 // We did not handle this timeout.
5483 return false;
5484 }
5485
Michael Wright842500e2015-03-13 17:32:02 -07005486 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5487 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488
5489 // Update the velocity tracker.
5490 {
5491 VelocityTracker::Position positions[MAX_POINTERS];
5492 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005493 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005494 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005495 const RawPointerData::Pointer& pointer =
5496 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 positions[count].x = pointer.x * mPointerXMovementScale;
5498 positions[count].y = pointer.y * mPointerYMovementScale;
5499 }
5500 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005501 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502 }
5503
5504 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5505 // to NEUTRAL, then we should not generate tap event.
5506 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5507 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5508 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5509 mPointerGesture.resetTap();
5510 }
5511
5512 // Pick a new active touch id if needed.
5513 // Choose an arbitrary pointer that just went down, if there is one.
5514 // Otherwise choose an arbitrary remaining pointer.
5515 // This guarantees we always have an active touch id when there is at least one pointer.
5516 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5518 int32_t activeTouchId = lastActiveTouchId;
5519 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005520 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005521 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005522 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005523 mPointerGesture.firstTouchTime = when;
5524 }
Michael Wright842500e2015-03-13 17:32:02 -07005525 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005526 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005527 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005528 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529 } else {
5530 activeTouchId = mPointerGesture.activeTouchId = -1;
5531 }
5532 }
5533
5534 // Determine whether we are in quiet time.
5535 bool isQuietTime = false;
5536 if (activeTouchId < 0) {
5537 mPointerGesture.resetQuietTime();
5538 } else {
5539 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5540 if (!isQuietTime) {
5541 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5542 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5543 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5544 && currentFingerCount < 2) {
5545 // Enter quiet time when exiting swipe or freeform state.
5546 // This is to prevent accidentally entering the hover state and flinging the
5547 // pointer when finishing a swipe and there is still one pointer left onscreen.
5548 isQuietTime = true;
5549 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5550 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005551 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552 // Enter quiet time when releasing the button and there are still two or more
5553 // fingers down. This may indicate that one finger was used to press the button
5554 // but it has not gone up yet.
5555 isQuietTime = true;
5556 }
5557 if (isQuietTime) {
5558 mPointerGesture.quietTime = when;
5559 }
5560 }
5561 }
5562
5563 // Switch states based on button and pointer state.
5564 if (isQuietTime) {
5565 // Case 1: Quiet time. (QUIET)
5566#if DEBUG_GESTURES
5567 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5568 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5569#endif
5570 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5571 *outFinishPreviousGesture = true;
5572 }
5573
5574 mPointerGesture.activeGestureId = -1;
5575 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5576 mPointerGesture.currentGestureIdBits.clear();
5577
5578 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005579 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005580 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5581 // The pointer follows the active touch point.
5582 // Emit DOWN, MOVE, UP events at the pointer location.
5583 //
5584 // Only the active touch matters; other fingers are ignored. This policy helps
5585 // to handle the case where the user places a second finger on the touch pad
5586 // to apply the necessary force to depress an integrated button below the surface.
5587 // We don't want the second finger to be delivered to applications.
5588 //
5589 // For this to work well, we need to make sure to track the pointer that is really
5590 // active. If the user first puts one finger down to click then adds another
5591 // finger to drag then the active pointer should switch to the finger that is
5592 // being dragged.
5593#if DEBUG_GESTURES
5594 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5595 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5596#endif
5597 // Reset state when just starting.
5598 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5599 *outFinishPreviousGesture = true;
5600 mPointerGesture.activeGestureId = 0;
5601 }
5602
5603 // Switch pointers if needed.
5604 // Find the fastest pointer and follow it.
5605 if (activeTouchId >= 0 && currentFingerCount > 1) {
5606 int32_t bestId = -1;
5607 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005608 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609 uint32_t id = idBits.clearFirstMarkedBit();
5610 float vx, vy;
5611 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5612 float speed = hypotf(vx, vy);
5613 if (speed > bestSpeed) {
5614 bestId = id;
5615 bestSpeed = speed;
5616 }
5617 }
5618 }
5619 if (bestId >= 0 && bestId != activeTouchId) {
5620 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621#if DEBUG_GESTURES
5622 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5623 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5624#endif
5625 }
5626 }
5627
Jun Mukaifa1706a2015-12-03 01:14:46 -08005628 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005629 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005631 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005633 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005634 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5635 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636
5637 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5638 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5639
5640 // Move the pointer using a relative motion.
5641 // When using spots, the click will occur at the position of the anchor
5642 // spot and all other spots will move there.
5643 mPointerController->move(deltaX, deltaY);
5644 } else {
5645 mPointerVelocityControl.reset();
5646 }
5647
5648 float x, y;
5649 mPointerController->getPosition(&x, &y);
5650
5651 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5652 mPointerGesture.currentGestureIdBits.clear();
5653 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5654 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5655 mPointerGesture.currentGestureProperties[0].clear();
5656 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5657 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5658 mPointerGesture.currentGestureCoords[0].clear();
5659 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5660 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5661 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5662 } else if (currentFingerCount == 0) {
5663 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5664 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5665 *outFinishPreviousGesture = true;
5666 }
5667
5668 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5669 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5670 bool tapped = false;
5671 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5672 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5673 && lastFingerCount == 1) {
5674 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5675 float x, y;
5676 mPointerController->getPosition(&x, &y);
5677 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5678 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5679#if DEBUG_GESTURES
5680 ALOGD("Gestures: TAP");
5681#endif
5682
5683 mPointerGesture.tapUpTime = when;
5684 getContext()->requestTimeoutAtTime(when
5685 + mConfig.pointerGestureTapDragInterval);
5686
5687 mPointerGesture.activeGestureId = 0;
5688 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5689 mPointerGesture.currentGestureIdBits.clear();
5690 mPointerGesture.currentGestureIdBits.markBit(
5691 mPointerGesture.activeGestureId);
5692 mPointerGesture.currentGestureIdToIndex[
5693 mPointerGesture.activeGestureId] = 0;
5694 mPointerGesture.currentGestureProperties[0].clear();
5695 mPointerGesture.currentGestureProperties[0].id =
5696 mPointerGesture.activeGestureId;
5697 mPointerGesture.currentGestureProperties[0].toolType =
5698 AMOTION_EVENT_TOOL_TYPE_FINGER;
5699 mPointerGesture.currentGestureCoords[0].clear();
5700 mPointerGesture.currentGestureCoords[0].setAxisValue(
5701 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5702 mPointerGesture.currentGestureCoords[0].setAxisValue(
5703 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5704 mPointerGesture.currentGestureCoords[0].setAxisValue(
5705 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5706
5707 tapped = true;
5708 } else {
5709#if DEBUG_GESTURES
5710 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5711 x - mPointerGesture.tapX,
5712 y - mPointerGesture.tapY);
5713#endif
5714 }
5715 } else {
5716#if DEBUG_GESTURES
5717 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5718 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5719 (when - mPointerGesture.tapDownTime) * 0.000001f);
5720 } else {
5721 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5722 }
5723#endif
5724 }
5725 }
5726
5727 mPointerVelocityControl.reset();
5728
5729 if (!tapped) {
5730#if DEBUG_GESTURES
5731 ALOGD("Gestures: NEUTRAL");
5732#endif
5733 mPointerGesture.activeGestureId = -1;
5734 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5735 mPointerGesture.currentGestureIdBits.clear();
5736 }
5737 } else if (currentFingerCount == 1) {
5738 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5739 // The pointer follows the active touch point.
5740 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5741 // When in TAP_DRAG, emit MOVE events at the pointer location.
5742 ALOG_ASSERT(activeTouchId >= 0);
5743
5744 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5745 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5746 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5747 float x, y;
5748 mPointerController->getPosition(&x, &y);
5749 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5750 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5751 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5752 } else {
5753#if DEBUG_GESTURES
5754 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5755 x - mPointerGesture.tapX,
5756 y - mPointerGesture.tapY);
5757#endif
5758 }
5759 } else {
5760#if DEBUG_GESTURES
5761 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5762 (when - mPointerGesture.tapUpTime) * 0.000001f);
5763#endif
5764 }
5765 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5766 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5767 }
5768
Jun Mukaifa1706a2015-12-03 01:14:46 -08005769 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005770 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005772 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005774 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005775 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5776 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777
5778 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5779 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5780
5781 // Move the pointer using a relative motion.
5782 // When using spots, the hover or drag will occur at the position of the anchor spot.
5783 mPointerController->move(deltaX, deltaY);
5784 } else {
5785 mPointerVelocityControl.reset();
5786 }
5787
5788 bool down;
5789 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5790#if DEBUG_GESTURES
5791 ALOGD("Gestures: TAP_DRAG");
5792#endif
5793 down = true;
5794 } else {
5795#if DEBUG_GESTURES
5796 ALOGD("Gestures: HOVER");
5797#endif
5798 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5799 *outFinishPreviousGesture = true;
5800 }
5801 mPointerGesture.activeGestureId = 0;
5802 down = false;
5803 }
5804
5805 float x, y;
5806 mPointerController->getPosition(&x, &y);
5807
5808 mPointerGesture.currentGestureIdBits.clear();
5809 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5810 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5811 mPointerGesture.currentGestureProperties[0].clear();
5812 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5813 mPointerGesture.currentGestureProperties[0].toolType =
5814 AMOTION_EVENT_TOOL_TYPE_FINGER;
5815 mPointerGesture.currentGestureCoords[0].clear();
5816 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5817 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5818 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5819 down ? 1.0f : 0.0f);
5820
5821 if (lastFingerCount == 0 && currentFingerCount != 0) {
5822 mPointerGesture.resetTap();
5823 mPointerGesture.tapDownTime = when;
5824 mPointerGesture.tapX = x;
5825 mPointerGesture.tapY = y;
5826 }
5827 } else {
5828 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5829 // We need to provide feedback for each finger that goes down so we cannot wait
5830 // for the fingers to move before deciding what to do.
5831 //
5832 // The ambiguous case is deciding what to do when there are two fingers down but they
5833 // have not moved enough to determine whether they are part of a drag or part of a
5834 // freeform gesture, or just a press or long-press at the pointer location.
5835 //
5836 // When there are two fingers we start with the PRESS hypothesis and we generate a
5837 // down at the pointer location.
5838 //
5839 // When the two fingers move enough or when additional fingers are added, we make
5840 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5841 ALOG_ASSERT(activeTouchId >= 0);
5842
5843 bool settled = when >= mPointerGesture.firstTouchTime
5844 + mConfig.pointerGestureMultitouchSettleInterval;
5845 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5846 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5847 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5848 *outFinishPreviousGesture = true;
5849 } else if (!settled && currentFingerCount > lastFingerCount) {
5850 // Additional pointers have gone down but not yet settled.
5851 // Reset the gesture.
5852#if DEBUG_GESTURES
5853 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5854 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5855 + mConfig.pointerGestureMultitouchSettleInterval - when)
5856 * 0.000001f);
5857#endif
5858 *outCancelPreviousGesture = true;
5859 } else {
5860 // Continue previous gesture.
5861 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5862 }
5863
5864 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5865 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5866 mPointerGesture.activeGestureId = 0;
5867 mPointerGesture.referenceIdBits.clear();
5868 mPointerVelocityControl.reset();
5869
5870 // Use the centroid and pointer location as the reference points for the gesture.
5871#if DEBUG_GESTURES
5872 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5873 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5874 + mConfig.pointerGestureMultitouchSettleInterval - when)
5875 * 0.000001f);
5876#endif
Michael Wright842500e2015-03-13 17:32:02 -07005877 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005878 &mPointerGesture.referenceTouchX,
5879 &mPointerGesture.referenceTouchY);
5880 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5881 &mPointerGesture.referenceGestureY);
5882 }
5883
5884 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005885 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005886 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5887 uint32_t id = idBits.clearFirstMarkedBit();
5888 mPointerGesture.referenceDeltas[id].dx = 0;
5889 mPointerGesture.referenceDeltas[id].dy = 0;
5890 }
Michael Wright842500e2015-03-13 17:32:02 -07005891 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892
5893 // Add delta for all fingers and calculate a common movement delta.
5894 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005895 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5896 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5898 bool first = (idBits == commonIdBits);
5899 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005900 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5901 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5903 delta.dx += cpd.x - lpd.x;
5904 delta.dy += cpd.y - lpd.y;
5905
5906 if (first) {
5907 commonDeltaX = delta.dx;
5908 commonDeltaY = delta.dy;
5909 } else {
5910 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5911 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5912 }
5913 }
5914
5915 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5916 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5917 float dist[MAX_POINTER_ID + 1];
5918 int32_t distOverThreshold = 0;
5919 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5920 uint32_t id = idBits.clearFirstMarkedBit();
5921 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5922 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5923 delta.dy * mPointerYZoomScale);
5924 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5925 distOverThreshold += 1;
5926 }
5927 }
5928
5929 // Only transition when at least two pointers have moved further than
5930 // the minimum distance threshold.
5931 if (distOverThreshold >= 2) {
5932 if (currentFingerCount > 2) {
5933 // There are more than two pointers, switch to FREEFORM.
5934#if DEBUG_GESTURES
5935 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5936 currentFingerCount);
5937#endif
5938 *outCancelPreviousGesture = true;
5939 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5940 } else {
5941 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005942 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005943 uint32_t id1 = idBits.clearFirstMarkedBit();
5944 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005945 const RawPointerData::Pointer& p1 =
5946 mCurrentRawState.rawPointerData.pointerForId(id1);
5947 const RawPointerData::Pointer& p2 =
5948 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005949 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5950 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5951 // There are two pointers but they are too far apart for a SWIPE,
5952 // switch to FREEFORM.
5953#if DEBUG_GESTURES
5954 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5955 mutualDistance, mPointerGestureMaxSwipeWidth);
5956#endif
5957 *outCancelPreviousGesture = true;
5958 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5959 } else {
5960 // There are two pointers. Wait for both pointers to start moving
5961 // before deciding whether this is a SWIPE or FREEFORM gesture.
5962 float dist1 = dist[id1];
5963 float dist2 = dist[id2];
5964 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5965 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5966 // Calculate the dot product of the displacement vectors.
5967 // When the vectors are oriented in approximately the same direction,
5968 // the angle betweeen them is near zero and the cosine of the angle
5969 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5970 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5971 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5972 float dx1 = delta1.dx * mPointerXZoomScale;
5973 float dy1 = delta1.dy * mPointerYZoomScale;
5974 float dx2 = delta2.dx * mPointerXZoomScale;
5975 float dy2 = delta2.dy * mPointerYZoomScale;
5976 float dot = dx1 * dx2 + dy1 * dy2;
5977 float cosine = dot / (dist1 * dist2); // denominator always > 0
5978 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5979 // Pointers are moving in the same direction. Switch to SWIPE.
5980#if DEBUG_GESTURES
5981 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5982 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5983 "cosine %0.3f >= %0.3f",
5984 dist1, mConfig.pointerGestureMultitouchMinDistance,
5985 dist2, mConfig.pointerGestureMultitouchMinDistance,
5986 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5987#endif
5988 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5989 } else {
5990 // Pointers are moving in different directions. Switch to FREEFORM.
5991#if DEBUG_GESTURES
5992 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5993 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5994 "cosine %0.3f < %0.3f",
5995 dist1, mConfig.pointerGestureMultitouchMinDistance,
5996 dist2, mConfig.pointerGestureMultitouchMinDistance,
5997 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5998#endif
5999 *outCancelPreviousGesture = true;
6000 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6001 }
6002 }
6003 }
6004 }
6005 }
6006 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6007 // Switch from SWIPE to FREEFORM if additional pointers go down.
6008 // Cancel previous gesture.
6009 if (currentFingerCount > 2) {
6010#if DEBUG_GESTURES
6011 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6012 currentFingerCount);
6013#endif
6014 *outCancelPreviousGesture = true;
6015 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6016 }
6017 }
6018
6019 // Move the reference points based on the overall group motion of the fingers
6020 // except in PRESS mode while waiting for a transition to occur.
6021 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6022 && (commonDeltaX || commonDeltaY)) {
6023 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6024 uint32_t id = idBits.clearFirstMarkedBit();
6025 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6026 delta.dx = 0;
6027 delta.dy = 0;
6028 }
6029
6030 mPointerGesture.referenceTouchX += commonDeltaX;
6031 mPointerGesture.referenceTouchY += commonDeltaY;
6032
6033 commonDeltaX *= mPointerXMovementScale;
6034 commonDeltaY *= mPointerYMovementScale;
6035
6036 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6037 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6038
6039 mPointerGesture.referenceGestureX += commonDeltaX;
6040 mPointerGesture.referenceGestureY += commonDeltaY;
6041 }
6042
6043 // Report gestures.
6044 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6045 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6046 // PRESS or SWIPE mode.
6047#if DEBUG_GESTURES
6048 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6049 "activeGestureId=%d, currentTouchPointerCount=%d",
6050 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6051#endif
6052 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6053
6054 mPointerGesture.currentGestureIdBits.clear();
6055 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6056 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6057 mPointerGesture.currentGestureProperties[0].clear();
6058 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6059 mPointerGesture.currentGestureProperties[0].toolType =
6060 AMOTION_EVENT_TOOL_TYPE_FINGER;
6061 mPointerGesture.currentGestureCoords[0].clear();
6062 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6063 mPointerGesture.referenceGestureX);
6064 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6065 mPointerGesture.referenceGestureY);
6066 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6067 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6068 // FREEFORM mode.
6069#if DEBUG_GESTURES
6070 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6071 "activeGestureId=%d, currentTouchPointerCount=%d",
6072 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6073#endif
6074 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6075
6076 mPointerGesture.currentGestureIdBits.clear();
6077
6078 BitSet32 mappedTouchIdBits;
6079 BitSet32 usedGestureIdBits;
6080 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6081 // Initially, assign the active gesture id to the active touch point
6082 // if there is one. No other touch id bits are mapped yet.
6083 if (!*outCancelPreviousGesture) {
6084 mappedTouchIdBits.markBit(activeTouchId);
6085 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6086 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6087 mPointerGesture.activeGestureId;
6088 } else {
6089 mPointerGesture.activeGestureId = -1;
6090 }
6091 } else {
6092 // Otherwise, assume we mapped all touches from the previous frame.
6093 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006094 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6095 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006096 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6097
6098 // Check whether we need to choose a new active gesture id because the
6099 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006100 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6101 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006102 !upTouchIdBits.isEmpty(); ) {
6103 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6104 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6105 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6106 mPointerGesture.activeGestureId = -1;
6107 break;
6108 }
6109 }
6110 }
6111
6112#if DEBUG_GESTURES
6113 ALOGD("Gestures: FREEFORM follow up "
6114 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6115 "activeGestureId=%d",
6116 mappedTouchIdBits.value, usedGestureIdBits.value,
6117 mPointerGesture.activeGestureId);
6118#endif
6119
Michael Wright842500e2015-03-13 17:32:02 -07006120 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006121 for (uint32_t i = 0; i < currentFingerCount; i++) {
6122 uint32_t touchId = idBits.clearFirstMarkedBit();
6123 uint32_t gestureId;
6124 if (!mappedTouchIdBits.hasBit(touchId)) {
6125 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6126 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6127#if DEBUG_GESTURES
6128 ALOGD("Gestures: FREEFORM "
6129 "new mapping for touch id %d -> gesture id %d",
6130 touchId, gestureId);
6131#endif
6132 } else {
6133 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6134#if DEBUG_GESTURES
6135 ALOGD("Gestures: FREEFORM "
6136 "existing mapping for touch id %d -> gesture id %d",
6137 touchId, gestureId);
6138#endif
6139 }
6140 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6141 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6142
6143 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006144 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006145 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6146 * mPointerXZoomScale;
6147 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6148 * mPointerYZoomScale;
6149 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6150
6151 mPointerGesture.currentGestureProperties[i].clear();
6152 mPointerGesture.currentGestureProperties[i].id = gestureId;
6153 mPointerGesture.currentGestureProperties[i].toolType =
6154 AMOTION_EVENT_TOOL_TYPE_FINGER;
6155 mPointerGesture.currentGestureCoords[i].clear();
6156 mPointerGesture.currentGestureCoords[i].setAxisValue(
6157 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6158 mPointerGesture.currentGestureCoords[i].setAxisValue(
6159 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6160 mPointerGesture.currentGestureCoords[i].setAxisValue(
6161 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6162 }
6163
6164 if (mPointerGesture.activeGestureId < 0) {
6165 mPointerGesture.activeGestureId =
6166 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6167#if DEBUG_GESTURES
6168 ALOGD("Gestures: FREEFORM new "
6169 "activeGestureId=%d", mPointerGesture.activeGestureId);
6170#endif
6171 }
6172 }
6173 }
6174
Michael Wright842500e2015-03-13 17:32:02 -07006175 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006176
6177#if DEBUG_GESTURES
6178 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6179 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6180 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6181 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6182 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6183 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6184 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6185 uint32_t id = idBits.clearFirstMarkedBit();
6186 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6187 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6188 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6189 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6190 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6191 id, index, properties.toolType,
6192 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6193 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6194 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6195 }
6196 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6197 uint32_t id = idBits.clearFirstMarkedBit();
6198 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6199 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6200 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6201 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6202 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6203 id, index, properties.toolType,
6204 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6205 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6206 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6207 }
6208#endif
6209 return true;
6210}
6211
6212void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6213 mPointerSimple.currentCoords.clear();
6214 mPointerSimple.currentProperties.clear();
6215
6216 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006217 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6218 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6219 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6220 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6221 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006222 mPointerController->setPosition(x, y);
6223
Michael Wright842500e2015-03-13 17:32:02 -07006224 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006225 down = !hovering;
6226
6227 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006228 mPointerSimple.currentCoords.copyFrom(
6229 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6231 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6232 mPointerSimple.currentProperties.id = 0;
6233 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006234 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006235 } else {
6236 down = false;
6237 hovering = false;
6238 }
6239
6240 dispatchPointerSimple(when, policyFlags, down, hovering);
6241}
6242
6243void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6244 abortPointerSimple(when, policyFlags);
6245}
6246
6247void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6248 mPointerSimple.currentCoords.clear();
6249 mPointerSimple.currentProperties.clear();
6250
6251 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006252 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6253 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6254 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006255 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006256 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6257 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006258 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006259 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006261 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006262 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006263 * mPointerYMovementScale;
6264
6265 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6266 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6267
6268 mPointerController->move(deltaX, deltaY);
6269 } else {
6270 mPointerVelocityControl.reset();
6271 }
6272
Michael Wright842500e2015-03-13 17:32:02 -07006273 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006274 hovering = !down;
6275
6276 float x, y;
6277 mPointerController->getPosition(&x, &y);
6278 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006279 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006280 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6281 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6282 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6283 hovering ? 0.0f : 1.0f);
6284 mPointerSimple.currentProperties.id = 0;
6285 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006286 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006287 } else {
6288 mPointerVelocityControl.reset();
6289
6290 down = false;
6291 hovering = false;
6292 }
6293
6294 dispatchPointerSimple(when, policyFlags, down, hovering);
6295}
6296
6297void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6298 abortPointerSimple(when, policyFlags);
6299
6300 mPointerVelocityControl.reset();
6301}
6302
6303void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6304 bool down, bool hovering) {
6305 int32_t metaState = getContext()->getGlobalMetaState();
6306
6307 if (mPointerController != NULL) {
6308 if (down || hovering) {
6309 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6310 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006311 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006312 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6313 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6314 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6315 }
6316 }
6317
6318 if (mPointerSimple.down && !down) {
6319 mPointerSimple.down = false;
6320
6321 // Send up.
6322 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006323 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006324 mViewport.displayId,
6325 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6326 mOrientedXPrecision, mOrientedYPrecision,
6327 mPointerSimple.downTime);
6328 getListener()->notifyMotion(&args);
6329 }
6330
6331 if (mPointerSimple.hovering && !hovering) {
6332 mPointerSimple.hovering = false;
6333
6334 // Send hover exit.
6335 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006336 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006337 mViewport.displayId,
6338 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6339 mOrientedXPrecision, mOrientedYPrecision,
6340 mPointerSimple.downTime);
6341 getListener()->notifyMotion(&args);
6342 }
6343
6344 if (down) {
6345 if (!mPointerSimple.down) {
6346 mPointerSimple.down = true;
6347 mPointerSimple.downTime = when;
6348
6349 // Send down.
6350 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006351 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006352 mViewport.displayId,
6353 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6354 mOrientedXPrecision, mOrientedYPrecision,
6355 mPointerSimple.downTime);
6356 getListener()->notifyMotion(&args);
6357 }
6358
6359 // Send move.
6360 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006361 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006362 mViewport.displayId,
6363 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6364 mOrientedXPrecision, mOrientedYPrecision,
6365 mPointerSimple.downTime);
6366 getListener()->notifyMotion(&args);
6367 }
6368
6369 if (hovering) {
6370 if (!mPointerSimple.hovering) {
6371 mPointerSimple.hovering = true;
6372
6373 // Send hover enter.
6374 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006375 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006376 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006377 mViewport.displayId,
6378 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6379 mOrientedXPrecision, mOrientedYPrecision,
6380 mPointerSimple.downTime);
6381 getListener()->notifyMotion(&args);
6382 }
6383
6384 // Send hover move.
6385 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006386 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006387 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006388 mViewport.displayId,
6389 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6390 mOrientedXPrecision, mOrientedYPrecision,
6391 mPointerSimple.downTime);
6392 getListener()->notifyMotion(&args);
6393 }
6394
Michael Wright842500e2015-03-13 17:32:02 -07006395 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6396 float vscroll = mCurrentRawState.rawVScroll;
6397 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006398 mWheelYVelocityControl.move(when, NULL, &vscroll);
6399 mWheelXVelocityControl.move(when, &hscroll, NULL);
6400
6401 // Send scroll.
6402 PointerCoords pointerCoords;
6403 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6404 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6405 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6406
6407 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006408 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006409 mViewport.displayId,
6410 1, &mPointerSimple.currentProperties, &pointerCoords,
6411 mOrientedXPrecision, mOrientedYPrecision,
6412 mPointerSimple.downTime);
6413 getListener()->notifyMotion(&args);
6414 }
6415
6416 // Save state.
6417 if (down || hovering) {
6418 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6419 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6420 } else {
6421 mPointerSimple.reset();
6422 }
6423}
6424
6425void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6426 mPointerSimple.currentCoords.clear();
6427 mPointerSimple.currentProperties.clear();
6428
6429 dispatchPointerSimple(when, policyFlags, false, false);
6430}
6431
6432void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006433 int32_t action, int32_t actionButton, int32_t flags,
6434 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006435 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006436 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6437 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006438 PointerCoords pointerCoords[MAX_POINTERS];
6439 PointerProperties pointerProperties[MAX_POINTERS];
6440 uint32_t pointerCount = 0;
6441 while (!idBits.isEmpty()) {
6442 uint32_t id = idBits.clearFirstMarkedBit();
6443 uint32_t index = idToIndex[id];
6444 pointerProperties[pointerCount].copyFrom(properties[index]);
6445 pointerCoords[pointerCount].copyFrom(coords[index]);
6446
6447 if (changedId >= 0 && id == uint32_t(changedId)) {
6448 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6449 }
6450
6451 pointerCount += 1;
6452 }
6453
6454 ALOG_ASSERT(pointerCount != 0);
6455
6456 if (changedId >= 0 && pointerCount == 1) {
6457 // Replace initial down and final up action.
6458 // We can compare the action without masking off the changed pointer index
6459 // because we know the index is 0.
6460 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6461 action = AMOTION_EVENT_ACTION_DOWN;
6462 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6463 action = AMOTION_EVENT_ACTION_UP;
6464 } else {
6465 // Can't happen.
6466 ALOG_ASSERT(false);
6467 }
6468 }
6469
6470 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006471 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006472 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6473 xPrecision, yPrecision, downTime);
6474 getListener()->notifyMotion(&args);
6475}
6476
6477bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6478 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6479 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6480 BitSet32 idBits) const {
6481 bool changed = false;
6482 while (!idBits.isEmpty()) {
6483 uint32_t id = idBits.clearFirstMarkedBit();
6484 uint32_t inIndex = inIdToIndex[id];
6485 uint32_t outIndex = outIdToIndex[id];
6486
6487 const PointerProperties& curInProperties = inProperties[inIndex];
6488 const PointerCoords& curInCoords = inCoords[inIndex];
6489 PointerProperties& curOutProperties = outProperties[outIndex];
6490 PointerCoords& curOutCoords = outCoords[outIndex];
6491
6492 if (curInProperties != curOutProperties) {
6493 curOutProperties.copyFrom(curInProperties);
6494 changed = true;
6495 }
6496
6497 if (curInCoords != curOutCoords) {
6498 curOutCoords.copyFrom(curInCoords);
6499 changed = true;
6500 }
6501 }
6502 return changed;
6503}
6504
6505void TouchInputMapper::fadePointer() {
6506 if (mPointerController != NULL) {
6507 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6508 }
6509}
6510
Jeff Brownc9aa6282015-02-11 19:03:28 -08006511void TouchInputMapper::cancelTouch(nsecs_t when) {
6512 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006513 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006514}
6515
Michael Wrightd02c5b62014-02-10 15:10:22 -08006516bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6517 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6518 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6519}
6520
6521const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6522 int32_t x, int32_t y) {
6523 size_t numVirtualKeys = mVirtualKeys.size();
6524 for (size_t i = 0; i < numVirtualKeys; i++) {
6525 const VirtualKey& virtualKey = mVirtualKeys[i];
6526
6527#if DEBUG_VIRTUAL_KEYS
6528 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6529 "left=%d, top=%d, right=%d, bottom=%d",
6530 x, y,
6531 virtualKey.keyCode, virtualKey.scanCode,
6532 virtualKey.hitLeft, virtualKey.hitTop,
6533 virtualKey.hitRight, virtualKey.hitBottom);
6534#endif
6535
6536 if (virtualKey.isHit(x, y)) {
6537 return & virtualKey;
6538 }
6539 }
6540
6541 return NULL;
6542}
6543
Michael Wright842500e2015-03-13 17:32:02 -07006544void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6545 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6546 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006547
Michael Wright842500e2015-03-13 17:32:02 -07006548 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006549
6550 if (currentPointerCount == 0) {
6551 // No pointers to assign.
6552 return;
6553 }
6554
6555 if (lastPointerCount == 0) {
6556 // All pointers are new.
6557 for (uint32_t i = 0; i < currentPointerCount; i++) {
6558 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006559 current->rawPointerData.pointers[i].id = id;
6560 current->rawPointerData.idToIndex[id] = i;
6561 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006562 }
6563 return;
6564 }
6565
6566 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006567 && current->rawPointerData.pointers[0].toolType
6568 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006569 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006570 uint32_t id = last->rawPointerData.pointers[0].id;
6571 current->rawPointerData.pointers[0].id = id;
6572 current->rawPointerData.idToIndex[id] = 0;
6573 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006574 return;
6575 }
6576
6577 // General case.
6578 // We build a heap of squared euclidean distances between current and last pointers
6579 // associated with the current and last pointer indices. Then, we find the best
6580 // match (by distance) for each current pointer.
6581 // The pointers must have the same tool type but it is possible for them to
6582 // transition from hovering to touching or vice-versa while retaining the same id.
6583 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6584
6585 uint32_t heapSize = 0;
6586 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6587 currentPointerIndex++) {
6588 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6589 lastPointerIndex++) {
6590 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006591 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006592 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006593 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006594 if (currentPointer.toolType == lastPointer.toolType) {
6595 int64_t deltaX = currentPointer.x - lastPointer.x;
6596 int64_t deltaY = currentPointer.y - lastPointer.y;
6597
6598 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6599
6600 // Insert new element into the heap (sift up).
6601 heap[heapSize].currentPointerIndex = currentPointerIndex;
6602 heap[heapSize].lastPointerIndex = lastPointerIndex;
6603 heap[heapSize].distance = distance;
6604 heapSize += 1;
6605 }
6606 }
6607 }
6608
6609 // Heapify
6610 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6611 startIndex -= 1;
6612 for (uint32_t parentIndex = startIndex; ;) {
6613 uint32_t childIndex = parentIndex * 2 + 1;
6614 if (childIndex >= heapSize) {
6615 break;
6616 }
6617
6618 if (childIndex + 1 < heapSize
6619 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6620 childIndex += 1;
6621 }
6622
6623 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6624 break;
6625 }
6626
6627 swap(heap[parentIndex], heap[childIndex]);
6628 parentIndex = childIndex;
6629 }
6630 }
6631
6632#if DEBUG_POINTER_ASSIGNMENT
6633 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6634 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006635 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006636 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6637 heap[i].distance);
6638 }
6639#endif
6640
6641 // Pull matches out by increasing order of distance.
6642 // To avoid reassigning pointers that have already been matched, the loop keeps track
6643 // of which last and current pointers have been matched using the matchedXXXBits variables.
6644 // It also tracks the used pointer id bits.
6645 BitSet32 matchedLastBits(0);
6646 BitSet32 matchedCurrentBits(0);
6647 BitSet32 usedIdBits(0);
6648 bool first = true;
6649 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6650 while (heapSize > 0) {
6651 if (first) {
6652 // The first time through the loop, we just consume the root element of
6653 // the heap (the one with smallest distance).
6654 first = false;
6655 } else {
6656 // Previous iterations consumed the root element of the heap.
6657 // Pop root element off of the heap (sift down).
6658 heap[0] = heap[heapSize];
6659 for (uint32_t parentIndex = 0; ;) {
6660 uint32_t childIndex = parentIndex * 2 + 1;
6661 if (childIndex >= heapSize) {
6662 break;
6663 }
6664
6665 if (childIndex + 1 < heapSize
6666 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6667 childIndex += 1;
6668 }
6669
6670 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6671 break;
6672 }
6673
6674 swap(heap[parentIndex], heap[childIndex]);
6675 parentIndex = childIndex;
6676 }
6677
6678#if DEBUG_POINTER_ASSIGNMENT
6679 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6680 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006681 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006682 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6683 heap[i].distance);
6684 }
6685#endif
6686 }
6687
6688 heapSize -= 1;
6689
6690 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6691 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6692
6693 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6694 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6695
6696 matchedCurrentBits.markBit(currentPointerIndex);
6697 matchedLastBits.markBit(lastPointerIndex);
6698
Michael Wright842500e2015-03-13 17:32:02 -07006699 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6700 current->rawPointerData.pointers[currentPointerIndex].id = id;
6701 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6702 current->rawPointerData.markIdBit(id,
6703 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006704 usedIdBits.markBit(id);
6705
6706#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006707 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6708 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006709 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6710#endif
6711 break;
6712 }
6713 }
6714
6715 // Assign fresh ids to pointers that were not matched in the process.
6716 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6717 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6718 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6719
Michael Wright842500e2015-03-13 17:32:02 -07006720 current->rawPointerData.pointers[currentPointerIndex].id = id;
6721 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6722 current->rawPointerData.markIdBit(id,
6723 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006724
6725#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006726 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006727#endif
6728 }
6729}
6730
6731int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6732 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6733 return AKEY_STATE_VIRTUAL;
6734 }
6735
6736 size_t numVirtualKeys = mVirtualKeys.size();
6737 for (size_t i = 0; i < numVirtualKeys; i++) {
6738 const VirtualKey& virtualKey = mVirtualKeys[i];
6739 if (virtualKey.keyCode == keyCode) {
6740 return AKEY_STATE_UP;
6741 }
6742 }
6743
6744 return AKEY_STATE_UNKNOWN;
6745}
6746
6747int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6748 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6749 return AKEY_STATE_VIRTUAL;
6750 }
6751
6752 size_t numVirtualKeys = mVirtualKeys.size();
6753 for (size_t i = 0; i < numVirtualKeys; i++) {
6754 const VirtualKey& virtualKey = mVirtualKeys[i];
6755 if (virtualKey.scanCode == scanCode) {
6756 return AKEY_STATE_UP;
6757 }
6758 }
6759
6760 return AKEY_STATE_UNKNOWN;
6761}
6762
6763bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6764 const int32_t* keyCodes, uint8_t* outFlags) {
6765 size_t numVirtualKeys = mVirtualKeys.size();
6766 for (size_t i = 0; i < numVirtualKeys; i++) {
6767 const VirtualKey& virtualKey = mVirtualKeys[i];
6768
6769 for (size_t i = 0; i < numCodes; i++) {
6770 if (virtualKey.keyCode == keyCodes[i]) {
6771 outFlags[i] = 1;
6772 }
6773 }
6774 }
6775
6776 return true;
6777}
6778
6779
6780// --- SingleTouchInputMapper ---
6781
6782SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6783 TouchInputMapper(device) {
6784}
6785
6786SingleTouchInputMapper::~SingleTouchInputMapper() {
6787}
6788
6789void SingleTouchInputMapper::reset(nsecs_t when) {
6790 mSingleTouchMotionAccumulator.reset(getDevice());
6791
6792 TouchInputMapper::reset(when);
6793}
6794
6795void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6796 TouchInputMapper::process(rawEvent);
6797
6798 mSingleTouchMotionAccumulator.process(rawEvent);
6799}
6800
Michael Wright842500e2015-03-13 17:32:02 -07006801void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006802 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006803 outState->rawPointerData.pointerCount = 1;
6804 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006805
6806 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6807 && (mTouchButtonAccumulator.isHovering()
6808 || (mRawPointerAxes.pressure.valid
6809 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006810 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006811
Michael Wright842500e2015-03-13 17:32:02 -07006812 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006813 outPointer.id = 0;
6814 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6815 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6816 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6817 outPointer.touchMajor = 0;
6818 outPointer.touchMinor = 0;
6819 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6820 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6821 outPointer.orientation = 0;
6822 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6823 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6824 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6825 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6826 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6827 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6828 }
6829 outPointer.isHovering = isHovering;
6830 }
6831}
6832
6833void SingleTouchInputMapper::configureRawPointerAxes() {
6834 TouchInputMapper::configureRawPointerAxes();
6835
6836 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6837 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6838 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6839 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6840 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6841 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6842 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6843}
6844
6845bool SingleTouchInputMapper::hasStylus() const {
6846 return mTouchButtonAccumulator.hasStylus();
6847}
6848
6849
6850// --- MultiTouchInputMapper ---
6851
6852MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6853 TouchInputMapper(device) {
6854}
6855
6856MultiTouchInputMapper::~MultiTouchInputMapper() {
6857}
6858
6859void MultiTouchInputMapper::reset(nsecs_t when) {
6860 mMultiTouchMotionAccumulator.reset(getDevice());
6861
6862 mPointerIdBits.clear();
6863
6864 TouchInputMapper::reset(when);
6865}
6866
6867void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6868 TouchInputMapper::process(rawEvent);
6869
6870 mMultiTouchMotionAccumulator.process(rawEvent);
6871}
6872
Michael Wright842500e2015-03-13 17:32:02 -07006873void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006874 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6875 size_t outCount = 0;
6876 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006877 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006878
6879 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6880 const MultiTouchMotionAccumulator::Slot* inSlot =
6881 mMultiTouchMotionAccumulator.getSlot(inIndex);
6882 if (!inSlot->isInUse()) {
6883 continue;
6884 }
6885
6886 if (outCount >= MAX_POINTERS) {
6887#if DEBUG_POINTERS
6888 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6889 "ignoring the rest.",
6890 getDeviceName().string(), MAX_POINTERS);
6891#endif
6892 break; // too many fingers!
6893 }
6894
Michael Wright842500e2015-03-13 17:32:02 -07006895 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006896 outPointer.x = inSlot->getX();
6897 outPointer.y = inSlot->getY();
6898 outPointer.pressure = inSlot->getPressure();
6899 outPointer.touchMajor = inSlot->getTouchMajor();
6900 outPointer.touchMinor = inSlot->getTouchMinor();
6901 outPointer.toolMajor = inSlot->getToolMajor();
6902 outPointer.toolMinor = inSlot->getToolMinor();
6903 outPointer.orientation = inSlot->getOrientation();
6904 outPointer.distance = inSlot->getDistance();
6905 outPointer.tiltX = 0;
6906 outPointer.tiltY = 0;
6907
6908 outPointer.toolType = inSlot->getToolType();
6909 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6910 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6911 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6912 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6913 }
6914 }
6915
6916 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6917 && (mTouchButtonAccumulator.isHovering()
6918 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6919 outPointer.isHovering = isHovering;
6920
6921 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006922 if (mHavePointerIds) {
6923 int32_t trackingId = inSlot->getTrackingId();
6924 int32_t id = -1;
6925 if (trackingId >= 0) {
6926 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6927 uint32_t n = idBits.clearFirstMarkedBit();
6928 if (mPointerTrackingIdMap[n] == trackingId) {
6929 id = n;
6930 }
6931 }
6932
6933 if (id < 0 && !mPointerIdBits.isFull()) {
6934 id = mPointerIdBits.markFirstUnmarkedBit();
6935 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006936 }
Michael Wright842500e2015-03-13 17:32:02 -07006937 }
gaoshang1a632de2016-08-24 10:23:50 +08006938 if (id < 0) {
6939 mHavePointerIds = false;
6940 outState->rawPointerData.clearIdBits();
6941 newPointerIdBits.clear();
6942 } else {
6943 outPointer.id = id;
6944 outState->rawPointerData.idToIndex[id] = outCount;
6945 outState->rawPointerData.markIdBit(id, isHovering);
6946 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006947 }
Michael Wright842500e2015-03-13 17:32:02 -07006948 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006949 outCount += 1;
6950 }
6951
Michael Wright842500e2015-03-13 17:32:02 -07006952 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006953 mPointerIdBits = newPointerIdBits;
6954
6955 mMultiTouchMotionAccumulator.finishSync();
6956}
6957
6958void MultiTouchInputMapper::configureRawPointerAxes() {
6959 TouchInputMapper::configureRawPointerAxes();
6960
6961 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6962 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6963 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6964 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6965 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6966 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6967 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6968 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6969 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6970 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6971 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6972
6973 if (mRawPointerAxes.trackingId.valid
6974 && mRawPointerAxes.slot.valid
6975 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6976 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6977 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006978 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6979 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006980 getDeviceName().string(), slotCount, MAX_SLOTS);
6981 slotCount = MAX_SLOTS;
6982 }
6983 mMultiTouchMotionAccumulator.configure(getDevice(),
6984 slotCount, true /*usingSlotsProtocol*/);
6985 } else {
6986 mMultiTouchMotionAccumulator.configure(getDevice(),
6987 MAX_POINTERS, false /*usingSlotsProtocol*/);
6988 }
6989}
6990
6991bool MultiTouchInputMapper::hasStylus() const {
6992 return mMultiTouchMotionAccumulator.hasStylus()
6993 || mTouchButtonAccumulator.hasStylus();
6994}
6995
Michael Wright842500e2015-03-13 17:32:02 -07006996// --- ExternalStylusInputMapper
6997
6998ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6999 InputMapper(device) {
7000
7001}
7002
7003uint32_t ExternalStylusInputMapper::getSources() {
7004 return AINPUT_SOURCE_STYLUS;
7005}
7006
7007void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7008 InputMapper::populateDeviceInfo(info);
7009 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7010 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7011}
7012
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007013void ExternalStylusInputMapper::dump(std::string& dump) {
7014 dump += INDENT2 "External Stylus Input Mapper:\n";
7015 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007016 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007017 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007018 dumpStylusState(dump, mStylusState);
7019}
7020
7021void ExternalStylusInputMapper::configure(nsecs_t when,
7022 const InputReaderConfiguration* config, uint32_t changes) {
7023 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7024 mTouchButtonAccumulator.configure(getDevice());
7025}
7026
7027void ExternalStylusInputMapper::reset(nsecs_t when) {
7028 InputDevice* device = getDevice();
7029 mSingleTouchMotionAccumulator.reset(device);
7030 mTouchButtonAccumulator.reset(device);
7031 InputMapper::reset(when);
7032}
7033
7034void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7035 mSingleTouchMotionAccumulator.process(rawEvent);
7036 mTouchButtonAccumulator.process(rawEvent);
7037
7038 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7039 sync(rawEvent->when);
7040 }
7041}
7042
7043void ExternalStylusInputMapper::sync(nsecs_t when) {
7044 mStylusState.clear();
7045
7046 mStylusState.when = when;
7047
Michael Wright45ccacf2015-04-21 19:01:58 +01007048 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7049 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7050 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7051 }
7052
Michael Wright842500e2015-03-13 17:32:02 -07007053 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7054 if (mRawPressureAxis.valid) {
7055 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7056 } else if (mTouchButtonAccumulator.isToolActive()) {
7057 mStylusState.pressure = 1.0f;
7058 } else {
7059 mStylusState.pressure = 0.0f;
7060 }
7061
7062 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007063
7064 mContext->dispatchExternalStylusState(mStylusState);
7065}
7066
Michael Wrightd02c5b62014-02-10 15:10:22 -08007067
7068// --- JoystickInputMapper ---
7069
7070JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7071 InputMapper(device) {
7072}
7073
7074JoystickInputMapper::~JoystickInputMapper() {
7075}
7076
7077uint32_t JoystickInputMapper::getSources() {
7078 return AINPUT_SOURCE_JOYSTICK;
7079}
7080
7081void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7082 InputMapper::populateDeviceInfo(info);
7083
7084 for (size_t i = 0; i < mAxes.size(); i++) {
7085 const Axis& axis = mAxes.valueAt(i);
7086 addMotionRange(axis.axisInfo.axis, axis, info);
7087
7088 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7089 addMotionRange(axis.axisInfo.highAxis, axis, info);
7090
7091 }
7092 }
7093}
7094
7095void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7096 InputDeviceInfo* info) {
7097 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7098 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7099 /* In order to ease the transition for developers from using the old axes
7100 * to the newer, more semantically correct axes, we'll continue to register
7101 * the old axes as duplicates of their corresponding new ones. */
7102 int32_t compatAxis = getCompatAxis(axisId);
7103 if (compatAxis >= 0) {
7104 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7105 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7106 }
7107}
7108
7109/* A mapping from axes the joystick actually has to the axes that should be
7110 * artificially created for compatibility purposes.
7111 * Returns -1 if no compatibility axis is needed. */
7112int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7113 switch(axis) {
7114 case AMOTION_EVENT_AXIS_LTRIGGER:
7115 return AMOTION_EVENT_AXIS_BRAKE;
7116 case AMOTION_EVENT_AXIS_RTRIGGER:
7117 return AMOTION_EVENT_AXIS_GAS;
7118 }
7119 return -1;
7120}
7121
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007122void JoystickInputMapper::dump(std::string& dump) {
7123 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007124
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007125 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007126 size_t numAxes = mAxes.size();
7127 for (size_t i = 0; i < numAxes; i++) {
7128 const Axis& axis = mAxes.valueAt(i);
7129 const char* label = getAxisLabel(axis.axisInfo.axis);
7130 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007131 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007132 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007133 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007134 }
7135 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7136 label = getAxisLabel(axis.axisInfo.highAxis);
7137 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007138 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007139 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007140 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007141 axis.axisInfo.splitValue);
7142 }
7143 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007144 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007145 }
7146
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007147 dump += StringPrintf(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007148 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007149 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007150 "highScale=%0.5f, highOffset=%0.5f\n",
7151 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007152 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007153 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7154 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7155 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7156 }
7157}
7158
7159void JoystickInputMapper::configure(nsecs_t when,
7160 const InputReaderConfiguration* config, uint32_t changes) {
7161 InputMapper::configure(when, config, changes);
7162
7163 if (!changes) { // first time only
7164 // Collect all axes.
7165 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7166 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7167 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7168 continue; // axis must be claimed by a different device
7169 }
7170
7171 RawAbsoluteAxisInfo rawAxisInfo;
7172 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7173 if (rawAxisInfo.valid) {
7174 // Map axis.
7175 AxisInfo axisInfo;
7176 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7177 if (!explicitlyMapped) {
7178 // Axis is not explicitly mapped, will choose a generic axis later.
7179 axisInfo.mode = AxisInfo::MODE_NORMAL;
7180 axisInfo.axis = -1;
7181 }
7182
7183 // Apply flat override.
7184 int32_t rawFlat = axisInfo.flatOverride < 0
7185 ? rawAxisInfo.flat : axisInfo.flatOverride;
7186
7187 // Calculate scaling factors and limits.
7188 Axis axis;
7189 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7190 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7191 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7192 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7193 scale, 0.0f, highScale, 0.0f,
7194 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7195 rawAxisInfo.resolution * scale);
7196 } else if (isCenteredAxis(axisInfo.axis)) {
7197 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7198 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7199 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7200 scale, offset, scale, offset,
7201 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7202 rawAxisInfo.resolution * scale);
7203 } else {
7204 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7205 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7206 scale, 0.0f, scale, 0.0f,
7207 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7208 rawAxisInfo.resolution * scale);
7209 }
7210
7211 // To eliminate noise while the joystick is at rest, filter out small variations
7212 // in axis values up front.
7213 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7214
7215 mAxes.add(abs, axis);
7216 }
7217 }
7218
7219 // If there are too many axes, start dropping them.
7220 // Prefer to keep explicitly mapped axes.
7221 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007222 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007223 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7224 pruneAxes(true);
7225 pruneAxes(false);
7226 }
7227
7228 // Assign generic axis ids to remaining axes.
7229 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7230 size_t numAxes = mAxes.size();
7231 for (size_t i = 0; i < numAxes; i++) {
7232 Axis& axis = mAxes.editValueAt(i);
7233 if (axis.axisInfo.axis < 0) {
7234 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7235 && haveAxis(nextGenericAxisId)) {
7236 nextGenericAxisId += 1;
7237 }
7238
7239 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7240 axis.axisInfo.axis = nextGenericAxisId;
7241 nextGenericAxisId += 1;
7242 } else {
7243 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7244 "have already been assigned to other axes.",
7245 getDeviceName().string(), mAxes.keyAt(i));
7246 mAxes.removeItemsAt(i--);
7247 numAxes -= 1;
7248 }
7249 }
7250 }
7251 }
7252}
7253
7254bool JoystickInputMapper::haveAxis(int32_t axisId) {
7255 size_t numAxes = mAxes.size();
7256 for (size_t i = 0; i < numAxes; i++) {
7257 const Axis& axis = mAxes.valueAt(i);
7258 if (axis.axisInfo.axis == axisId
7259 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7260 && axis.axisInfo.highAxis == axisId)) {
7261 return true;
7262 }
7263 }
7264 return false;
7265}
7266
7267void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7268 size_t i = mAxes.size();
7269 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7270 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7271 continue;
7272 }
7273 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7274 getDeviceName().string(), mAxes.keyAt(i));
7275 mAxes.removeItemsAt(i);
7276 }
7277}
7278
7279bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7280 switch (axis) {
7281 case AMOTION_EVENT_AXIS_X:
7282 case AMOTION_EVENT_AXIS_Y:
7283 case AMOTION_EVENT_AXIS_Z:
7284 case AMOTION_EVENT_AXIS_RX:
7285 case AMOTION_EVENT_AXIS_RY:
7286 case AMOTION_EVENT_AXIS_RZ:
7287 case AMOTION_EVENT_AXIS_HAT_X:
7288 case AMOTION_EVENT_AXIS_HAT_Y:
7289 case AMOTION_EVENT_AXIS_ORIENTATION:
7290 case AMOTION_EVENT_AXIS_RUDDER:
7291 case AMOTION_EVENT_AXIS_WHEEL:
7292 return true;
7293 default:
7294 return false;
7295 }
7296}
7297
7298void JoystickInputMapper::reset(nsecs_t when) {
7299 // Recenter all axes.
7300 size_t numAxes = mAxes.size();
7301 for (size_t i = 0; i < numAxes; i++) {
7302 Axis& axis = mAxes.editValueAt(i);
7303 axis.resetValue();
7304 }
7305
7306 InputMapper::reset(when);
7307}
7308
7309void JoystickInputMapper::process(const RawEvent* rawEvent) {
7310 switch (rawEvent->type) {
7311 case EV_ABS: {
7312 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7313 if (index >= 0) {
7314 Axis& axis = mAxes.editValueAt(index);
7315 float newValue, highNewValue;
7316 switch (axis.axisInfo.mode) {
7317 case AxisInfo::MODE_INVERT:
7318 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7319 * axis.scale + axis.offset;
7320 highNewValue = 0.0f;
7321 break;
7322 case AxisInfo::MODE_SPLIT:
7323 if (rawEvent->value < axis.axisInfo.splitValue) {
7324 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7325 * axis.scale + axis.offset;
7326 highNewValue = 0.0f;
7327 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7328 newValue = 0.0f;
7329 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7330 * axis.highScale + axis.highOffset;
7331 } else {
7332 newValue = 0.0f;
7333 highNewValue = 0.0f;
7334 }
7335 break;
7336 default:
7337 newValue = rawEvent->value * axis.scale + axis.offset;
7338 highNewValue = 0.0f;
7339 break;
7340 }
7341 axis.newValue = newValue;
7342 axis.highNewValue = highNewValue;
7343 }
7344 break;
7345 }
7346
7347 case EV_SYN:
7348 switch (rawEvent->code) {
7349 case SYN_REPORT:
7350 sync(rawEvent->when, false /*force*/);
7351 break;
7352 }
7353 break;
7354 }
7355}
7356
7357void JoystickInputMapper::sync(nsecs_t when, bool force) {
7358 if (!filterAxes(force)) {
7359 return;
7360 }
7361
7362 int32_t metaState = mContext->getGlobalMetaState();
7363 int32_t buttonState = 0;
7364
7365 PointerProperties pointerProperties;
7366 pointerProperties.clear();
7367 pointerProperties.id = 0;
7368 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7369
7370 PointerCoords pointerCoords;
7371 pointerCoords.clear();
7372
7373 size_t numAxes = mAxes.size();
7374 for (size_t i = 0; i < numAxes; i++) {
7375 const Axis& axis = mAxes.valueAt(i);
7376 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7377 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7378 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7379 axis.highCurrentValue);
7380 }
7381 }
7382
7383 // Moving a joystick axis should not wake the device because joysticks can
7384 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7385 // button will likely wake the device.
7386 // TODO: Use the input device configuration to control this behavior more finely.
7387 uint32_t policyFlags = 0;
7388
7389 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007390 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007391 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7392 getListener()->notifyMotion(&args);
7393}
7394
7395void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7396 int32_t axis, float value) {
7397 pointerCoords->setAxisValue(axis, value);
7398 /* In order to ease the transition for developers from using the old axes
7399 * to the newer, more semantically correct axes, we'll continue to produce
7400 * values for the old axes as mirrors of the value of their corresponding
7401 * new axes. */
7402 int32_t compatAxis = getCompatAxis(axis);
7403 if (compatAxis >= 0) {
7404 pointerCoords->setAxisValue(compatAxis, value);
7405 }
7406}
7407
7408bool JoystickInputMapper::filterAxes(bool force) {
7409 bool atLeastOneSignificantChange = force;
7410 size_t numAxes = mAxes.size();
7411 for (size_t i = 0; i < numAxes; i++) {
7412 Axis& axis = mAxes.editValueAt(i);
7413 if (force || hasValueChangedSignificantly(axis.filter,
7414 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7415 axis.currentValue = axis.newValue;
7416 atLeastOneSignificantChange = true;
7417 }
7418 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7419 if (force || hasValueChangedSignificantly(axis.filter,
7420 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7421 axis.highCurrentValue = axis.highNewValue;
7422 atLeastOneSignificantChange = true;
7423 }
7424 }
7425 }
7426 return atLeastOneSignificantChange;
7427}
7428
7429bool JoystickInputMapper::hasValueChangedSignificantly(
7430 float filter, float newValue, float currentValue, float min, float max) {
7431 if (newValue != currentValue) {
7432 // Filter out small changes in value unless the value is converging on the axis
7433 // bounds or center point. This is intended to reduce the amount of information
7434 // sent to applications by particularly noisy joysticks (such as PS3).
7435 if (fabs(newValue - currentValue) > filter
7436 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7437 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7438 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7439 return true;
7440 }
7441 }
7442 return false;
7443}
7444
7445bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7446 float filter, float newValue, float currentValue, float thresholdValue) {
7447 float newDistance = fabs(newValue - thresholdValue);
7448 if (newDistance < filter) {
7449 float oldDistance = fabs(currentValue - thresholdValue);
7450 if (newDistance < oldDistance) {
7451 return true;
7452 }
7453 }
7454 return false;
7455}
7456
7457} // namespace android