blob: 50229cbaab81a7a08b2535c4edcf3d20ca350381 [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),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001790 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791}
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 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001831 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832}
1833
1834void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1835 if (mSlots) {
1836 for (size_t i = 0; i < mSlotCount; i++) {
1837 mSlots[i].clear();
1838 }
1839 }
1840 mCurrentSlot = initialSlot;
1841}
1842
1843void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1844 if (rawEvent->type == EV_ABS) {
1845 bool newSlot = false;
1846 if (mUsingSlotsProtocol) {
1847 if (rawEvent->code == ABS_MT_SLOT) {
1848 mCurrentSlot = rawEvent->value;
1849 newSlot = true;
1850 }
1851 } else if (mCurrentSlot < 0) {
1852 mCurrentSlot = 0;
1853 }
1854
1855 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1856#if DEBUG_POINTERS
1857 if (newSlot) {
1858 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001859 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 mCurrentSlot, mSlotCount - 1);
1861 }
1862#endif
1863 } else {
1864 Slot* slot = &mSlots[mCurrentSlot];
1865
1866 switch (rawEvent->code) {
1867 case ABS_MT_POSITION_X:
1868 slot->mInUse = true;
1869 slot->mAbsMTPositionX = rawEvent->value;
1870 break;
1871 case ABS_MT_POSITION_Y:
1872 slot->mInUse = true;
1873 slot->mAbsMTPositionY = rawEvent->value;
1874 break;
1875 case ABS_MT_TOUCH_MAJOR:
1876 slot->mInUse = true;
1877 slot->mAbsMTTouchMajor = rawEvent->value;
1878 break;
1879 case ABS_MT_TOUCH_MINOR:
1880 slot->mInUse = true;
1881 slot->mAbsMTTouchMinor = rawEvent->value;
1882 slot->mHaveAbsMTTouchMinor = true;
1883 break;
1884 case ABS_MT_WIDTH_MAJOR:
1885 slot->mInUse = true;
1886 slot->mAbsMTWidthMajor = rawEvent->value;
1887 break;
1888 case ABS_MT_WIDTH_MINOR:
1889 slot->mInUse = true;
1890 slot->mAbsMTWidthMinor = rawEvent->value;
1891 slot->mHaveAbsMTWidthMinor = true;
1892 break;
1893 case ABS_MT_ORIENTATION:
1894 slot->mInUse = true;
1895 slot->mAbsMTOrientation = rawEvent->value;
1896 break;
1897 case ABS_MT_TRACKING_ID:
1898 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1899 // The slot is no longer in use but it retains its previous contents,
1900 // which may be reused for subsequent touches.
1901 slot->mInUse = false;
1902 } else {
1903 slot->mInUse = true;
1904 slot->mAbsMTTrackingId = rawEvent->value;
1905 }
1906 break;
1907 case ABS_MT_PRESSURE:
1908 slot->mInUse = true;
1909 slot->mAbsMTPressure = rawEvent->value;
1910 break;
1911 case ABS_MT_DISTANCE:
1912 slot->mInUse = true;
1913 slot->mAbsMTDistance = rawEvent->value;
1914 break;
1915 case ABS_MT_TOOL_TYPE:
1916 slot->mInUse = true;
1917 slot->mAbsMTToolType = rawEvent->value;
1918 slot->mHaveAbsMTToolType = true;
1919 break;
1920 }
1921 }
1922 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1923 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1924 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001925 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1926 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 }
1928}
1929
1930void MultiTouchMotionAccumulator::finishSync() {
1931 if (!mUsingSlotsProtocol) {
1932 clearSlots(-1);
1933 }
1934}
1935
1936bool MultiTouchMotionAccumulator::hasStylus() const {
1937 return mHaveStylus;
1938}
1939
1940
1941// --- MultiTouchMotionAccumulator::Slot ---
1942
1943MultiTouchMotionAccumulator::Slot::Slot() {
1944 clear();
1945}
1946
1947void MultiTouchMotionAccumulator::Slot::clear() {
1948 mInUse = false;
1949 mHaveAbsMTTouchMinor = false;
1950 mHaveAbsMTWidthMinor = false;
1951 mHaveAbsMTToolType = false;
1952 mAbsMTPositionX = 0;
1953 mAbsMTPositionY = 0;
1954 mAbsMTTouchMajor = 0;
1955 mAbsMTTouchMinor = 0;
1956 mAbsMTWidthMajor = 0;
1957 mAbsMTWidthMinor = 0;
1958 mAbsMTOrientation = 0;
1959 mAbsMTTrackingId = -1;
1960 mAbsMTPressure = 0;
1961 mAbsMTDistance = 0;
1962 mAbsMTToolType = 0;
1963}
1964
1965int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1966 if (mHaveAbsMTToolType) {
1967 switch (mAbsMTToolType) {
1968 case MT_TOOL_FINGER:
1969 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1970 case MT_TOOL_PEN:
1971 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1972 }
1973 }
1974 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1975}
1976
1977
1978// --- InputMapper ---
1979
1980InputMapper::InputMapper(InputDevice* device) :
1981 mDevice(device), mContext(device->getContext()) {
1982}
1983
1984InputMapper::~InputMapper() {
1985}
1986
1987void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1988 info->addSource(getSources());
1989}
1990
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001991void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992}
1993
1994void InputMapper::configure(nsecs_t when,
1995 const InputReaderConfiguration* config, uint32_t changes) {
1996}
1997
1998void InputMapper::reset(nsecs_t when) {
1999}
2000
2001void InputMapper::timeoutExpired(nsecs_t when) {
2002}
2003
2004int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2005 return AKEY_STATE_UNKNOWN;
2006}
2007
2008int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2009 return AKEY_STATE_UNKNOWN;
2010}
2011
2012int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2013 return AKEY_STATE_UNKNOWN;
2014}
2015
2016bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2017 const int32_t* keyCodes, uint8_t* outFlags) {
2018 return false;
2019}
2020
2021void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2022 int32_t token) {
2023}
2024
2025void InputMapper::cancelVibrate(int32_t token) {
2026}
2027
Jeff Brownc9aa6282015-02-11 19:03:28 -08002028void InputMapper::cancelTouch(nsecs_t when) {
2029}
2030
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031int32_t InputMapper::getMetaState() {
2032 return 0;
2033}
2034
Andrii Kulian763a3a42016-03-08 10:46:16 -08002035void InputMapper::updateMetaState(int32_t keyCode) {
2036}
2037
Michael Wright842500e2015-03-13 17:32:02 -07002038void InputMapper::updateExternalStylusState(const StylusState& state) {
2039
2040}
2041
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042void InputMapper::fadePointer() {
2043}
2044
2045status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2046 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2047}
2048
2049void InputMapper::bumpGeneration() {
2050 mDevice->bumpGeneration();
2051}
2052
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002053void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 const RawAbsoluteAxisInfo& axis, const char* name) {
2055 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002056 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2058 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002059 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 }
2061}
2062
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002063void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2064 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2065 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2066 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2067 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002068}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069
2070// --- SwitchInputMapper ---
2071
2072SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002073 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074}
2075
2076SwitchInputMapper::~SwitchInputMapper() {
2077}
2078
2079uint32_t SwitchInputMapper::getSources() {
2080 return AINPUT_SOURCE_SWITCH;
2081}
2082
2083void SwitchInputMapper::process(const RawEvent* rawEvent) {
2084 switch (rawEvent->type) {
2085 case EV_SW:
2086 processSwitch(rawEvent->code, rawEvent->value);
2087 break;
2088
2089 case EV_SYN:
2090 if (rawEvent->code == SYN_REPORT) {
2091 sync(rawEvent->when);
2092 }
2093 }
2094}
2095
2096void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2097 if (switchCode >= 0 && switchCode < 32) {
2098 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002099 mSwitchValues |= 1 << switchCode;
2100 } else {
2101 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 }
2103 mUpdatedSwitchMask |= 1 << switchCode;
2104 }
2105}
2106
2107void SwitchInputMapper::sync(nsecs_t when) {
2108 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002109 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002110 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 getListener()->notifySwitch(&args);
2112
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 mUpdatedSwitchMask = 0;
2114 }
2115}
2116
2117int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2118 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2119}
2120
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002121void SwitchInputMapper::dump(std::string& dump) {
2122 dump += INDENT2 "Switch Input Mapper:\n";
2123 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002124}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125
2126// --- VibratorInputMapper ---
2127
2128VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2129 InputMapper(device), mVibrating(false) {
2130}
2131
2132VibratorInputMapper::~VibratorInputMapper() {
2133}
2134
2135uint32_t VibratorInputMapper::getSources() {
2136 return 0;
2137}
2138
2139void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2140 InputMapper::populateDeviceInfo(info);
2141
2142 info->setVibrator(true);
2143}
2144
2145void VibratorInputMapper::process(const RawEvent* rawEvent) {
2146 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2147}
2148
2149void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2150 int32_t token) {
2151#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002152 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 for (size_t i = 0; i < patternSize; i++) {
2154 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002155 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002157 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002159 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002160 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161#endif
2162
2163 mVibrating = true;
2164 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2165 mPatternSize = patternSize;
2166 mRepeat = repeat;
2167 mToken = token;
2168 mIndex = -1;
2169
2170 nextStep();
2171}
2172
2173void VibratorInputMapper::cancelVibrate(int32_t token) {
2174#if DEBUG_VIBRATOR
2175 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2176#endif
2177
2178 if (mVibrating && mToken == token) {
2179 stopVibrating();
2180 }
2181}
2182
2183void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2184 if (mVibrating) {
2185 if (when >= mNextStepTime) {
2186 nextStep();
2187 } else {
2188 getContext()->requestTimeoutAtTime(mNextStepTime);
2189 }
2190 }
2191}
2192
2193void VibratorInputMapper::nextStep() {
2194 mIndex += 1;
2195 if (size_t(mIndex) >= mPatternSize) {
2196 if (mRepeat < 0) {
2197 // We are done.
2198 stopVibrating();
2199 return;
2200 }
2201 mIndex = mRepeat;
2202 }
2203
2204 bool vibratorOn = mIndex & 1;
2205 nsecs_t duration = mPattern[mIndex];
2206 if (vibratorOn) {
2207#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002208 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209#endif
2210 getEventHub()->vibrate(getDeviceId(), duration);
2211 } else {
2212#if DEBUG_VIBRATOR
2213 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2214#endif
2215 getEventHub()->cancelVibrate(getDeviceId());
2216 }
2217 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2218 mNextStepTime = now + duration;
2219 getContext()->requestTimeoutAtTime(mNextStepTime);
2220#if DEBUG_VIBRATOR
2221 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2222#endif
2223}
2224
2225void VibratorInputMapper::stopVibrating() {
2226 mVibrating = false;
2227#if DEBUG_VIBRATOR
2228 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2229#endif
2230 getEventHub()->cancelVibrate(getDeviceId());
2231}
2232
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002233void VibratorInputMapper::dump(std::string& dump) {
2234 dump += INDENT2 "Vibrator Input Mapper:\n";
2235 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236}
2237
2238
2239// --- KeyboardInputMapper ---
2240
2241KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2242 uint32_t source, int32_t keyboardType) :
2243 InputMapper(device), mSource(source),
2244 mKeyboardType(keyboardType) {
2245}
2246
2247KeyboardInputMapper::~KeyboardInputMapper() {
2248}
2249
2250uint32_t KeyboardInputMapper::getSources() {
2251 return mSource;
2252}
2253
2254void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2255 InputMapper::populateDeviceInfo(info);
2256
2257 info->setKeyboardType(mKeyboardType);
2258 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2259}
2260
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002261void KeyboardInputMapper::dump(std::string& dump) {
2262 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002264 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2265 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2266 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2267 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2268 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269}
2270
2271
2272void KeyboardInputMapper::configure(nsecs_t when,
2273 const InputReaderConfiguration* config, uint32_t changes) {
2274 InputMapper::configure(when, config, changes);
2275
2276 if (!changes) { // first time only
2277 // Configure basic parameters.
2278 configureParameters();
2279 }
2280
2281 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002282 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2284 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002285 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 mOrientation = v.orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288 }
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)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002699 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2701 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002702 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002703 mOrientation = v.orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705 }
2706 bumpGeneration();
2707 }
2708}
2709
2710void CursorInputMapper::configureParameters() {
2711 mParameters.mode = Parameters::MODE_POINTER;
2712 String8 cursorModeString;
2713 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2714 if (cursorModeString == "navigation") {
2715 mParameters.mode = Parameters::MODE_NAVIGATION;
2716 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2717 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2718 }
2719 }
2720
2721 mParameters.orientationAware = false;
2722 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2723 mParameters.orientationAware);
2724
2725 mParameters.hasAssociatedDisplay = false;
2726 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2727 mParameters.hasAssociatedDisplay = true;
2728 }
2729}
2730
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002731void CursorInputMapper::dumpParameters(std::string& dump) {
2732 dump += INDENT3 "Parameters:\n";
2733 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734 toString(mParameters.hasAssociatedDisplay));
2735
2736 switch (mParameters.mode) {
2737 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002738 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002740 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002741 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002742 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002743 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002744 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 break;
2746 default:
2747 ALOG_ASSERT(false);
2748 }
2749
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002750 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002751 toString(mParameters.orientationAware));
2752}
2753
2754void CursorInputMapper::reset(nsecs_t when) {
2755 mButtonState = 0;
2756 mDownTime = 0;
2757
2758 mPointerVelocityControl.reset();
2759 mWheelXVelocityControl.reset();
2760 mWheelYVelocityControl.reset();
2761
2762 mCursorButtonAccumulator.reset(getDevice());
2763 mCursorMotionAccumulator.reset(getDevice());
2764 mCursorScrollAccumulator.reset(getDevice());
2765
2766 InputMapper::reset(when);
2767}
2768
2769void CursorInputMapper::process(const RawEvent* rawEvent) {
2770 mCursorButtonAccumulator.process(rawEvent);
2771 mCursorMotionAccumulator.process(rawEvent);
2772 mCursorScrollAccumulator.process(rawEvent);
2773
2774 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2775 sync(rawEvent->when);
2776 }
2777}
2778
2779void CursorInputMapper::sync(nsecs_t when) {
2780 int32_t lastButtonState = mButtonState;
2781 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2782 mButtonState = currentButtonState;
2783
2784 bool wasDown = isPointerDown(lastButtonState);
2785 bool down = isPointerDown(currentButtonState);
2786 bool downChanged;
2787 if (!wasDown && down) {
2788 mDownTime = when;
2789 downChanged = true;
2790 } else if (wasDown && !down) {
2791 downChanged = true;
2792 } else {
2793 downChanged = false;
2794 }
2795 nsecs_t downTime = mDownTime;
2796 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002797 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2798 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002799
2800 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2801 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2802 bool moved = deltaX != 0 || deltaY != 0;
2803
2804 // Rotate delta according to orientation if needed.
2805 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2806 && (deltaX != 0.0f || deltaY != 0.0f)) {
2807 rotateDelta(mOrientation, &deltaX, &deltaY);
2808 }
2809
2810 // Move the pointer.
2811 PointerProperties pointerProperties;
2812 pointerProperties.clear();
2813 pointerProperties.id = 0;
2814 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2815
2816 PointerCoords pointerCoords;
2817 pointerCoords.clear();
2818
2819 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2820 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2821 bool scrolled = vscroll != 0 || hscroll != 0;
2822
2823 mWheelYVelocityControl.move(when, NULL, &vscroll);
2824 mWheelXVelocityControl.move(when, &hscroll, NULL);
2825
2826 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2827
2828 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002829 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830 if (moved || scrolled || buttonsChanged) {
2831 mPointerController->setPresentation(
2832 PointerControllerInterface::PRESENTATION_POINTER);
2833
2834 if (moved) {
2835 mPointerController->move(deltaX, deltaY);
2836 }
2837
2838 if (buttonsChanged) {
2839 mPointerController->setButtonState(currentButtonState);
2840 }
2841
2842 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2843 }
2844
2845 float x, y;
2846 mPointerController->getPosition(&x, &y);
2847 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2848 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002849 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2850 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 displayId = ADISPLAY_ID_DEFAULT;
2852 } else {
2853 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2854 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2855 displayId = ADISPLAY_ID_NONE;
2856 }
2857
2858 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2859
2860 // Moving an external trackball or mouse should wake the device.
2861 // We don't do this for internal cursor devices to prevent them from waking up
2862 // the device in your pocket.
2863 // TODO: Use the input device configuration to control this behavior more finely.
2864 uint32_t policyFlags = 0;
2865 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002866 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 }
2868
2869 // Synthesize key down from buttons if needed.
2870 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2871 policyFlags, lastButtonState, currentButtonState);
2872
2873 // Send motion event.
2874 if (downChanged || moved || scrolled || buttonsChanged) {
2875 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002876 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877 int32_t motionEventAction;
2878 if (downChanged) {
2879 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002880 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2882 } else {
2883 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2884 }
2885
Michael Wright7b159c92015-05-14 14:48:03 +01002886 if (buttonsReleased) {
2887 BitSet32 released(buttonsReleased);
2888 while (!released.isEmpty()) {
2889 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2890 buttonState &= ~actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002891 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002892 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2893 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002894 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002895 mXPrecision, mYPrecision, downTime);
2896 getListener()->notifyMotion(&releaseArgs);
2897 }
2898 }
2899
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002900 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002901 motionEventAction, 0, 0, metaState, currentButtonState,
2902 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002903 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904 mXPrecision, mYPrecision, downTime);
2905 getListener()->notifyMotion(&args);
2906
Michael Wright7b159c92015-05-14 14:48:03 +01002907 if (buttonsPressed) {
2908 BitSet32 pressed(buttonsPressed);
2909 while (!pressed.isEmpty()) {
2910 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2911 buttonState |= actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002912 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002913 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2914 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002915 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002916 mXPrecision, mYPrecision, downTime);
2917 getListener()->notifyMotion(&pressArgs);
2918 }
2919 }
2920
2921 ALOG_ASSERT(buttonState == currentButtonState);
2922
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 // Send hover move after UP to tell the application that the mouse is hovering now.
2924 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002925 && (mSource == AINPUT_SOURCE_MOUSE)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002926 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002927 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002928 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002929 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930 mXPrecision, mYPrecision, downTime);
2931 getListener()->notifyMotion(&hoverArgs);
2932 }
2933
2934 // Send scroll events.
2935 if (scrolled) {
2936 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2937 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2938
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002939 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002940 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002941 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002942 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002943 mXPrecision, mYPrecision, downTime);
2944 getListener()->notifyMotion(&scrollArgs);
2945 }
2946 }
2947
2948 // Synthesize key up from buttons if needed.
2949 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2950 policyFlags, lastButtonState, currentButtonState);
2951
2952 mCursorMotionAccumulator.finishSync();
2953 mCursorScrollAccumulator.finishSync();
2954}
2955
2956int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2957 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2958 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2959 } else {
2960 return AKEY_STATE_UNKNOWN;
2961 }
2962}
2963
2964void CursorInputMapper::fadePointer() {
2965 if (mPointerController != NULL) {
2966 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2967 }
2968}
2969
Prashant Malani1941ff52015-08-11 18:29:28 -07002970// --- RotaryEncoderInputMapper ---
2971
2972RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002973 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002974 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2975}
2976
2977RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2978}
2979
2980uint32_t RotaryEncoderInputMapper::getSources() {
2981 return mSource;
2982}
2983
2984void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2985 InputMapper::populateDeviceInfo(info);
2986
2987 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002988 float res = 0.0f;
2989 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2990 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2991 }
2992 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2993 mScalingFactor)) {
2994 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2995 "default to 1.0!\n");
2996 mScalingFactor = 1.0f;
2997 }
2998 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2999 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003000 }
3001}
3002
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003003void RotaryEncoderInputMapper::dump(std::string& dump) {
3004 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
3005 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07003006 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
3007}
3008
3009void RotaryEncoderInputMapper::configure(nsecs_t when,
3010 const InputReaderConfiguration* config, uint32_t changes) {
3011 InputMapper::configure(when, config, changes);
3012 if (!changes) {
3013 mRotaryEncoderScrollAccumulator.configure(getDevice());
3014 }
Ivan Podogovad437252016-09-29 16:29:55 +01003015 if (!changes || (InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
3016 DisplayViewport v;
3017 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
3018 mOrientation = v.orientation;
3019 } else {
3020 mOrientation = DISPLAY_ORIENTATION_0;
3021 }
3022 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003023}
3024
3025void RotaryEncoderInputMapper::reset(nsecs_t when) {
3026 mRotaryEncoderScrollAccumulator.reset(getDevice());
3027
3028 InputMapper::reset(when);
3029}
3030
3031void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3032 mRotaryEncoderScrollAccumulator.process(rawEvent);
3033
3034 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3035 sync(rawEvent->when);
3036 }
3037}
3038
3039void RotaryEncoderInputMapper::sync(nsecs_t when) {
3040 PointerCoords pointerCoords;
3041 pointerCoords.clear();
3042
3043 PointerProperties pointerProperties;
3044 pointerProperties.clear();
3045 pointerProperties.id = 0;
3046 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3047
3048 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3049 bool scrolled = scroll != 0;
3050
3051 // This is not a pointer, so it's not associated with a display.
3052 int32_t displayId = ADISPLAY_ID_NONE;
3053
3054 // Moving the rotary encoder should wake the device (if specified).
3055 uint32_t policyFlags = 0;
3056 if (scrolled && getDevice()->isExternal()) {
3057 policyFlags |= POLICY_FLAG_WAKE;
3058 }
3059
Ivan Podogovad437252016-09-29 16:29:55 +01003060 if (mOrientation == DISPLAY_ORIENTATION_180) {
3061 scroll = -scroll;
3062 }
3063
Prashant Malani1941ff52015-08-11 18:29:28 -07003064 // Send motion event.
3065 if (scrolled) {
3066 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003067 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003068
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003069 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Prashant Malani1941ff52015-08-11 18:29:28 -07003070 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3071 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003072 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Prashant Malani1941ff52015-08-11 18:29:28 -07003073 0, 0, 0);
3074 getListener()->notifyMotion(&scrollArgs);
3075 }
3076
3077 mRotaryEncoderScrollAccumulator.finishSync();
3078}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003079
3080// --- TouchInputMapper ---
3081
3082TouchInputMapper::TouchInputMapper(InputDevice* device) :
3083 InputMapper(device),
3084 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3085 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
3086 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3087}
3088
3089TouchInputMapper::~TouchInputMapper() {
3090}
3091
3092uint32_t TouchInputMapper::getSources() {
3093 return mSource;
3094}
3095
3096void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3097 InputMapper::populateDeviceInfo(info);
3098
3099 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3100 info->addMotionRange(mOrientedRanges.x);
3101 info->addMotionRange(mOrientedRanges.y);
3102 info->addMotionRange(mOrientedRanges.pressure);
3103
3104 if (mOrientedRanges.haveSize) {
3105 info->addMotionRange(mOrientedRanges.size);
3106 }
3107
3108 if (mOrientedRanges.haveTouchSize) {
3109 info->addMotionRange(mOrientedRanges.touchMajor);
3110 info->addMotionRange(mOrientedRanges.touchMinor);
3111 }
3112
3113 if (mOrientedRanges.haveToolSize) {
3114 info->addMotionRange(mOrientedRanges.toolMajor);
3115 info->addMotionRange(mOrientedRanges.toolMinor);
3116 }
3117
3118 if (mOrientedRanges.haveOrientation) {
3119 info->addMotionRange(mOrientedRanges.orientation);
3120 }
3121
3122 if (mOrientedRanges.haveDistance) {
3123 info->addMotionRange(mOrientedRanges.distance);
3124 }
3125
3126 if (mOrientedRanges.haveTilt) {
3127 info->addMotionRange(mOrientedRanges.tilt);
3128 }
3129
3130 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3131 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3132 0.0f);
3133 }
3134 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3135 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3136 0.0f);
3137 }
3138 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3139 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3140 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3141 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3142 x.fuzz, x.resolution);
3143 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3144 y.fuzz, y.resolution);
3145 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3146 x.fuzz, x.resolution);
3147 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3148 y.fuzz, y.resolution);
3149 }
3150 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3151 }
3152}
3153
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003154void TouchInputMapper::dump(std::string& dump) {
3155 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156 dumpParameters(dump);
3157 dumpVirtualKeys(dump);
3158 dumpRawPointerAxes(dump);
3159 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003160 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003161 dumpSurface(dump);
3162
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003163 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3164 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3165 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3166 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3167 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3168 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3169 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3170 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3171 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3172 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3173 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3174 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3175 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3176 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3177 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3178 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3179 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003181 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3182 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003183 mLastRawState.rawPointerData.pointerCount);
3184 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3185 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003186 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3188 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3189 "toolType=%d, isHovering=%s\n", i,
3190 pointer.id, pointer.x, pointer.y, pointer.pressure,
3191 pointer.touchMajor, pointer.touchMinor,
3192 pointer.toolMajor, pointer.toolMinor,
3193 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3194 pointer.toolType, toString(pointer.isHovering));
3195 }
3196
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003197 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3198 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003199 mLastCookedState.cookedPointerData.pointerCount);
3200 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3201 const PointerProperties& pointerProperties =
3202 mLastCookedState.cookedPointerData.pointerProperties[i];
3203 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003204 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3206 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3207 "toolType=%d, isHovering=%s\n", i,
3208 pointerProperties.id,
3209 pointerCoords.getX(),
3210 pointerCoords.getY(),
3211 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3212 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3213 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3214 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3215 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3216 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3217 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3218 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3219 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003220 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 }
3222
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003223 dump += INDENT3 "Stylus Fusion:\n";
3224 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003225 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003226 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3227 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003228 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003229 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003230 dumpStylusState(dump, mExternalStylusState);
3231
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003233 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3234 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003236 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003238 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003240 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003242 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 mPointerGestureMaxSwipeWidth);
3244 }
3245}
3246
Santos Cordonfa5cf462017-04-05 10:37:00 -07003247const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3248 switch (deviceMode) {
3249 case DEVICE_MODE_DISABLED:
3250 return "disabled";
3251 case DEVICE_MODE_DIRECT:
3252 return "direct";
3253 case DEVICE_MODE_UNSCALED:
3254 return "unscaled";
3255 case DEVICE_MODE_NAVIGATION:
3256 return "navigation";
3257 case DEVICE_MODE_POINTER:
3258 return "pointer";
3259 }
3260 return "unknown";
3261}
3262
Michael Wrightd02c5b62014-02-10 15:10:22 -08003263void TouchInputMapper::configure(nsecs_t when,
3264 const InputReaderConfiguration* config, uint32_t changes) {
3265 InputMapper::configure(when, config, changes);
3266
3267 mConfig = *config;
3268
3269 if (!changes) { // first time only
3270 // Configure basic parameters.
3271 configureParameters();
3272
3273 // Configure common accumulators.
3274 mCursorScrollAccumulator.configure(getDevice());
3275 mTouchButtonAccumulator.configure(getDevice());
3276
3277 // Configure absolute axis information.
3278 configureRawPointerAxes();
3279
3280 // Prepare input device calibration.
3281 parseCalibration();
3282 resolveCalibration();
3283 }
3284
Michael Wright842500e2015-03-13 17:32:02 -07003285 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003286 // Update location calibration to reflect current settings
3287 updateAffineTransformation();
3288 }
3289
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3291 // Update pointer speed.
3292 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3293 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3294 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3295 }
3296
3297 bool resetNeeded = false;
3298 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3299 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003300 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3301 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003302 // Configure device sources, surface dimensions, orientation and
3303 // scaling factors.
3304 configureSurface(when, &resetNeeded);
3305 }
3306
3307 if (changes && resetNeeded) {
3308 // Send reset, unless this is the first time the device has been configured,
3309 // in which case the reader will call reset itself after all mappers are ready.
3310 getDevice()->notifyReset(when);
3311 }
3312}
3313
Michael Wright842500e2015-03-13 17:32:02 -07003314void TouchInputMapper::resolveExternalStylusPresence() {
3315 Vector<InputDeviceInfo> devices;
3316 mContext->getExternalStylusDevices(devices);
3317 mExternalStylusConnected = !devices.isEmpty();
3318
3319 if (!mExternalStylusConnected) {
3320 resetExternalStylus();
3321 }
3322}
3323
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324void TouchInputMapper::configureParameters() {
3325 // Use the pointer presentation mode for devices that do not support distinct
3326 // multitouch. The spot-based presentation relies on being able to accurately
3327 // locate two or more fingers on the touch pad.
3328 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003329 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330
3331 String8 gestureModeString;
3332 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3333 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003334 if (gestureModeString == "single-touch") {
3335 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3336 } else if (gestureModeString == "multi-touch") {
3337 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338 } else if (gestureModeString != "default") {
3339 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3340 }
3341 }
3342
3343 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3344 // The device is a touch screen.
3345 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3346 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3347 // The device is a pointing device like a track pad.
3348 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3349 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3350 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3351 // The device is a cursor device with a touch pad attached.
3352 // By default don't use the touch pad to move the pointer.
3353 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3354 } else {
3355 // The device is a touch pad of unknown purpose.
3356 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3357 }
3358
3359 mParameters.hasButtonUnderPad=
3360 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3361
3362 String8 deviceTypeString;
3363 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3364 deviceTypeString)) {
3365 if (deviceTypeString == "touchScreen") {
3366 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3367 } else if (deviceTypeString == "touchPad") {
3368 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3369 } else if (deviceTypeString == "touchNavigation") {
3370 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3371 } else if (deviceTypeString == "pointer") {
3372 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3373 } else if (deviceTypeString != "default") {
3374 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3375 }
3376 }
3377
3378 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3379 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3380 mParameters.orientationAware);
3381
3382 mParameters.hasAssociatedDisplay = false;
3383 mParameters.associatedDisplayIsExternal = false;
3384 if (mParameters.orientationAware
3385 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3386 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3387 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003388 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3389 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3390 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3391 mParameters.uniqueDisplayId);
3392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003394
3395 // Initial downs on external touch devices should wake the device.
3396 // Normally we don't do this for internal touch screens to prevent them from waking
3397 // up in your pocket but you can enable it using the input device configuration.
3398 mParameters.wake = getDevice()->isExternal();
3399 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3400 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401}
3402
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003403void TouchInputMapper::dumpParameters(std::string& dump) {
3404 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405
3406 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003407 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003408 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003410 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003411 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 break;
3413 default:
3414 assert(false);
3415 }
3416
3417 switch (mParameters.deviceType) {
3418 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003419 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003420 break;
3421 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003422 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 break;
3424 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003425 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003426 break;
3427 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003428 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 break;
3430 default:
3431 ALOG_ASSERT(false);
3432 }
3433
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003434 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003435 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003437 toString(mParameters.associatedDisplayIsExternal),
3438 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003439 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 toString(mParameters.orientationAware));
3441}
3442
3443void TouchInputMapper::configureRawPointerAxes() {
3444 mRawPointerAxes.clear();
3445}
3446
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003447void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3448 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3450 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3451 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3452 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3453 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3454 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3455 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3456 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3457 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3458 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3459 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3460 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3461 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3462}
3463
Michael Wright842500e2015-03-13 17:32:02 -07003464bool TouchInputMapper::hasExternalStylus() const {
3465 return mExternalStylusConnected;
3466}
3467
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3469 int32_t oldDeviceMode = mDeviceMode;
3470
Michael Wright842500e2015-03-13 17:32:02 -07003471 resolveExternalStylusPresence();
3472
Michael Wrightd02c5b62014-02-10 15:10:22 -08003473 // Determine device mode.
3474 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3475 && mConfig.pointerGesturesEnabled) {
3476 mSource = AINPUT_SOURCE_MOUSE;
3477 mDeviceMode = DEVICE_MODE_POINTER;
3478 if (hasStylus()) {
3479 mSource |= AINPUT_SOURCE_STYLUS;
3480 }
3481 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3482 && mParameters.hasAssociatedDisplay) {
3483 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3484 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003485 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 mSource |= AINPUT_SOURCE_STYLUS;
3487 }
Michael Wright2f78b682015-06-12 15:25:08 +01003488 if (hasExternalStylus()) {
3489 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3490 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003491 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3492 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3493 mDeviceMode = DEVICE_MODE_NAVIGATION;
3494 } else {
3495 mSource = AINPUT_SOURCE_TOUCHPAD;
3496 mDeviceMode = DEVICE_MODE_UNSCALED;
3497 }
3498
3499 // Ensure we have valid X and Y axes.
3500 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3501 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3502 "The device will be inoperable.", getDeviceName().string());
3503 mDeviceMode = DEVICE_MODE_DISABLED;
3504 return;
3505 }
3506
3507 // Raw width and height in the natural orientation.
3508 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3509 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3510
3511 // Get associated display dimensions.
3512 DisplayViewport newViewport;
3513 if (mParameters.hasAssociatedDisplay) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003514 const String8* uniqueDisplayId = NULL;
3515 ViewportType viewportTypeToUse;
3516
3517 if (mParameters.associatedDisplayIsExternal) {
3518 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3519 } else if (!mParameters.uniqueDisplayId.isEmpty()) {
3520 // If the IDC file specified a unique display Id, then it expects to be linked to a
3521 // virtual display with the same unique ID.
3522 uniqueDisplayId = &mParameters.uniqueDisplayId;
3523 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3524 } else {
3525 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3526 }
3527
3528 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003529 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3530 "display. The device will be inoperable until the display size "
3531 "becomes available.",
3532 getDeviceName().string());
3533 mDeviceMode = DEVICE_MODE_DISABLED;
3534 return;
3535 }
3536 } else {
3537 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3538 }
3539 bool viewportChanged = mViewport != newViewport;
3540 if (viewportChanged) {
3541 mViewport = newViewport;
3542
3543 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3544 // Convert rotated viewport to natural surface coordinates.
3545 int32_t naturalLogicalWidth, naturalLogicalHeight;
3546 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3547 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3548 int32_t naturalDeviceWidth, naturalDeviceHeight;
3549 switch (mViewport.orientation) {
3550 case DISPLAY_ORIENTATION_90:
3551 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3552 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3553 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3554 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3555 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3556 naturalPhysicalTop = mViewport.physicalLeft;
3557 naturalDeviceWidth = mViewport.deviceHeight;
3558 naturalDeviceHeight = mViewport.deviceWidth;
3559 break;
3560 case DISPLAY_ORIENTATION_180:
3561 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3562 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3563 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3564 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3565 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3566 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3567 naturalDeviceWidth = mViewport.deviceWidth;
3568 naturalDeviceHeight = mViewport.deviceHeight;
3569 break;
3570 case DISPLAY_ORIENTATION_270:
3571 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3572 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3573 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3574 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3575 naturalPhysicalLeft = mViewport.physicalTop;
3576 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3577 naturalDeviceWidth = mViewport.deviceHeight;
3578 naturalDeviceHeight = mViewport.deviceWidth;
3579 break;
3580 case DISPLAY_ORIENTATION_0:
3581 default:
3582 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3583 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3584 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3585 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3586 naturalPhysicalLeft = mViewport.physicalLeft;
3587 naturalPhysicalTop = mViewport.physicalTop;
3588 naturalDeviceWidth = mViewport.deviceWidth;
3589 naturalDeviceHeight = mViewport.deviceHeight;
3590 break;
3591 }
3592
3593 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3594 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3595 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3596 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3597
3598 mSurfaceOrientation = mParameters.orientationAware ?
3599 mViewport.orientation : DISPLAY_ORIENTATION_0;
3600 } else {
3601 mSurfaceWidth = rawWidth;
3602 mSurfaceHeight = rawHeight;
3603 mSurfaceLeft = 0;
3604 mSurfaceTop = 0;
3605 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3606 }
3607 }
3608
3609 // If moving between pointer modes, need to reset some state.
3610 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3611 if (deviceModeChanged) {
3612 mOrientedRanges.clear();
3613 }
3614
3615 // Create pointer controller if needed.
3616 if (mDeviceMode == DEVICE_MODE_POINTER ||
3617 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3618 if (mPointerController == NULL) {
3619 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3620 }
3621 } else {
3622 mPointerController.clear();
3623 }
3624
3625 if (viewportChanged || deviceModeChanged) {
3626 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3627 "display id %d",
3628 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3629 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3630
3631 // Configure X and Y factors.
3632 mXScale = float(mSurfaceWidth) / rawWidth;
3633 mYScale = float(mSurfaceHeight) / rawHeight;
3634 mXTranslate = -mSurfaceLeft;
3635 mYTranslate = -mSurfaceTop;
3636 mXPrecision = 1.0f / mXScale;
3637 mYPrecision = 1.0f / mYScale;
3638
3639 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3640 mOrientedRanges.x.source = mSource;
3641 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3642 mOrientedRanges.y.source = mSource;
3643
3644 configureVirtualKeys();
3645
3646 // Scale factor for terms that are not oriented in a particular axis.
3647 // If the pixels are square then xScale == yScale otherwise we fake it
3648 // by choosing an average.
3649 mGeometricScale = avg(mXScale, mYScale);
3650
3651 // Size of diagonal axis.
3652 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3653
3654 // Size factors.
3655 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3656 if (mRawPointerAxes.touchMajor.valid
3657 && mRawPointerAxes.touchMajor.maxValue != 0) {
3658 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3659 } else if (mRawPointerAxes.toolMajor.valid
3660 && mRawPointerAxes.toolMajor.maxValue != 0) {
3661 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3662 } else {
3663 mSizeScale = 0.0f;
3664 }
3665
3666 mOrientedRanges.haveTouchSize = true;
3667 mOrientedRanges.haveToolSize = true;
3668 mOrientedRanges.haveSize = true;
3669
3670 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3671 mOrientedRanges.touchMajor.source = mSource;
3672 mOrientedRanges.touchMajor.min = 0;
3673 mOrientedRanges.touchMajor.max = diagonalSize;
3674 mOrientedRanges.touchMajor.flat = 0;
3675 mOrientedRanges.touchMajor.fuzz = 0;
3676 mOrientedRanges.touchMajor.resolution = 0;
3677
3678 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3679 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3680
3681 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3682 mOrientedRanges.toolMajor.source = mSource;
3683 mOrientedRanges.toolMajor.min = 0;
3684 mOrientedRanges.toolMajor.max = diagonalSize;
3685 mOrientedRanges.toolMajor.flat = 0;
3686 mOrientedRanges.toolMajor.fuzz = 0;
3687 mOrientedRanges.toolMajor.resolution = 0;
3688
3689 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3690 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3691
3692 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3693 mOrientedRanges.size.source = mSource;
3694 mOrientedRanges.size.min = 0;
3695 mOrientedRanges.size.max = 1.0;
3696 mOrientedRanges.size.flat = 0;
3697 mOrientedRanges.size.fuzz = 0;
3698 mOrientedRanges.size.resolution = 0;
3699 } else {
3700 mSizeScale = 0.0f;
3701 }
3702
3703 // Pressure factors.
3704 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003705 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3707 || mCalibration.pressureCalibration
3708 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3709 if (mCalibration.havePressureScale) {
3710 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003711 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 } else if (mRawPointerAxes.pressure.valid
3713 && mRawPointerAxes.pressure.maxValue != 0) {
3714 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3715 }
3716 }
3717
3718 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3719 mOrientedRanges.pressure.source = mSource;
3720 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003721 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722 mOrientedRanges.pressure.flat = 0;
3723 mOrientedRanges.pressure.fuzz = 0;
3724 mOrientedRanges.pressure.resolution = 0;
3725
3726 // Tilt
3727 mTiltXCenter = 0;
3728 mTiltXScale = 0;
3729 mTiltYCenter = 0;
3730 mTiltYScale = 0;
3731 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3732 if (mHaveTilt) {
3733 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3734 mRawPointerAxes.tiltX.maxValue);
3735 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3736 mRawPointerAxes.tiltY.maxValue);
3737 mTiltXScale = M_PI / 180;
3738 mTiltYScale = M_PI / 180;
3739
3740 mOrientedRanges.haveTilt = true;
3741
3742 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3743 mOrientedRanges.tilt.source = mSource;
3744 mOrientedRanges.tilt.min = 0;
3745 mOrientedRanges.tilt.max = M_PI_2;
3746 mOrientedRanges.tilt.flat = 0;
3747 mOrientedRanges.tilt.fuzz = 0;
3748 mOrientedRanges.tilt.resolution = 0;
3749 }
3750
3751 // Orientation
3752 mOrientationScale = 0;
3753 if (mHaveTilt) {
3754 mOrientedRanges.haveOrientation = true;
3755
3756 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3757 mOrientedRanges.orientation.source = mSource;
3758 mOrientedRanges.orientation.min = -M_PI;
3759 mOrientedRanges.orientation.max = M_PI;
3760 mOrientedRanges.orientation.flat = 0;
3761 mOrientedRanges.orientation.fuzz = 0;
3762 mOrientedRanges.orientation.resolution = 0;
3763 } else if (mCalibration.orientationCalibration !=
3764 Calibration::ORIENTATION_CALIBRATION_NONE) {
3765 if (mCalibration.orientationCalibration
3766 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3767 if (mRawPointerAxes.orientation.valid) {
3768 if (mRawPointerAxes.orientation.maxValue > 0) {
3769 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3770 } else if (mRawPointerAxes.orientation.minValue < 0) {
3771 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3772 } else {
3773 mOrientationScale = 0;
3774 }
3775 }
3776 }
3777
3778 mOrientedRanges.haveOrientation = true;
3779
3780 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3781 mOrientedRanges.orientation.source = mSource;
3782 mOrientedRanges.orientation.min = -M_PI_2;
3783 mOrientedRanges.orientation.max = M_PI_2;
3784 mOrientedRanges.orientation.flat = 0;
3785 mOrientedRanges.orientation.fuzz = 0;
3786 mOrientedRanges.orientation.resolution = 0;
3787 }
3788
3789 // Distance
3790 mDistanceScale = 0;
3791 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3792 if (mCalibration.distanceCalibration
3793 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3794 if (mCalibration.haveDistanceScale) {
3795 mDistanceScale = mCalibration.distanceScale;
3796 } else {
3797 mDistanceScale = 1.0f;
3798 }
3799 }
3800
3801 mOrientedRanges.haveDistance = true;
3802
3803 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3804 mOrientedRanges.distance.source = mSource;
3805 mOrientedRanges.distance.min =
3806 mRawPointerAxes.distance.minValue * mDistanceScale;
3807 mOrientedRanges.distance.max =
3808 mRawPointerAxes.distance.maxValue * mDistanceScale;
3809 mOrientedRanges.distance.flat = 0;
3810 mOrientedRanges.distance.fuzz =
3811 mRawPointerAxes.distance.fuzz * mDistanceScale;
3812 mOrientedRanges.distance.resolution = 0;
3813 }
3814
3815 // Compute oriented precision, scales and ranges.
3816 // Note that the maximum value reported is an inclusive maximum value so it is one
3817 // unit less than the total width or height of surface.
3818 switch (mSurfaceOrientation) {
3819 case DISPLAY_ORIENTATION_90:
3820 case DISPLAY_ORIENTATION_270:
3821 mOrientedXPrecision = mYPrecision;
3822 mOrientedYPrecision = mXPrecision;
3823
3824 mOrientedRanges.x.min = mYTranslate;
3825 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3826 mOrientedRanges.x.flat = 0;
3827 mOrientedRanges.x.fuzz = 0;
3828 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3829
3830 mOrientedRanges.y.min = mXTranslate;
3831 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3832 mOrientedRanges.y.flat = 0;
3833 mOrientedRanges.y.fuzz = 0;
3834 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3835 break;
3836
3837 default:
3838 mOrientedXPrecision = mXPrecision;
3839 mOrientedYPrecision = mYPrecision;
3840
3841 mOrientedRanges.x.min = mXTranslate;
3842 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3843 mOrientedRanges.x.flat = 0;
3844 mOrientedRanges.x.fuzz = 0;
3845 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3846
3847 mOrientedRanges.y.min = mYTranslate;
3848 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3849 mOrientedRanges.y.flat = 0;
3850 mOrientedRanges.y.fuzz = 0;
3851 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3852 break;
3853 }
3854
Jason Gerecke71b16e82014-03-10 09:47:59 -07003855 // Location
3856 updateAffineTransformation();
3857
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 if (mDeviceMode == DEVICE_MODE_POINTER) {
3859 // Compute pointer gesture detection parameters.
3860 float rawDiagonal = hypotf(rawWidth, rawHeight);
3861 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3862
3863 // Scale movements such that one whole swipe of the touch pad covers a
3864 // given area relative to the diagonal size of the display when no acceleration
3865 // is applied.
3866 // Assume that the touch pad has a square aspect ratio such that movements in
3867 // X and Y of the same number of raw units cover the same physical distance.
3868 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3869 * displayDiagonal / rawDiagonal;
3870 mPointerYMovementScale = mPointerXMovementScale;
3871
3872 // Scale zooms to cover a smaller range of the display than movements do.
3873 // This value determines the area around the pointer that is affected by freeform
3874 // pointer gestures.
3875 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3876 * displayDiagonal / rawDiagonal;
3877 mPointerYZoomScale = mPointerXZoomScale;
3878
3879 // Max width between pointers to detect a swipe gesture is more than some fraction
3880 // of the diagonal axis of the touch pad. Touches that are wider than this are
3881 // translated into freeform gestures.
3882 mPointerGestureMaxSwipeWidth =
3883 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3884
3885 // Abort current pointer usages because the state has changed.
3886 abortPointerUsage(when, 0 /*policyFlags*/);
3887 }
3888
3889 // Inform the dispatcher about the changes.
3890 *outResetNeeded = true;
3891 bumpGeneration();
3892 }
3893}
3894
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003895void TouchInputMapper::dumpSurface(std::string& dump) {
3896 dump += StringPrintf(INDENT3 "Viewport: displayId=%d, orientation=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 "logicalFrame=[%d, %d, %d, %d], "
3898 "physicalFrame=[%d, %d, %d, %d], "
3899 "deviceSize=[%d, %d]\n",
3900 mViewport.displayId, mViewport.orientation,
3901 mViewport.logicalLeft, mViewport.logicalTop,
3902 mViewport.logicalRight, mViewport.logicalBottom,
3903 mViewport.physicalLeft, mViewport.physicalTop,
3904 mViewport.physicalRight, mViewport.physicalBottom,
3905 mViewport.deviceWidth, mViewport.deviceHeight);
3906
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003907 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3908 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3909 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3910 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3911 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912}
3913
3914void TouchInputMapper::configureVirtualKeys() {
3915 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3916 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3917
3918 mVirtualKeys.clear();
3919
3920 if (virtualKeyDefinitions.size() == 0) {
3921 return;
3922 }
3923
3924 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3925
3926 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3927 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3928 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3929 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3930
3931 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3932 const VirtualKeyDefinition& virtualKeyDefinition =
3933 virtualKeyDefinitions[i];
3934
3935 mVirtualKeys.add();
3936 VirtualKey& virtualKey = mVirtualKeys.editTop();
3937
3938 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3939 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003940 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003941 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003942 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3943 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3945 virtualKey.scanCode);
3946 mVirtualKeys.pop(); // drop the key
3947 continue;
3948 }
3949
3950 virtualKey.keyCode = keyCode;
3951 virtualKey.flags = flags;
3952
3953 // convert the key definition's display coordinates into touch coordinates for a hit box
3954 int32_t halfWidth = virtualKeyDefinition.width / 2;
3955 int32_t halfHeight = virtualKeyDefinition.height / 2;
3956
3957 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3958 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3959 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3960 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3961 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3962 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3963 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3964 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3965 }
3966}
3967
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003968void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003970 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971
3972 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3973 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003974 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3976 i, virtualKey.scanCode, virtualKey.keyCode,
3977 virtualKey.hitLeft, virtualKey.hitRight,
3978 virtualKey.hitTop, virtualKey.hitBottom);
3979 }
3980 }
3981}
3982
3983void TouchInputMapper::parseCalibration() {
3984 const PropertyMap& in = getDevice()->getConfiguration();
3985 Calibration& out = mCalibration;
3986
3987 // Size
3988 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3989 String8 sizeCalibrationString;
3990 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3991 if (sizeCalibrationString == "none") {
3992 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3993 } else if (sizeCalibrationString == "geometric") {
3994 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3995 } else if (sizeCalibrationString == "diameter") {
3996 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3997 } else if (sizeCalibrationString == "box") {
3998 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3999 } else if (sizeCalibrationString == "area") {
4000 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4001 } else if (sizeCalibrationString != "default") {
4002 ALOGW("Invalid value for touch.size.calibration: '%s'",
4003 sizeCalibrationString.string());
4004 }
4005 }
4006
4007 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4008 out.sizeScale);
4009 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4010 out.sizeBias);
4011 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4012 out.sizeIsSummed);
4013
4014 // Pressure
4015 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4016 String8 pressureCalibrationString;
4017 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4018 if (pressureCalibrationString == "none") {
4019 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4020 } else if (pressureCalibrationString == "physical") {
4021 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4022 } else if (pressureCalibrationString == "amplitude") {
4023 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4024 } else if (pressureCalibrationString != "default") {
4025 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4026 pressureCalibrationString.string());
4027 }
4028 }
4029
4030 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4031 out.pressureScale);
4032
4033 // Orientation
4034 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4035 String8 orientationCalibrationString;
4036 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4037 if (orientationCalibrationString == "none") {
4038 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4039 } else if (orientationCalibrationString == "interpolated") {
4040 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4041 } else if (orientationCalibrationString == "vector") {
4042 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4043 } else if (orientationCalibrationString != "default") {
4044 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4045 orientationCalibrationString.string());
4046 }
4047 }
4048
4049 // Distance
4050 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4051 String8 distanceCalibrationString;
4052 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4053 if (distanceCalibrationString == "none") {
4054 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4055 } else if (distanceCalibrationString == "scaled") {
4056 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4057 } else if (distanceCalibrationString != "default") {
4058 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4059 distanceCalibrationString.string());
4060 }
4061 }
4062
4063 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4064 out.distanceScale);
4065
4066 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4067 String8 coverageCalibrationString;
4068 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4069 if (coverageCalibrationString == "none") {
4070 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4071 } else if (coverageCalibrationString == "box") {
4072 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4073 } else if (coverageCalibrationString != "default") {
4074 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4075 coverageCalibrationString.string());
4076 }
4077 }
4078}
4079
4080void TouchInputMapper::resolveCalibration() {
4081 // Size
4082 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4083 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4084 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4085 }
4086 } else {
4087 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4088 }
4089
4090 // Pressure
4091 if (mRawPointerAxes.pressure.valid) {
4092 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4093 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4094 }
4095 } else {
4096 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4097 }
4098
4099 // Orientation
4100 if (mRawPointerAxes.orientation.valid) {
4101 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4102 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4103 }
4104 } else {
4105 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4106 }
4107
4108 // Distance
4109 if (mRawPointerAxes.distance.valid) {
4110 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4111 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4112 }
4113 } else {
4114 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4115 }
4116
4117 // Coverage
4118 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4119 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4120 }
4121}
4122
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004123void TouchInputMapper::dumpCalibration(std::string& dump) {
4124 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125
4126 // Size
4127 switch (mCalibration.sizeCalibration) {
4128 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004129 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 break;
4131 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004132 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 break;
4134 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004135 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 break;
4137 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004138 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 break;
4140 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004141 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 break;
4143 default:
4144 ALOG_ASSERT(false);
4145 }
4146
4147 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004148 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 mCalibration.sizeScale);
4150 }
4151
4152 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004153 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 mCalibration.sizeBias);
4155 }
4156
4157 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004158 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 toString(mCalibration.sizeIsSummed));
4160 }
4161
4162 // Pressure
4163 switch (mCalibration.pressureCalibration) {
4164 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004165 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 break;
4167 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004168 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 break;
4170 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004171 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 break;
4173 default:
4174 ALOG_ASSERT(false);
4175 }
4176
4177 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004178 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 mCalibration.pressureScale);
4180 }
4181
4182 // Orientation
4183 switch (mCalibration.orientationCalibration) {
4184 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004185 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 break;
4187 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004188 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 break;
4190 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 break;
4193 default:
4194 ALOG_ASSERT(false);
4195 }
4196
4197 // Distance
4198 switch (mCalibration.distanceCalibration) {
4199 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004200 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 break;
4202 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004203 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 break;
4205 default:
4206 ALOG_ASSERT(false);
4207 }
4208
4209 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004210 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 mCalibration.distanceScale);
4212 }
4213
4214 switch (mCalibration.coverageCalibration) {
4215 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004216 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 break;
4218 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004219 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 break;
4221 default:
4222 ALOG_ASSERT(false);
4223 }
4224}
4225
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004226void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4227 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004228
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004229 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4230 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4231 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4232 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4233 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4234 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004235}
4236
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004237void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004238 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4239 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004240}
4241
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242void TouchInputMapper::reset(nsecs_t when) {
4243 mCursorButtonAccumulator.reset(getDevice());
4244 mCursorScrollAccumulator.reset(getDevice());
4245 mTouchButtonAccumulator.reset(getDevice());
4246
4247 mPointerVelocityControl.reset();
4248 mWheelXVelocityControl.reset();
4249 mWheelYVelocityControl.reset();
4250
Michael Wright842500e2015-03-13 17:32:02 -07004251 mRawStatesPending.clear();
4252 mCurrentRawState.clear();
4253 mCurrentCookedState.clear();
4254 mLastRawState.clear();
4255 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 mPointerUsage = POINTER_USAGE_NONE;
4257 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004258 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004259 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 mDownTime = 0;
4261
4262 mCurrentVirtualKey.down = false;
4263
4264 mPointerGesture.reset();
4265 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004266 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267
4268 if (mPointerController != NULL) {
4269 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4270 mPointerController->clearSpots();
4271 }
4272
4273 InputMapper::reset(when);
4274}
4275
Michael Wright842500e2015-03-13 17:32:02 -07004276void TouchInputMapper::resetExternalStylus() {
4277 mExternalStylusState.clear();
4278 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004279 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004280 mExternalStylusDataPending = false;
4281}
4282
Michael Wright43fd19f2015-04-21 19:02:58 +01004283void TouchInputMapper::clearStylusDataPendingFlags() {
4284 mExternalStylusDataPending = false;
4285 mExternalStylusFusionTimeout = LLONG_MAX;
4286}
4287
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288void TouchInputMapper::process(const RawEvent* rawEvent) {
4289 mCursorButtonAccumulator.process(rawEvent);
4290 mCursorScrollAccumulator.process(rawEvent);
4291 mTouchButtonAccumulator.process(rawEvent);
4292
4293 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4294 sync(rawEvent->when);
4295 }
4296}
4297
4298void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004299 const RawState* last = mRawStatesPending.isEmpty() ?
4300 &mCurrentRawState : &mRawStatesPending.top();
4301
4302 // Push a new state.
4303 mRawStatesPending.push();
4304 RawState* next = &mRawStatesPending.editTop();
4305 next->clear();
4306 next->when = when;
4307
Michael Wrightd02c5b62014-02-10 15:10:22 -08004308 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004309 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 | mCursorButtonAccumulator.getButtonState();
4311
Michael Wright842500e2015-03-13 17:32:02 -07004312 // Sync scroll
4313 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4314 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 mCursorScrollAccumulator.finishSync();
4316
Michael Wright842500e2015-03-13 17:32:02 -07004317 // Sync touch
4318 syncTouch(when, next);
4319
4320 // Assign pointer ids.
4321 if (!mHavePointerIds) {
4322 assignPointerIds(last, next);
4323 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324
4325#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004326 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4327 "hovering ids 0x%08x -> 0x%08x",
4328 last->rawPointerData.pointerCount,
4329 next->rawPointerData.pointerCount,
4330 last->rawPointerData.touchingIdBits.value,
4331 next->rawPointerData.touchingIdBits.value,
4332 last->rawPointerData.hoveringIdBits.value,
4333 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334#endif
4335
Michael Wright842500e2015-03-13 17:32:02 -07004336 processRawTouches(false /*timeout*/);
4337}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338
Michael Wright842500e2015-03-13 17:32:02 -07004339void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4341 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004342 mCurrentRawState.clear();
4343 mRawStatesPending.clear();
4344 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 }
4346
Michael Wright842500e2015-03-13 17:32:02 -07004347 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4348 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4349 // touching the current state will only observe the events that have been dispatched to the
4350 // rest of the pipeline.
4351 const size_t N = mRawStatesPending.size();
4352 size_t count;
4353 for(count = 0; count < N; count++) {
4354 const RawState& next = mRawStatesPending[count];
4355
4356 // A failure to assign the stylus id means that we're waiting on stylus data
4357 // and so should defer the rest of the pipeline.
4358 if (assignExternalStylusId(next, timeout)) {
4359 break;
4360 }
4361
4362 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004363 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004364 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004365 if (mCurrentRawState.when < mLastRawState.when) {
4366 mCurrentRawState.when = mLastRawState.when;
4367 }
Michael Wright842500e2015-03-13 17:32:02 -07004368 cookAndDispatch(mCurrentRawState.when);
4369 }
4370 if (count != 0) {
4371 mRawStatesPending.removeItemsAt(0, count);
4372 }
4373
Michael Wright842500e2015-03-13 17:32:02 -07004374 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004375 if (timeout) {
4376 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4377 clearStylusDataPendingFlags();
4378 mCurrentRawState.copyFrom(mLastRawState);
4379#if DEBUG_STYLUS_FUSION
4380 ALOGD("Timeout expired, synthesizing event with new stylus data");
4381#endif
4382 cookAndDispatch(when);
4383 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4384 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4385 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4386 }
Michael Wright842500e2015-03-13 17:32:02 -07004387 }
4388}
4389
4390void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4391 // Always start with a clean state.
4392 mCurrentCookedState.clear();
4393
4394 // Apply stylus buttons to current raw state.
4395 applyExternalStylusButtonState(when);
4396
4397 // Handle policy on initial down or hover events.
4398 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4399 && mCurrentRawState.rawPointerData.pointerCount != 0;
4400
4401 uint32_t policyFlags = 0;
4402 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4403 if (initialDown || buttonsPressed) {
4404 // If this is a touch screen, hide the pointer on an initial down.
4405 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4406 getContext()->fadePointer();
4407 }
4408
4409 if (mParameters.wake) {
4410 policyFlags |= POLICY_FLAG_WAKE;
4411 }
4412 }
4413
4414 // Consume raw off-screen touches before cooking pointer data.
4415 // If touches are consumed, subsequent code will not receive any pointer data.
4416 if (consumeRawTouches(when, policyFlags)) {
4417 mCurrentRawState.rawPointerData.clear();
4418 }
4419
4420 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4421 // with cooked pointer data that has the same ids and indices as the raw data.
4422 // The following code can use either the raw or cooked data, as needed.
4423 cookPointerData();
4424
4425 // Apply stylus pressure to current cooked state.
4426 applyExternalStylusTouchState(when);
4427
4428 // Synthesize key down from raw buttons if needed.
4429 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004430 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004431
4432 // Dispatch the touches either directly or by translation through a pointer on screen.
4433 if (mDeviceMode == DEVICE_MODE_POINTER) {
4434 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4435 !idBits.isEmpty(); ) {
4436 uint32_t id = idBits.clearFirstMarkedBit();
4437 const RawPointerData::Pointer& pointer =
4438 mCurrentRawState.rawPointerData.pointerForId(id);
4439 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4440 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4441 mCurrentCookedState.stylusIdBits.markBit(id);
4442 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4443 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4444 mCurrentCookedState.fingerIdBits.markBit(id);
4445 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4446 mCurrentCookedState.mouseIdBits.markBit(id);
4447 }
4448 }
4449 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4450 !idBits.isEmpty(); ) {
4451 uint32_t id = idBits.clearFirstMarkedBit();
4452 const RawPointerData::Pointer& pointer =
4453 mCurrentRawState.rawPointerData.pointerForId(id);
4454 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4455 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4456 mCurrentCookedState.stylusIdBits.markBit(id);
4457 }
4458 }
4459
4460 // Stylus takes precedence over all tools, then mouse, then finger.
4461 PointerUsage pointerUsage = mPointerUsage;
4462 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4463 mCurrentCookedState.mouseIdBits.clear();
4464 mCurrentCookedState.fingerIdBits.clear();
4465 pointerUsage = POINTER_USAGE_STYLUS;
4466 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4467 mCurrentCookedState.fingerIdBits.clear();
4468 pointerUsage = POINTER_USAGE_MOUSE;
4469 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4470 isPointerDown(mCurrentRawState.buttonState)) {
4471 pointerUsage = POINTER_USAGE_GESTURES;
4472 }
4473
4474 dispatchPointerUsage(when, policyFlags, pointerUsage);
4475 } else {
4476 if (mDeviceMode == DEVICE_MODE_DIRECT
4477 && mConfig.showTouches && mPointerController != NULL) {
4478 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4479 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4480
4481 mPointerController->setButtonState(mCurrentRawState.buttonState);
4482 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4483 mCurrentCookedState.cookedPointerData.idToIndex,
4484 mCurrentCookedState.cookedPointerData.touchingIdBits);
4485 }
4486
Michael Wright8e812822015-06-22 16:18:21 +01004487 if (!mCurrentMotionAborted) {
4488 dispatchButtonRelease(when, policyFlags);
4489 dispatchHoverExit(when, policyFlags);
4490 dispatchTouches(when, policyFlags);
4491 dispatchHoverEnterAndMove(when, policyFlags);
4492 dispatchButtonPress(when, policyFlags);
4493 }
4494
4495 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4496 mCurrentMotionAborted = false;
4497 }
Michael Wright842500e2015-03-13 17:32:02 -07004498 }
4499
4500 // Synthesize key up from raw buttons if needed.
4501 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004502 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004503
4504 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004505 mCurrentRawState.rawVScroll = 0;
4506 mCurrentRawState.rawHScroll = 0;
4507
4508 // Copy current touch to last touch in preparation for the next cycle.
4509 mLastRawState.copyFrom(mCurrentRawState);
4510 mLastCookedState.copyFrom(mCurrentCookedState);
4511}
4512
4513void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004514 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004515 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4516 }
4517}
4518
4519void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004520 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4521 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004522
Michael Wright53dca3a2015-04-23 17:39:53 +01004523 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4524 float pressure = mExternalStylusState.pressure;
4525 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4526 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4527 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4528 }
4529 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4530 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4531
4532 PointerProperties& properties =
4533 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004534 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4535 properties.toolType = mExternalStylusState.toolType;
4536 }
4537 }
4538}
4539
4540bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4541 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4542 return false;
4543 }
4544
4545 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4546 && state.rawPointerData.pointerCount != 0;
4547 if (initialDown) {
4548 if (mExternalStylusState.pressure != 0.0f) {
4549#if DEBUG_STYLUS_FUSION
4550 ALOGD("Have both stylus and touch data, beginning fusion");
4551#endif
4552 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4553 } else if (timeout) {
4554#if DEBUG_STYLUS_FUSION
4555 ALOGD("Timeout expired, assuming touch is not a stylus.");
4556#endif
4557 resetExternalStylus();
4558 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004559 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4560 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004561 }
4562#if DEBUG_STYLUS_FUSION
4563 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004564 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004565#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004566 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004567 return true;
4568 }
4569 }
4570
4571 // Check if the stylus pointer has gone up.
4572 if (mExternalStylusId != -1 &&
4573 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4574#if DEBUG_STYLUS_FUSION
4575 ALOGD("Stylus pointer is going up");
4576#endif
4577 mExternalStylusId = -1;
4578 }
4579
4580 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004581}
4582
4583void TouchInputMapper::timeoutExpired(nsecs_t when) {
4584 if (mDeviceMode == DEVICE_MODE_POINTER) {
4585 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4586 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4587 }
Michael Wright842500e2015-03-13 17:32:02 -07004588 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004589 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004590 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004591 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4592 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004593 }
4594 }
4595}
4596
4597void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004598 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004599 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004600 // We're either in the middle of a fused stream of data or we're waiting on data before
4601 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4602 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004603 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004604 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004605 }
4606}
4607
4608bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4609 // Check for release of a virtual key.
4610 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004611 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004612 // Pointer went up while virtual key was down.
4613 mCurrentVirtualKey.down = false;
4614 if (!mCurrentVirtualKey.ignored) {
4615#if DEBUG_VIRTUAL_KEYS
4616 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4617 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4618#endif
4619 dispatchVirtualKey(when, policyFlags,
4620 AKEY_EVENT_ACTION_UP,
4621 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4622 }
4623 return true;
4624 }
4625
Michael Wright842500e2015-03-13 17:32:02 -07004626 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4627 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4628 const RawPointerData::Pointer& pointer =
4629 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004630 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4631 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4632 // Pointer is still within the space of the virtual key.
4633 return true;
4634 }
4635 }
4636
4637 // Pointer left virtual key area or another pointer also went down.
4638 // Send key cancellation but do not consume the touch yet.
4639 // This is useful when the user swipes through from the virtual key area
4640 // into the main display surface.
4641 mCurrentVirtualKey.down = false;
4642 if (!mCurrentVirtualKey.ignored) {
4643#if DEBUG_VIRTUAL_KEYS
4644 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4645 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4646#endif
4647 dispatchVirtualKey(when, policyFlags,
4648 AKEY_EVENT_ACTION_UP,
4649 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4650 | AKEY_EVENT_FLAG_CANCELED);
4651 }
4652 }
4653
Michael Wright842500e2015-03-13 17:32:02 -07004654 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4655 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004657 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4658 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4660 // If exactly one pointer went down, check for virtual key hit.
4661 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004662 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4664 if (virtualKey) {
4665 mCurrentVirtualKey.down = true;
4666 mCurrentVirtualKey.downTime = when;
4667 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4668 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4669 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4670 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4671
4672 if (!mCurrentVirtualKey.ignored) {
4673#if DEBUG_VIRTUAL_KEYS
4674 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4675 mCurrentVirtualKey.keyCode,
4676 mCurrentVirtualKey.scanCode);
4677#endif
4678 dispatchVirtualKey(when, policyFlags,
4679 AKEY_EVENT_ACTION_DOWN,
4680 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4681 }
4682 }
4683 }
4684 return true;
4685 }
4686 }
4687
4688 // Disable all virtual key touches that happen within a short time interval of the
4689 // most recent touch within the screen area. The idea is to filter out stray
4690 // virtual key presses when interacting with the touch screen.
4691 //
4692 // Problems we're trying to solve:
4693 //
4694 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4695 // virtual key area that is implemented by a separate touch panel and accidentally
4696 // triggers a virtual key.
4697 //
4698 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4699 // area and accidentally triggers a virtual key. This often happens when virtual keys
4700 // are layed out below the screen near to where the on screen keyboard's space bar
4701 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004702 if (mConfig.virtualKeyQuietTime > 0 &&
4703 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4705 }
4706 return false;
4707}
4708
4709void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4710 int32_t keyEventAction, int32_t keyEventFlags) {
4711 int32_t keyCode = mCurrentVirtualKey.keyCode;
4712 int32_t scanCode = mCurrentVirtualKey.scanCode;
4713 nsecs_t downTime = mCurrentVirtualKey.downTime;
4714 int32_t metaState = mContext->getGlobalMetaState();
4715 policyFlags |= POLICY_FLAG_VIRTUAL;
4716
4717 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4718 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4719 getListener()->notifyKey(&args);
4720}
4721
Michael Wright8e812822015-06-22 16:18:21 +01004722void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4723 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4724 if (!currentIdBits.isEmpty()) {
4725 int32_t metaState = getContext()->getGlobalMetaState();
4726 int32_t buttonState = mCurrentCookedState.buttonState;
4727 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4728 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004729 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004730 mCurrentCookedState.cookedPointerData.pointerProperties,
4731 mCurrentCookedState.cookedPointerData.pointerCoords,
4732 mCurrentCookedState.cookedPointerData.idToIndex,
4733 currentIdBits, -1,
4734 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4735 mCurrentMotionAborted = true;
4736 }
4737}
4738
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004740 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4741 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004743 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744
4745 if (currentIdBits == lastIdBits) {
4746 if (!currentIdBits.isEmpty()) {
4747 // No pointer id changes so this is a move event.
4748 // The listener takes care of batching moves so we don't have to deal with that here.
4749 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004750 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004751 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004752 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004753 mCurrentCookedState.cookedPointerData.pointerProperties,
4754 mCurrentCookedState.cookedPointerData.pointerCoords,
4755 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 currentIdBits, -1,
4757 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4758 }
4759 } else {
4760 // There may be pointers going up and pointers going down and pointers moving
4761 // all at the same time.
4762 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4763 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4764 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4765 BitSet32 dispatchedIdBits(lastIdBits.value);
4766
4767 // Update last coordinates of pointers that have moved so that we observe the new
4768 // pointer positions at the same time as other pointers that have just gone up.
4769 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004770 mCurrentCookedState.cookedPointerData.pointerProperties,
4771 mCurrentCookedState.cookedPointerData.pointerCoords,
4772 mCurrentCookedState.cookedPointerData.idToIndex,
4773 mLastCookedState.cookedPointerData.pointerProperties,
4774 mLastCookedState.cookedPointerData.pointerCoords,
4775 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004777 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004778 moveNeeded = true;
4779 }
4780
4781 // Dispatch pointer up events.
4782 while (!upIdBits.isEmpty()) {
4783 uint32_t upId = upIdBits.clearFirstMarkedBit();
4784
4785 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004786 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004787 mCurrentCookedState.deviceTimestamp,
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,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004802 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004803 mCurrentCookedState.cookedPointerData.pointerProperties,
4804 mCurrentCookedState.cookedPointerData.pointerCoords,
4805 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004806 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807 }
4808
4809 // Dispatch pointer down events using the new pointer locations.
4810 while (!downIdBits.isEmpty()) {
4811 uint32_t downId = downIdBits.clearFirstMarkedBit();
4812 dispatchedIdBits.markBit(downId);
4813
4814 if (dispatchedIdBits.count() == 1) {
4815 // First pointer is going down. Set down time.
4816 mDownTime = when;
4817 }
4818
4819 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004820 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004821 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004822 mCurrentCookedState.cookedPointerData.pointerProperties,
4823 mCurrentCookedState.cookedPointerData.pointerCoords,
4824 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004825 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 }
4827 }
4828}
4829
4830void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4831 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004832 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4833 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 int32_t metaState = getContext()->getGlobalMetaState();
4835 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004836 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004837 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004838 mLastCookedState.cookedPointerData.pointerProperties,
4839 mLastCookedState.cookedPointerData.pointerCoords,
4840 mLastCookedState.cookedPointerData.idToIndex,
4841 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4843 mSentHoverEnter = false;
4844 }
4845}
4846
4847void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004848 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4849 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850 int32_t metaState = getContext()->getGlobalMetaState();
4851 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004852 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004853 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004854 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004855 mCurrentCookedState.cookedPointerData.pointerProperties,
4856 mCurrentCookedState.cookedPointerData.pointerCoords,
4857 mCurrentCookedState.cookedPointerData.idToIndex,
4858 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004859 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4860 mSentHoverEnter = true;
4861 }
4862
4863 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004864 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004865 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004866 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004867 mCurrentCookedState.cookedPointerData.pointerProperties,
4868 mCurrentCookedState.cookedPointerData.pointerCoords,
4869 mCurrentCookedState.cookedPointerData.idToIndex,
4870 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4872 }
4873}
4874
Michael Wright7b159c92015-05-14 14:48:03 +01004875void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4876 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4877 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4878 const int32_t metaState = getContext()->getGlobalMetaState();
4879 int32_t buttonState = mLastCookedState.buttonState;
4880 while (!releasedButtons.isEmpty()) {
4881 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4882 buttonState &= ~actionButton;
4883 dispatchMotion(when, policyFlags, mSource,
4884 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4885 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004886 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004887 mCurrentCookedState.cookedPointerData.pointerProperties,
4888 mCurrentCookedState.cookedPointerData.pointerCoords,
4889 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4890 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4891 }
4892}
4893
4894void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4895 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4896 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4897 const int32_t metaState = getContext()->getGlobalMetaState();
4898 int32_t buttonState = mLastCookedState.buttonState;
4899 while (!pressedButtons.isEmpty()) {
4900 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4901 buttonState |= actionButton;
4902 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4903 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004904 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004905 mCurrentCookedState.cookedPointerData.pointerProperties,
4906 mCurrentCookedState.cookedPointerData.pointerCoords,
4907 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4908 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4909 }
4910}
4911
4912const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4913 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4914 return cookedPointerData.touchingIdBits;
4915 }
4916 return cookedPointerData.hoveringIdBits;
4917}
4918
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004920 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921
Michael Wright842500e2015-03-13 17:32:02 -07004922 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004923 mCurrentCookedState.deviceTimestamp =
4924 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004925 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4926 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4927 mCurrentRawState.rawPointerData.hoveringIdBits;
4928 mCurrentCookedState.cookedPointerData.touchingIdBits =
4929 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930
Michael Wright7b159c92015-05-14 14:48:03 +01004931 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4932 mCurrentCookedState.buttonState = 0;
4933 } else {
4934 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4935 }
4936
Michael Wrightd02c5b62014-02-10 15:10:22 -08004937 // Walk through the the active pointers and map device coordinates onto
4938 // surface coordinates and adjust for display orientation.
4939 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004940 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004941
4942 // Size
4943 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4944 switch (mCalibration.sizeCalibration) {
4945 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4946 case Calibration::SIZE_CALIBRATION_DIAMETER:
4947 case Calibration::SIZE_CALIBRATION_BOX:
4948 case Calibration::SIZE_CALIBRATION_AREA:
4949 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4950 touchMajor = in.touchMajor;
4951 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4952 toolMajor = in.toolMajor;
4953 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4954 size = mRawPointerAxes.touchMinor.valid
4955 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4956 } else if (mRawPointerAxes.touchMajor.valid) {
4957 toolMajor = touchMajor = in.touchMajor;
4958 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4959 ? in.touchMinor : in.touchMajor;
4960 size = mRawPointerAxes.touchMinor.valid
4961 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4962 } else if (mRawPointerAxes.toolMajor.valid) {
4963 touchMajor = toolMajor = in.toolMajor;
4964 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4965 ? in.toolMinor : in.toolMajor;
4966 size = mRawPointerAxes.toolMinor.valid
4967 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4968 } else {
4969 ALOG_ASSERT(false, "No touch or tool axes. "
4970 "Size calibration should have been resolved to NONE.");
4971 touchMajor = 0;
4972 touchMinor = 0;
4973 toolMajor = 0;
4974 toolMinor = 0;
4975 size = 0;
4976 }
4977
4978 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004979 uint32_t touchingCount =
4980 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004981 if (touchingCount > 1) {
4982 touchMajor /= touchingCount;
4983 touchMinor /= touchingCount;
4984 toolMajor /= touchingCount;
4985 toolMinor /= touchingCount;
4986 size /= touchingCount;
4987 }
4988 }
4989
4990 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4991 touchMajor *= mGeometricScale;
4992 touchMinor *= mGeometricScale;
4993 toolMajor *= mGeometricScale;
4994 toolMinor *= mGeometricScale;
4995 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4996 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4997 touchMinor = touchMajor;
4998 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4999 toolMinor = toolMajor;
5000 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5001 touchMinor = touchMajor;
5002 toolMinor = toolMajor;
5003 }
5004
5005 mCalibration.applySizeScaleAndBias(&touchMajor);
5006 mCalibration.applySizeScaleAndBias(&touchMinor);
5007 mCalibration.applySizeScaleAndBias(&toolMajor);
5008 mCalibration.applySizeScaleAndBias(&toolMinor);
5009 size *= mSizeScale;
5010 break;
5011 default:
5012 touchMajor = 0;
5013 touchMinor = 0;
5014 toolMajor = 0;
5015 toolMinor = 0;
5016 size = 0;
5017 break;
5018 }
5019
5020 // Pressure
5021 float pressure;
5022 switch (mCalibration.pressureCalibration) {
5023 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5024 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5025 pressure = in.pressure * mPressureScale;
5026 break;
5027 default:
5028 pressure = in.isHovering ? 0 : 1;
5029 break;
5030 }
5031
5032 // Tilt and Orientation
5033 float tilt;
5034 float orientation;
5035 if (mHaveTilt) {
5036 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5037 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5038 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5039 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5040 } else {
5041 tilt = 0;
5042
5043 switch (mCalibration.orientationCalibration) {
5044 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5045 orientation = in.orientation * mOrientationScale;
5046 break;
5047 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5048 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5049 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5050 if (c1 != 0 || c2 != 0) {
5051 orientation = atan2f(c1, c2) * 0.5f;
5052 float confidence = hypotf(c1, c2);
5053 float scale = 1.0f + confidence / 16.0f;
5054 touchMajor *= scale;
5055 touchMinor /= scale;
5056 toolMajor *= scale;
5057 toolMinor /= scale;
5058 } else {
5059 orientation = 0;
5060 }
5061 break;
5062 }
5063 default:
5064 orientation = 0;
5065 }
5066 }
5067
5068 // Distance
5069 float distance;
5070 switch (mCalibration.distanceCalibration) {
5071 case Calibration::DISTANCE_CALIBRATION_SCALED:
5072 distance = in.distance * mDistanceScale;
5073 break;
5074 default:
5075 distance = 0;
5076 }
5077
5078 // Coverage
5079 int32_t rawLeft, rawTop, rawRight, rawBottom;
5080 switch (mCalibration.coverageCalibration) {
5081 case Calibration::COVERAGE_CALIBRATION_BOX:
5082 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5083 rawRight = in.toolMinor & 0x0000ffff;
5084 rawBottom = in.toolMajor & 0x0000ffff;
5085 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5086 break;
5087 default:
5088 rawLeft = rawTop = rawRight = rawBottom = 0;
5089 break;
5090 }
5091
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005092 // Adjust X,Y coords for device calibration
5093 // TODO: Adjust coverage coords?
5094 float xTransformed = in.x, yTransformed = in.y;
5095 mAffineTransform.applyTo(xTransformed, yTransformed);
5096
5097 // Adjust X, Y, and coverage coords for surface orientation.
5098 float x, y;
5099 float left, top, right, bottom;
5100
Michael Wrightd02c5b62014-02-10 15:10:22 -08005101 switch (mSurfaceOrientation) {
5102 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005103 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5104 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005105 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5106 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5107 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5108 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5109 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005110 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5112 }
5113 break;
5114 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005115 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5116 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005117 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5118 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5119 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5120 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5121 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005122 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5124 }
5125 break;
5126 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005127 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5128 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005129 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5130 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5131 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5132 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5133 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005134 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5136 }
5137 break;
5138 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005139 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5140 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5142 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5143 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5144 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5145 break;
5146 }
5147
5148 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005149 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005150 out.clear();
5151 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5152 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5153 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5154 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5155 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5156 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5157 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5158 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5159 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5160 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5161 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5162 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5163 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5164 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5165 } else {
5166 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5167 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5168 }
5169
5170 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005171 PointerProperties& properties =
5172 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 uint32_t id = in.id;
5174 properties.clear();
5175 properties.id = id;
5176 properties.toolType = in.toolType;
5177
5178 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005179 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005180 }
5181}
5182
5183void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5184 PointerUsage pointerUsage) {
5185 if (pointerUsage != mPointerUsage) {
5186 abortPointerUsage(when, policyFlags);
5187 mPointerUsage = pointerUsage;
5188 }
5189
5190 switch (mPointerUsage) {
5191 case POINTER_USAGE_GESTURES:
5192 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5193 break;
5194 case POINTER_USAGE_STYLUS:
5195 dispatchPointerStylus(when, policyFlags);
5196 break;
5197 case POINTER_USAGE_MOUSE:
5198 dispatchPointerMouse(when, policyFlags);
5199 break;
5200 default:
5201 break;
5202 }
5203}
5204
5205void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5206 switch (mPointerUsage) {
5207 case POINTER_USAGE_GESTURES:
5208 abortPointerGestures(when, policyFlags);
5209 break;
5210 case POINTER_USAGE_STYLUS:
5211 abortPointerStylus(when, policyFlags);
5212 break;
5213 case POINTER_USAGE_MOUSE:
5214 abortPointerMouse(when, policyFlags);
5215 break;
5216 default:
5217 break;
5218 }
5219
5220 mPointerUsage = POINTER_USAGE_NONE;
5221}
5222
5223void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5224 bool isTimeout) {
5225 // Update current gesture coordinates.
5226 bool cancelPreviousGesture, finishPreviousGesture;
5227 bool sendEvents = preparePointerGestures(when,
5228 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5229 if (!sendEvents) {
5230 return;
5231 }
5232 if (finishPreviousGesture) {
5233 cancelPreviousGesture = false;
5234 }
5235
5236 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005237 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5238 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239 if (finishPreviousGesture || cancelPreviousGesture) {
5240 mPointerController->clearSpots();
5241 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005242
5243 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5244 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5245 mPointerGesture.currentGestureIdToIndex,
5246 mPointerGesture.currentGestureIdBits);
5247 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 } else {
5249 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5250 }
5251
5252 // Show or hide the pointer if needed.
5253 switch (mPointerGesture.currentGestureMode) {
5254 case PointerGesture::NEUTRAL:
5255 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005256 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5257 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005258 // Remind the user of where the pointer is after finishing a gesture with spots.
5259 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5260 }
5261 break;
5262 case PointerGesture::TAP:
5263 case PointerGesture::TAP_DRAG:
5264 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5265 case PointerGesture::HOVER:
5266 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005267 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 // Unfade the pointer when the current gesture manipulates the
5269 // area directly under the pointer.
5270 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5271 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 case PointerGesture::FREEFORM:
5273 // Fade the pointer when the current gesture manipulates a different
5274 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005275 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005276 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5277 } else {
5278 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5279 }
5280 break;
5281 }
5282
5283 // Send events!
5284 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005285 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005286
5287 // Update last coordinates of pointers that have moved so that we observe the new
5288 // pointer positions at the same time as other pointers that have just gone up.
5289 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5290 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5291 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5292 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5293 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5294 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5295 bool moveNeeded = false;
5296 if (down && !cancelPreviousGesture && !finishPreviousGesture
5297 && !mPointerGesture.lastGestureIdBits.isEmpty()
5298 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5299 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5300 & mPointerGesture.lastGestureIdBits.value);
5301 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5302 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5303 mPointerGesture.lastGestureProperties,
5304 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5305 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005306 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307 moveNeeded = true;
5308 }
5309 }
5310
5311 // Send motion events for all pointers that went up or were canceled.
5312 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5313 if (!dispatchedGestureIdBits.isEmpty()) {
5314 if (cancelPreviousGesture) {
5315 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005316 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005317 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318 mPointerGesture.lastGestureProperties,
5319 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005320 dispatchedGestureIdBits, -1, 0,
5321 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322
5323 dispatchedGestureIdBits.clear();
5324 } else {
5325 BitSet32 upGestureIdBits;
5326 if (finishPreviousGesture) {
5327 upGestureIdBits = dispatchedGestureIdBits;
5328 } else {
5329 upGestureIdBits.value = dispatchedGestureIdBits.value
5330 & ~mPointerGesture.currentGestureIdBits.value;
5331 }
5332 while (!upGestureIdBits.isEmpty()) {
5333 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5334
5335 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005336 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005337 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005338 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 mPointerGesture.lastGestureProperties,
5340 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5341 dispatchedGestureIdBits, id,
5342 0, 0, mPointerGesture.downTime);
5343
5344 dispatchedGestureIdBits.clearBit(id);
5345 }
5346 }
5347 }
5348
5349 // Send motion events for all pointers that moved.
5350 if (moveNeeded) {
5351 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005352 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005353 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005354 mPointerGesture.currentGestureProperties,
5355 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5356 dispatchedGestureIdBits, -1,
5357 0, 0, mPointerGesture.downTime);
5358 }
5359
5360 // Send motion events for all pointers that went down.
5361 if (down) {
5362 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5363 & ~dispatchedGestureIdBits.value);
5364 while (!downGestureIdBits.isEmpty()) {
5365 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5366 dispatchedGestureIdBits.markBit(id);
5367
5368 if (dispatchedGestureIdBits.count() == 1) {
5369 mPointerGesture.downTime = when;
5370 }
5371
5372 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005373 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005374 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 mPointerGesture.currentGestureProperties,
5376 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5377 dispatchedGestureIdBits, id,
5378 0, 0, mPointerGesture.downTime);
5379 }
5380 }
5381
5382 // Send motion events for hover.
5383 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5384 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005385 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005386 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005387 mPointerGesture.currentGestureProperties,
5388 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5389 mPointerGesture.currentGestureIdBits, -1,
5390 0, 0, mPointerGesture.downTime);
5391 } else if (dispatchedGestureIdBits.isEmpty()
5392 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5393 // Synthesize a hover move event after all pointers go up to indicate that
5394 // the pointer is hovering again even if the user is not currently touching
5395 // the touch pad. This ensures that a view will receive a fresh hover enter
5396 // event after a tap.
5397 float x, y;
5398 mPointerController->getPosition(&x, &y);
5399
5400 PointerProperties pointerProperties;
5401 pointerProperties.clear();
5402 pointerProperties.id = 0;
5403 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5404
5405 PointerCoords pointerCoords;
5406 pointerCoords.clear();
5407 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5408 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5409
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005410 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005411 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005413 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005414 0, 0, mPointerGesture.downTime);
5415 getListener()->notifyMotion(&args);
5416 }
5417
5418 // Update state.
5419 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5420 if (!down) {
5421 mPointerGesture.lastGestureIdBits.clear();
5422 } else {
5423 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5424 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5425 uint32_t id = idBits.clearFirstMarkedBit();
5426 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5427 mPointerGesture.lastGestureProperties[index].copyFrom(
5428 mPointerGesture.currentGestureProperties[index]);
5429 mPointerGesture.lastGestureCoords[index].copyFrom(
5430 mPointerGesture.currentGestureCoords[index]);
5431 mPointerGesture.lastGestureIdToIndex[id] = index;
5432 }
5433 }
5434}
5435
5436void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5437 // Cancel previously dispatches pointers.
5438 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5439 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005440 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005441 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005442 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005443 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005444 mPointerGesture.lastGestureProperties,
5445 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5446 mPointerGesture.lastGestureIdBits, -1,
5447 0, 0, mPointerGesture.downTime);
5448 }
5449
5450 // Reset the current pointer gesture.
5451 mPointerGesture.reset();
5452 mPointerVelocityControl.reset();
5453
5454 // Remove any current spots.
5455 if (mPointerController != NULL) {
5456 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5457 mPointerController->clearSpots();
5458 }
5459}
5460
5461bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5462 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5463 *outCancelPreviousGesture = false;
5464 *outFinishPreviousGesture = false;
5465
5466 // Handle TAP timeout.
5467 if (isTimeout) {
5468#if DEBUG_GESTURES
5469 ALOGD("Gestures: Processing timeout");
5470#endif
5471
5472 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5473 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5474 // The tap/drag timeout has not yet expired.
5475 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5476 + mConfig.pointerGestureTapDragInterval);
5477 } else {
5478 // The tap is finished.
5479#if DEBUG_GESTURES
5480 ALOGD("Gestures: TAP finished");
5481#endif
5482 *outFinishPreviousGesture = true;
5483
5484 mPointerGesture.activeGestureId = -1;
5485 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5486 mPointerGesture.currentGestureIdBits.clear();
5487
5488 mPointerVelocityControl.reset();
5489 return true;
5490 }
5491 }
5492
5493 // We did not handle this timeout.
5494 return false;
5495 }
5496
Michael Wright842500e2015-03-13 17:32:02 -07005497 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5498 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499
5500 // Update the velocity tracker.
5501 {
5502 VelocityTracker::Position positions[MAX_POINTERS];
5503 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005504 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005506 const RawPointerData::Pointer& pointer =
5507 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508 positions[count].x = pointer.x * mPointerXMovementScale;
5509 positions[count].y = pointer.y * mPointerYMovementScale;
5510 }
5511 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005512 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513 }
5514
5515 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5516 // to NEUTRAL, then we should not generate tap event.
5517 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5518 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5519 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5520 mPointerGesture.resetTap();
5521 }
5522
5523 // Pick a new active touch id if needed.
5524 // Choose an arbitrary pointer that just went down, if there is one.
5525 // Otherwise choose an arbitrary remaining pointer.
5526 // This guarantees we always have an active touch id when there is at least one pointer.
5527 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5529 int32_t activeTouchId = lastActiveTouchId;
5530 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005531 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005533 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 mPointerGesture.firstTouchTime = when;
5535 }
Michael Wright842500e2015-03-13 17:32:02 -07005536 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005537 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005538 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005539 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005540 } else {
5541 activeTouchId = mPointerGesture.activeTouchId = -1;
5542 }
5543 }
5544
5545 // Determine whether we are in quiet time.
5546 bool isQuietTime = false;
5547 if (activeTouchId < 0) {
5548 mPointerGesture.resetQuietTime();
5549 } else {
5550 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5551 if (!isQuietTime) {
5552 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5553 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5554 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5555 && currentFingerCount < 2) {
5556 // Enter quiet time when exiting swipe or freeform state.
5557 // This is to prevent accidentally entering the hover state and flinging the
5558 // pointer when finishing a swipe and there is still one pointer left onscreen.
5559 isQuietTime = true;
5560 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5561 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005562 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563 // Enter quiet time when releasing the button and there are still two or more
5564 // fingers down. This may indicate that one finger was used to press the button
5565 // but it has not gone up yet.
5566 isQuietTime = true;
5567 }
5568 if (isQuietTime) {
5569 mPointerGesture.quietTime = when;
5570 }
5571 }
5572 }
5573
5574 // Switch states based on button and pointer state.
5575 if (isQuietTime) {
5576 // Case 1: Quiet time. (QUIET)
5577#if DEBUG_GESTURES
5578 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5579 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5580#endif
5581 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5582 *outFinishPreviousGesture = true;
5583 }
5584
5585 mPointerGesture.activeGestureId = -1;
5586 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5587 mPointerGesture.currentGestureIdBits.clear();
5588
5589 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005590 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5592 // The pointer follows the active touch point.
5593 // Emit DOWN, MOVE, UP events at the pointer location.
5594 //
5595 // Only the active touch matters; other fingers are ignored. This policy helps
5596 // to handle the case where the user places a second finger on the touch pad
5597 // to apply the necessary force to depress an integrated button below the surface.
5598 // We don't want the second finger to be delivered to applications.
5599 //
5600 // For this to work well, we need to make sure to track the pointer that is really
5601 // active. If the user first puts one finger down to click then adds another
5602 // finger to drag then the active pointer should switch to the finger that is
5603 // being dragged.
5604#if DEBUG_GESTURES
5605 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5606 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5607#endif
5608 // Reset state when just starting.
5609 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5610 *outFinishPreviousGesture = true;
5611 mPointerGesture.activeGestureId = 0;
5612 }
5613
5614 // Switch pointers if needed.
5615 // Find the fastest pointer and follow it.
5616 if (activeTouchId >= 0 && currentFingerCount > 1) {
5617 int32_t bestId = -1;
5618 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005619 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620 uint32_t id = idBits.clearFirstMarkedBit();
5621 float vx, vy;
5622 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5623 float speed = hypotf(vx, vy);
5624 if (speed > bestSpeed) {
5625 bestId = id;
5626 bestSpeed = speed;
5627 }
5628 }
5629 }
5630 if (bestId >= 0 && bestId != activeTouchId) {
5631 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632#if DEBUG_GESTURES
5633 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5634 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5635#endif
5636 }
5637 }
5638
Jun Mukaifa1706a2015-12-03 01:14:46 -08005639 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005640 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005642 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005644 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005645 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5646 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005647
5648 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5649 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5650
5651 // Move the pointer using a relative motion.
5652 // When using spots, the click will occur at the position of the anchor
5653 // spot and all other spots will move there.
5654 mPointerController->move(deltaX, deltaY);
5655 } else {
5656 mPointerVelocityControl.reset();
5657 }
5658
5659 float x, y;
5660 mPointerController->getPosition(&x, &y);
5661
5662 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5663 mPointerGesture.currentGestureIdBits.clear();
5664 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5665 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5666 mPointerGesture.currentGestureProperties[0].clear();
5667 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5668 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5669 mPointerGesture.currentGestureCoords[0].clear();
5670 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5671 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5672 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5673 } else if (currentFingerCount == 0) {
5674 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5675 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5676 *outFinishPreviousGesture = true;
5677 }
5678
5679 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5680 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5681 bool tapped = false;
5682 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5683 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5684 && lastFingerCount == 1) {
5685 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5686 float x, y;
5687 mPointerController->getPosition(&x, &y);
5688 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5689 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5690#if DEBUG_GESTURES
5691 ALOGD("Gestures: TAP");
5692#endif
5693
5694 mPointerGesture.tapUpTime = when;
5695 getContext()->requestTimeoutAtTime(when
5696 + mConfig.pointerGestureTapDragInterval);
5697
5698 mPointerGesture.activeGestureId = 0;
5699 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5700 mPointerGesture.currentGestureIdBits.clear();
5701 mPointerGesture.currentGestureIdBits.markBit(
5702 mPointerGesture.activeGestureId);
5703 mPointerGesture.currentGestureIdToIndex[
5704 mPointerGesture.activeGestureId] = 0;
5705 mPointerGesture.currentGestureProperties[0].clear();
5706 mPointerGesture.currentGestureProperties[0].id =
5707 mPointerGesture.activeGestureId;
5708 mPointerGesture.currentGestureProperties[0].toolType =
5709 AMOTION_EVENT_TOOL_TYPE_FINGER;
5710 mPointerGesture.currentGestureCoords[0].clear();
5711 mPointerGesture.currentGestureCoords[0].setAxisValue(
5712 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5713 mPointerGesture.currentGestureCoords[0].setAxisValue(
5714 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5715 mPointerGesture.currentGestureCoords[0].setAxisValue(
5716 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5717
5718 tapped = true;
5719 } else {
5720#if DEBUG_GESTURES
5721 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5722 x - mPointerGesture.tapX,
5723 y - mPointerGesture.tapY);
5724#endif
5725 }
5726 } else {
5727#if DEBUG_GESTURES
5728 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5729 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5730 (when - mPointerGesture.tapDownTime) * 0.000001f);
5731 } else {
5732 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5733 }
5734#endif
5735 }
5736 }
5737
5738 mPointerVelocityControl.reset();
5739
5740 if (!tapped) {
5741#if DEBUG_GESTURES
5742 ALOGD("Gestures: NEUTRAL");
5743#endif
5744 mPointerGesture.activeGestureId = -1;
5745 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5746 mPointerGesture.currentGestureIdBits.clear();
5747 }
5748 } else if (currentFingerCount == 1) {
5749 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5750 // The pointer follows the active touch point.
5751 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5752 // When in TAP_DRAG, emit MOVE events at the pointer location.
5753 ALOG_ASSERT(activeTouchId >= 0);
5754
5755 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5756 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5757 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5758 float x, y;
5759 mPointerController->getPosition(&x, &y);
5760 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5761 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5762 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5763 } else {
5764#if DEBUG_GESTURES
5765 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5766 x - mPointerGesture.tapX,
5767 y - mPointerGesture.tapY);
5768#endif
5769 }
5770 } else {
5771#if DEBUG_GESTURES
5772 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5773 (when - mPointerGesture.tapUpTime) * 0.000001f);
5774#endif
5775 }
5776 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5777 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5778 }
5779
Jun Mukaifa1706a2015-12-03 01:14:46 -08005780 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005781 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005783 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005784 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005785 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005786 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5787 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005788
5789 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5790 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5791
5792 // Move the pointer using a relative motion.
5793 // When using spots, the hover or drag will occur at the position of the anchor spot.
5794 mPointerController->move(deltaX, deltaY);
5795 } else {
5796 mPointerVelocityControl.reset();
5797 }
5798
5799 bool down;
5800 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5801#if DEBUG_GESTURES
5802 ALOGD("Gestures: TAP_DRAG");
5803#endif
5804 down = true;
5805 } else {
5806#if DEBUG_GESTURES
5807 ALOGD("Gestures: HOVER");
5808#endif
5809 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5810 *outFinishPreviousGesture = true;
5811 }
5812 mPointerGesture.activeGestureId = 0;
5813 down = false;
5814 }
5815
5816 float x, y;
5817 mPointerController->getPosition(&x, &y);
5818
5819 mPointerGesture.currentGestureIdBits.clear();
5820 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5821 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5822 mPointerGesture.currentGestureProperties[0].clear();
5823 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5824 mPointerGesture.currentGestureProperties[0].toolType =
5825 AMOTION_EVENT_TOOL_TYPE_FINGER;
5826 mPointerGesture.currentGestureCoords[0].clear();
5827 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5828 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5829 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5830 down ? 1.0f : 0.0f);
5831
5832 if (lastFingerCount == 0 && currentFingerCount != 0) {
5833 mPointerGesture.resetTap();
5834 mPointerGesture.tapDownTime = when;
5835 mPointerGesture.tapX = x;
5836 mPointerGesture.tapY = y;
5837 }
5838 } else {
5839 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5840 // We need to provide feedback for each finger that goes down so we cannot wait
5841 // for the fingers to move before deciding what to do.
5842 //
5843 // The ambiguous case is deciding what to do when there are two fingers down but they
5844 // have not moved enough to determine whether they are part of a drag or part of a
5845 // freeform gesture, or just a press or long-press at the pointer location.
5846 //
5847 // When there are two fingers we start with the PRESS hypothesis and we generate a
5848 // down at the pointer location.
5849 //
5850 // When the two fingers move enough or when additional fingers are added, we make
5851 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5852 ALOG_ASSERT(activeTouchId >= 0);
5853
5854 bool settled = when >= mPointerGesture.firstTouchTime
5855 + mConfig.pointerGestureMultitouchSettleInterval;
5856 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5857 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5858 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5859 *outFinishPreviousGesture = true;
5860 } else if (!settled && currentFingerCount > lastFingerCount) {
5861 // Additional pointers have gone down but not yet settled.
5862 // Reset the gesture.
5863#if DEBUG_GESTURES
5864 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5865 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5866 + mConfig.pointerGestureMultitouchSettleInterval - when)
5867 * 0.000001f);
5868#endif
5869 *outCancelPreviousGesture = true;
5870 } else {
5871 // Continue previous gesture.
5872 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5873 }
5874
5875 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5876 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5877 mPointerGesture.activeGestureId = 0;
5878 mPointerGesture.referenceIdBits.clear();
5879 mPointerVelocityControl.reset();
5880
5881 // Use the centroid and pointer location as the reference points for the gesture.
5882#if DEBUG_GESTURES
5883 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5884 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5885 + mConfig.pointerGestureMultitouchSettleInterval - when)
5886 * 0.000001f);
5887#endif
Michael Wright842500e2015-03-13 17:32:02 -07005888 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005889 &mPointerGesture.referenceTouchX,
5890 &mPointerGesture.referenceTouchY);
5891 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5892 &mPointerGesture.referenceGestureY);
5893 }
5894
5895 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005896 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005897 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5898 uint32_t id = idBits.clearFirstMarkedBit();
5899 mPointerGesture.referenceDeltas[id].dx = 0;
5900 mPointerGesture.referenceDeltas[id].dy = 0;
5901 }
Michael Wright842500e2015-03-13 17:32:02 -07005902 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005903
5904 // Add delta for all fingers and calculate a common movement delta.
5905 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005906 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5907 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005908 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5909 bool first = (idBits == commonIdBits);
5910 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005911 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5912 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5914 delta.dx += cpd.x - lpd.x;
5915 delta.dy += cpd.y - lpd.y;
5916
5917 if (first) {
5918 commonDeltaX = delta.dx;
5919 commonDeltaY = delta.dy;
5920 } else {
5921 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5922 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5923 }
5924 }
5925
5926 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5927 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5928 float dist[MAX_POINTER_ID + 1];
5929 int32_t distOverThreshold = 0;
5930 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5931 uint32_t id = idBits.clearFirstMarkedBit();
5932 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5933 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5934 delta.dy * mPointerYZoomScale);
5935 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5936 distOverThreshold += 1;
5937 }
5938 }
5939
5940 // Only transition when at least two pointers have moved further than
5941 // the minimum distance threshold.
5942 if (distOverThreshold >= 2) {
5943 if (currentFingerCount > 2) {
5944 // There are more than two pointers, switch to FREEFORM.
5945#if DEBUG_GESTURES
5946 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5947 currentFingerCount);
5948#endif
5949 *outCancelPreviousGesture = true;
5950 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5951 } else {
5952 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005953 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005954 uint32_t id1 = idBits.clearFirstMarkedBit();
5955 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005956 const RawPointerData::Pointer& p1 =
5957 mCurrentRawState.rawPointerData.pointerForId(id1);
5958 const RawPointerData::Pointer& p2 =
5959 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005960 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5961 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5962 // There are two pointers but they are too far apart for a SWIPE,
5963 // switch to FREEFORM.
5964#if DEBUG_GESTURES
5965 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5966 mutualDistance, mPointerGestureMaxSwipeWidth);
5967#endif
5968 *outCancelPreviousGesture = true;
5969 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5970 } else {
5971 // There are two pointers. Wait for both pointers to start moving
5972 // before deciding whether this is a SWIPE or FREEFORM gesture.
5973 float dist1 = dist[id1];
5974 float dist2 = dist[id2];
5975 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5976 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5977 // Calculate the dot product of the displacement vectors.
5978 // When the vectors are oriented in approximately the same direction,
5979 // the angle betweeen them is near zero and the cosine of the angle
5980 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5981 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5982 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5983 float dx1 = delta1.dx * mPointerXZoomScale;
5984 float dy1 = delta1.dy * mPointerYZoomScale;
5985 float dx2 = delta2.dx * mPointerXZoomScale;
5986 float dy2 = delta2.dy * mPointerYZoomScale;
5987 float dot = dx1 * dx2 + dy1 * dy2;
5988 float cosine = dot / (dist1 * dist2); // denominator always > 0
5989 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5990 // Pointers are moving in the same direction. Switch to SWIPE.
5991#if DEBUG_GESTURES
5992 ALOGD("Gestures: PRESS transitioned to SWIPE, "
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 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6000 } else {
6001 // Pointers are moving in different directions. Switch to FREEFORM.
6002#if DEBUG_GESTURES
6003 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6004 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6005 "cosine %0.3f < %0.3f",
6006 dist1, mConfig.pointerGestureMultitouchMinDistance,
6007 dist2, mConfig.pointerGestureMultitouchMinDistance,
6008 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6009#endif
6010 *outCancelPreviousGesture = true;
6011 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6012 }
6013 }
6014 }
6015 }
6016 }
6017 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6018 // Switch from SWIPE to FREEFORM if additional pointers go down.
6019 // Cancel previous gesture.
6020 if (currentFingerCount > 2) {
6021#if DEBUG_GESTURES
6022 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6023 currentFingerCount);
6024#endif
6025 *outCancelPreviousGesture = true;
6026 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6027 }
6028 }
6029
6030 // Move the reference points based on the overall group motion of the fingers
6031 // except in PRESS mode while waiting for a transition to occur.
6032 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6033 && (commonDeltaX || commonDeltaY)) {
6034 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6035 uint32_t id = idBits.clearFirstMarkedBit();
6036 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6037 delta.dx = 0;
6038 delta.dy = 0;
6039 }
6040
6041 mPointerGesture.referenceTouchX += commonDeltaX;
6042 mPointerGesture.referenceTouchY += commonDeltaY;
6043
6044 commonDeltaX *= mPointerXMovementScale;
6045 commonDeltaY *= mPointerYMovementScale;
6046
6047 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6048 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6049
6050 mPointerGesture.referenceGestureX += commonDeltaX;
6051 mPointerGesture.referenceGestureY += commonDeltaY;
6052 }
6053
6054 // Report gestures.
6055 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6056 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6057 // PRESS or SWIPE mode.
6058#if DEBUG_GESTURES
6059 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6060 "activeGestureId=%d, currentTouchPointerCount=%d",
6061 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6062#endif
6063 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6064
6065 mPointerGesture.currentGestureIdBits.clear();
6066 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6067 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6068 mPointerGesture.currentGestureProperties[0].clear();
6069 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6070 mPointerGesture.currentGestureProperties[0].toolType =
6071 AMOTION_EVENT_TOOL_TYPE_FINGER;
6072 mPointerGesture.currentGestureCoords[0].clear();
6073 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6074 mPointerGesture.referenceGestureX);
6075 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6076 mPointerGesture.referenceGestureY);
6077 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6078 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6079 // FREEFORM mode.
6080#if DEBUG_GESTURES
6081 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6082 "activeGestureId=%d, currentTouchPointerCount=%d",
6083 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6084#endif
6085 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6086
6087 mPointerGesture.currentGestureIdBits.clear();
6088
6089 BitSet32 mappedTouchIdBits;
6090 BitSet32 usedGestureIdBits;
6091 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6092 // Initially, assign the active gesture id to the active touch point
6093 // if there is one. No other touch id bits are mapped yet.
6094 if (!*outCancelPreviousGesture) {
6095 mappedTouchIdBits.markBit(activeTouchId);
6096 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6097 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6098 mPointerGesture.activeGestureId;
6099 } else {
6100 mPointerGesture.activeGestureId = -1;
6101 }
6102 } else {
6103 // Otherwise, assume we mapped all touches from the previous frame.
6104 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006105 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6106 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006107 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6108
6109 // Check whether we need to choose a new active gesture id because the
6110 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006111 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6112 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006113 !upTouchIdBits.isEmpty(); ) {
6114 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6115 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6116 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6117 mPointerGesture.activeGestureId = -1;
6118 break;
6119 }
6120 }
6121 }
6122
6123#if DEBUG_GESTURES
6124 ALOGD("Gestures: FREEFORM follow up "
6125 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6126 "activeGestureId=%d",
6127 mappedTouchIdBits.value, usedGestureIdBits.value,
6128 mPointerGesture.activeGestureId);
6129#endif
6130
Michael Wright842500e2015-03-13 17:32:02 -07006131 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006132 for (uint32_t i = 0; i < currentFingerCount; i++) {
6133 uint32_t touchId = idBits.clearFirstMarkedBit();
6134 uint32_t gestureId;
6135 if (!mappedTouchIdBits.hasBit(touchId)) {
6136 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6137 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6138#if DEBUG_GESTURES
6139 ALOGD("Gestures: FREEFORM "
6140 "new mapping for touch id %d -> gesture id %d",
6141 touchId, gestureId);
6142#endif
6143 } else {
6144 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6145#if DEBUG_GESTURES
6146 ALOGD("Gestures: FREEFORM "
6147 "existing mapping for touch id %d -> gesture id %d",
6148 touchId, gestureId);
6149#endif
6150 }
6151 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6152 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6153
6154 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006155 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006156 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6157 * mPointerXZoomScale;
6158 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6159 * mPointerYZoomScale;
6160 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6161
6162 mPointerGesture.currentGestureProperties[i].clear();
6163 mPointerGesture.currentGestureProperties[i].id = gestureId;
6164 mPointerGesture.currentGestureProperties[i].toolType =
6165 AMOTION_EVENT_TOOL_TYPE_FINGER;
6166 mPointerGesture.currentGestureCoords[i].clear();
6167 mPointerGesture.currentGestureCoords[i].setAxisValue(
6168 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6169 mPointerGesture.currentGestureCoords[i].setAxisValue(
6170 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6171 mPointerGesture.currentGestureCoords[i].setAxisValue(
6172 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6173 }
6174
6175 if (mPointerGesture.activeGestureId < 0) {
6176 mPointerGesture.activeGestureId =
6177 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6178#if DEBUG_GESTURES
6179 ALOGD("Gestures: FREEFORM new "
6180 "activeGestureId=%d", mPointerGesture.activeGestureId);
6181#endif
6182 }
6183 }
6184 }
6185
Michael Wright842500e2015-03-13 17:32:02 -07006186 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006187
6188#if DEBUG_GESTURES
6189 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6190 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6191 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6192 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6193 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6194 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6195 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6196 uint32_t id = idBits.clearFirstMarkedBit();
6197 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6198 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6199 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6200 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6201 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6202 id, index, properties.toolType,
6203 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6204 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6205 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6206 }
6207 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6208 uint32_t id = idBits.clearFirstMarkedBit();
6209 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6210 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6211 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6212 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6213 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6214 id, index, properties.toolType,
6215 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6216 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6217 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6218 }
6219#endif
6220 return true;
6221}
6222
6223void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6224 mPointerSimple.currentCoords.clear();
6225 mPointerSimple.currentProperties.clear();
6226
6227 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006228 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6229 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6230 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6231 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6232 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233 mPointerController->setPosition(x, y);
6234
Michael Wright842500e2015-03-13 17:32:02 -07006235 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006236 down = !hovering;
6237
6238 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006239 mPointerSimple.currentCoords.copyFrom(
6240 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006241 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6242 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6243 mPointerSimple.currentProperties.id = 0;
6244 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006245 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006246 } else {
6247 down = false;
6248 hovering = false;
6249 }
6250
6251 dispatchPointerSimple(when, policyFlags, down, hovering);
6252}
6253
6254void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6255 abortPointerSimple(when, policyFlags);
6256}
6257
6258void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6259 mPointerSimple.currentCoords.clear();
6260 mPointerSimple.currentProperties.clear();
6261
6262 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006263 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6264 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6265 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006266 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006267 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6268 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006269 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006270 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006271 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006272 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006273 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006274 * mPointerYMovementScale;
6275
6276 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6277 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6278
6279 mPointerController->move(deltaX, deltaY);
6280 } else {
6281 mPointerVelocityControl.reset();
6282 }
6283
Michael Wright842500e2015-03-13 17:32:02 -07006284 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006285 hovering = !down;
6286
6287 float x, y;
6288 mPointerController->getPosition(&x, &y);
6289 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006290 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006291 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6292 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6293 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6294 hovering ? 0.0f : 1.0f);
6295 mPointerSimple.currentProperties.id = 0;
6296 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006297 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006298 } else {
6299 mPointerVelocityControl.reset();
6300
6301 down = false;
6302 hovering = false;
6303 }
6304
6305 dispatchPointerSimple(when, policyFlags, down, hovering);
6306}
6307
6308void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6309 abortPointerSimple(when, policyFlags);
6310
6311 mPointerVelocityControl.reset();
6312}
6313
6314void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6315 bool down, bool hovering) {
6316 int32_t metaState = getContext()->getGlobalMetaState();
6317
6318 if (mPointerController != NULL) {
6319 if (down || hovering) {
6320 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6321 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006322 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006323 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6324 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6325 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6326 }
6327 }
6328
6329 if (mPointerSimple.down && !down) {
6330 mPointerSimple.down = false;
6331
6332 // Send up.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006333 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006334 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006335 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006336 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6337 mOrientedXPrecision, mOrientedYPrecision,
6338 mPointerSimple.downTime);
6339 getListener()->notifyMotion(&args);
6340 }
6341
6342 if (mPointerSimple.hovering && !hovering) {
6343 mPointerSimple.hovering = false;
6344
6345 // Send hover exit.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006346 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006347 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006348 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006349 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6350 mOrientedXPrecision, mOrientedYPrecision,
6351 mPointerSimple.downTime);
6352 getListener()->notifyMotion(&args);
6353 }
6354
6355 if (down) {
6356 if (!mPointerSimple.down) {
6357 mPointerSimple.down = true;
6358 mPointerSimple.downTime = when;
6359
6360 // Send down.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006361 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006362 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006363 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006364 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6365 mOrientedXPrecision, mOrientedYPrecision,
6366 mPointerSimple.downTime);
6367 getListener()->notifyMotion(&args);
6368 }
6369
6370 // Send move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006371 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006372 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006373 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006374 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6375 mOrientedXPrecision, mOrientedYPrecision,
6376 mPointerSimple.downTime);
6377 getListener()->notifyMotion(&args);
6378 }
6379
6380 if (hovering) {
6381 if (!mPointerSimple.hovering) {
6382 mPointerSimple.hovering = true;
6383
6384 // Send hover enter.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006385 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006386 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006387 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006388 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006389 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6390 mOrientedXPrecision, mOrientedYPrecision,
6391 mPointerSimple.downTime);
6392 getListener()->notifyMotion(&args);
6393 }
6394
6395 // Send hover move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006396 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006397 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006398 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006399 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006400 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6401 mOrientedXPrecision, mOrientedYPrecision,
6402 mPointerSimple.downTime);
6403 getListener()->notifyMotion(&args);
6404 }
6405
Michael Wright842500e2015-03-13 17:32:02 -07006406 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6407 float vscroll = mCurrentRawState.rawVScroll;
6408 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006409 mWheelYVelocityControl.move(when, NULL, &vscroll);
6410 mWheelXVelocityControl.move(when, &hscroll, NULL);
6411
6412 // Send scroll.
6413 PointerCoords pointerCoords;
6414 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6415 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6416 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6417
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006418 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006419 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006420 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006421 1, &mPointerSimple.currentProperties, &pointerCoords,
6422 mOrientedXPrecision, mOrientedYPrecision,
6423 mPointerSimple.downTime);
6424 getListener()->notifyMotion(&args);
6425 }
6426
6427 // Save state.
6428 if (down || hovering) {
6429 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6430 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6431 } else {
6432 mPointerSimple.reset();
6433 }
6434}
6435
6436void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6437 mPointerSimple.currentCoords.clear();
6438 mPointerSimple.currentProperties.clear();
6439
6440 dispatchPointerSimple(when, policyFlags, false, false);
6441}
6442
6443void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006444 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006445 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006446 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006447 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6448 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006449 PointerCoords pointerCoords[MAX_POINTERS];
6450 PointerProperties pointerProperties[MAX_POINTERS];
6451 uint32_t pointerCount = 0;
6452 while (!idBits.isEmpty()) {
6453 uint32_t id = idBits.clearFirstMarkedBit();
6454 uint32_t index = idToIndex[id];
6455 pointerProperties[pointerCount].copyFrom(properties[index]);
6456 pointerCoords[pointerCount].copyFrom(coords[index]);
6457
6458 if (changedId >= 0 && id == uint32_t(changedId)) {
6459 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6460 }
6461
6462 pointerCount += 1;
6463 }
6464
6465 ALOG_ASSERT(pointerCount != 0);
6466
6467 if (changedId >= 0 && pointerCount == 1) {
6468 // Replace initial down and final up action.
6469 // We can compare the action without masking off the changed pointer index
6470 // because we know the index is 0.
6471 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6472 action = AMOTION_EVENT_ACTION_DOWN;
6473 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6474 action = AMOTION_EVENT_ACTION_UP;
6475 } else {
6476 // Can't happen.
6477 ALOG_ASSERT(false);
6478 }
6479 }
6480
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006481 NotifyMotionArgs args(when, getDeviceId(), source, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006482 action, actionButton, flags, metaState, buttonState, edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006483 deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006484 xPrecision, yPrecision, downTime);
6485 getListener()->notifyMotion(&args);
6486}
6487
6488bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6489 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6490 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6491 BitSet32 idBits) const {
6492 bool changed = false;
6493 while (!idBits.isEmpty()) {
6494 uint32_t id = idBits.clearFirstMarkedBit();
6495 uint32_t inIndex = inIdToIndex[id];
6496 uint32_t outIndex = outIdToIndex[id];
6497
6498 const PointerProperties& curInProperties = inProperties[inIndex];
6499 const PointerCoords& curInCoords = inCoords[inIndex];
6500 PointerProperties& curOutProperties = outProperties[outIndex];
6501 PointerCoords& curOutCoords = outCoords[outIndex];
6502
6503 if (curInProperties != curOutProperties) {
6504 curOutProperties.copyFrom(curInProperties);
6505 changed = true;
6506 }
6507
6508 if (curInCoords != curOutCoords) {
6509 curOutCoords.copyFrom(curInCoords);
6510 changed = true;
6511 }
6512 }
6513 return changed;
6514}
6515
6516void TouchInputMapper::fadePointer() {
6517 if (mPointerController != NULL) {
6518 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6519 }
6520}
6521
Jeff Brownc9aa6282015-02-11 19:03:28 -08006522void TouchInputMapper::cancelTouch(nsecs_t when) {
6523 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006524 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006525}
6526
Michael Wrightd02c5b62014-02-10 15:10:22 -08006527bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6528 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6529 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6530}
6531
6532const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6533 int32_t x, int32_t y) {
6534 size_t numVirtualKeys = mVirtualKeys.size();
6535 for (size_t i = 0; i < numVirtualKeys; i++) {
6536 const VirtualKey& virtualKey = mVirtualKeys[i];
6537
6538#if DEBUG_VIRTUAL_KEYS
6539 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6540 "left=%d, top=%d, right=%d, bottom=%d",
6541 x, y,
6542 virtualKey.keyCode, virtualKey.scanCode,
6543 virtualKey.hitLeft, virtualKey.hitTop,
6544 virtualKey.hitRight, virtualKey.hitBottom);
6545#endif
6546
6547 if (virtualKey.isHit(x, y)) {
6548 return & virtualKey;
6549 }
6550 }
6551
6552 return NULL;
6553}
6554
Michael Wright842500e2015-03-13 17:32:02 -07006555void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6556 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6557 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006558
Michael Wright842500e2015-03-13 17:32:02 -07006559 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006560
6561 if (currentPointerCount == 0) {
6562 // No pointers to assign.
6563 return;
6564 }
6565
6566 if (lastPointerCount == 0) {
6567 // All pointers are new.
6568 for (uint32_t i = 0; i < currentPointerCount; i++) {
6569 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006570 current->rawPointerData.pointers[i].id = id;
6571 current->rawPointerData.idToIndex[id] = i;
6572 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006573 }
6574 return;
6575 }
6576
6577 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006578 && current->rawPointerData.pointers[0].toolType
6579 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006580 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006581 uint32_t id = last->rawPointerData.pointers[0].id;
6582 current->rawPointerData.pointers[0].id = id;
6583 current->rawPointerData.idToIndex[id] = 0;
6584 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006585 return;
6586 }
6587
6588 // General case.
6589 // We build a heap of squared euclidean distances between current and last pointers
6590 // associated with the current and last pointer indices. Then, we find the best
6591 // match (by distance) for each current pointer.
6592 // The pointers must have the same tool type but it is possible for them to
6593 // transition from hovering to touching or vice-versa while retaining the same id.
6594 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6595
6596 uint32_t heapSize = 0;
6597 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6598 currentPointerIndex++) {
6599 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6600 lastPointerIndex++) {
6601 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006602 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006603 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006604 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006605 if (currentPointer.toolType == lastPointer.toolType) {
6606 int64_t deltaX = currentPointer.x - lastPointer.x;
6607 int64_t deltaY = currentPointer.y - lastPointer.y;
6608
6609 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6610
6611 // Insert new element into the heap (sift up).
6612 heap[heapSize].currentPointerIndex = currentPointerIndex;
6613 heap[heapSize].lastPointerIndex = lastPointerIndex;
6614 heap[heapSize].distance = distance;
6615 heapSize += 1;
6616 }
6617 }
6618 }
6619
6620 // Heapify
6621 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6622 startIndex -= 1;
6623 for (uint32_t parentIndex = startIndex; ;) {
6624 uint32_t childIndex = parentIndex * 2 + 1;
6625 if (childIndex >= heapSize) {
6626 break;
6627 }
6628
6629 if (childIndex + 1 < heapSize
6630 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6631 childIndex += 1;
6632 }
6633
6634 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6635 break;
6636 }
6637
6638 swap(heap[parentIndex], heap[childIndex]);
6639 parentIndex = childIndex;
6640 }
6641 }
6642
6643#if DEBUG_POINTER_ASSIGNMENT
6644 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6645 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006646 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006647 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6648 heap[i].distance);
6649 }
6650#endif
6651
6652 // Pull matches out by increasing order of distance.
6653 // To avoid reassigning pointers that have already been matched, the loop keeps track
6654 // of which last and current pointers have been matched using the matchedXXXBits variables.
6655 // It also tracks the used pointer id bits.
6656 BitSet32 matchedLastBits(0);
6657 BitSet32 matchedCurrentBits(0);
6658 BitSet32 usedIdBits(0);
6659 bool first = true;
6660 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6661 while (heapSize > 0) {
6662 if (first) {
6663 // The first time through the loop, we just consume the root element of
6664 // the heap (the one with smallest distance).
6665 first = false;
6666 } else {
6667 // Previous iterations consumed the root element of the heap.
6668 // Pop root element off of the heap (sift down).
6669 heap[0] = heap[heapSize];
6670 for (uint32_t parentIndex = 0; ;) {
6671 uint32_t childIndex = parentIndex * 2 + 1;
6672 if (childIndex >= heapSize) {
6673 break;
6674 }
6675
6676 if (childIndex + 1 < heapSize
6677 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6678 childIndex += 1;
6679 }
6680
6681 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6682 break;
6683 }
6684
6685 swap(heap[parentIndex], heap[childIndex]);
6686 parentIndex = childIndex;
6687 }
6688
6689#if DEBUG_POINTER_ASSIGNMENT
6690 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6691 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006692 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006693 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6694 heap[i].distance);
6695 }
6696#endif
6697 }
6698
6699 heapSize -= 1;
6700
6701 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6702 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6703
6704 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6705 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6706
6707 matchedCurrentBits.markBit(currentPointerIndex);
6708 matchedLastBits.markBit(lastPointerIndex);
6709
Michael Wright842500e2015-03-13 17:32:02 -07006710 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6711 current->rawPointerData.pointers[currentPointerIndex].id = id;
6712 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6713 current->rawPointerData.markIdBit(id,
6714 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006715 usedIdBits.markBit(id);
6716
6717#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006718 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6719 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006720 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6721#endif
6722 break;
6723 }
6724 }
6725
6726 // Assign fresh ids to pointers that were not matched in the process.
6727 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6728 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6729 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6730
Michael Wright842500e2015-03-13 17:32:02 -07006731 current->rawPointerData.pointers[currentPointerIndex].id = id;
6732 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6733 current->rawPointerData.markIdBit(id,
6734 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006735
6736#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006737 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006738#endif
6739 }
6740}
6741
6742int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6743 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6744 return AKEY_STATE_VIRTUAL;
6745 }
6746
6747 size_t numVirtualKeys = mVirtualKeys.size();
6748 for (size_t i = 0; i < numVirtualKeys; i++) {
6749 const VirtualKey& virtualKey = mVirtualKeys[i];
6750 if (virtualKey.keyCode == keyCode) {
6751 return AKEY_STATE_UP;
6752 }
6753 }
6754
6755 return AKEY_STATE_UNKNOWN;
6756}
6757
6758int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6759 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6760 return AKEY_STATE_VIRTUAL;
6761 }
6762
6763 size_t numVirtualKeys = mVirtualKeys.size();
6764 for (size_t i = 0; i < numVirtualKeys; i++) {
6765 const VirtualKey& virtualKey = mVirtualKeys[i];
6766 if (virtualKey.scanCode == scanCode) {
6767 return AKEY_STATE_UP;
6768 }
6769 }
6770
6771 return AKEY_STATE_UNKNOWN;
6772}
6773
6774bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6775 const int32_t* keyCodes, uint8_t* outFlags) {
6776 size_t numVirtualKeys = mVirtualKeys.size();
6777 for (size_t i = 0; i < numVirtualKeys; i++) {
6778 const VirtualKey& virtualKey = mVirtualKeys[i];
6779
6780 for (size_t i = 0; i < numCodes; i++) {
6781 if (virtualKey.keyCode == keyCodes[i]) {
6782 outFlags[i] = 1;
6783 }
6784 }
6785 }
6786
6787 return true;
6788}
6789
6790
6791// --- SingleTouchInputMapper ---
6792
6793SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6794 TouchInputMapper(device) {
6795}
6796
6797SingleTouchInputMapper::~SingleTouchInputMapper() {
6798}
6799
6800void SingleTouchInputMapper::reset(nsecs_t when) {
6801 mSingleTouchMotionAccumulator.reset(getDevice());
6802
6803 TouchInputMapper::reset(when);
6804}
6805
6806void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6807 TouchInputMapper::process(rawEvent);
6808
6809 mSingleTouchMotionAccumulator.process(rawEvent);
6810}
6811
Michael Wright842500e2015-03-13 17:32:02 -07006812void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006813 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006814 outState->rawPointerData.pointerCount = 1;
6815 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006816
6817 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6818 && (mTouchButtonAccumulator.isHovering()
6819 || (mRawPointerAxes.pressure.valid
6820 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006821 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006822
Michael Wright842500e2015-03-13 17:32:02 -07006823 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006824 outPointer.id = 0;
6825 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6826 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6827 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6828 outPointer.touchMajor = 0;
6829 outPointer.touchMinor = 0;
6830 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6831 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6832 outPointer.orientation = 0;
6833 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6834 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6835 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6836 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6837 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6838 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6839 }
6840 outPointer.isHovering = isHovering;
6841 }
6842}
6843
6844void SingleTouchInputMapper::configureRawPointerAxes() {
6845 TouchInputMapper::configureRawPointerAxes();
6846
6847 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6848 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6849 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6850 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6851 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6852 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6853 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6854}
6855
6856bool SingleTouchInputMapper::hasStylus() const {
6857 return mTouchButtonAccumulator.hasStylus();
6858}
6859
6860
6861// --- MultiTouchInputMapper ---
6862
6863MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6864 TouchInputMapper(device) {
6865}
6866
6867MultiTouchInputMapper::~MultiTouchInputMapper() {
6868}
6869
6870void MultiTouchInputMapper::reset(nsecs_t when) {
6871 mMultiTouchMotionAccumulator.reset(getDevice());
6872
6873 mPointerIdBits.clear();
6874
6875 TouchInputMapper::reset(when);
6876}
6877
6878void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6879 TouchInputMapper::process(rawEvent);
6880
6881 mMultiTouchMotionAccumulator.process(rawEvent);
6882}
6883
Michael Wright842500e2015-03-13 17:32:02 -07006884void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006885 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6886 size_t outCount = 0;
6887 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006888 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006889
6890 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6891 const MultiTouchMotionAccumulator::Slot* inSlot =
6892 mMultiTouchMotionAccumulator.getSlot(inIndex);
6893 if (!inSlot->isInUse()) {
6894 continue;
6895 }
6896
6897 if (outCount >= MAX_POINTERS) {
6898#if DEBUG_POINTERS
6899 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6900 "ignoring the rest.",
6901 getDeviceName().string(), MAX_POINTERS);
6902#endif
6903 break; // too many fingers!
6904 }
6905
Michael Wright842500e2015-03-13 17:32:02 -07006906 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006907 outPointer.x = inSlot->getX();
6908 outPointer.y = inSlot->getY();
6909 outPointer.pressure = inSlot->getPressure();
6910 outPointer.touchMajor = inSlot->getTouchMajor();
6911 outPointer.touchMinor = inSlot->getTouchMinor();
6912 outPointer.toolMajor = inSlot->getToolMajor();
6913 outPointer.toolMinor = inSlot->getToolMinor();
6914 outPointer.orientation = inSlot->getOrientation();
6915 outPointer.distance = inSlot->getDistance();
6916 outPointer.tiltX = 0;
6917 outPointer.tiltY = 0;
6918
6919 outPointer.toolType = inSlot->getToolType();
6920 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6921 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6922 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6923 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6924 }
6925 }
6926
6927 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6928 && (mTouchButtonAccumulator.isHovering()
6929 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6930 outPointer.isHovering = isHovering;
6931
6932 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006933 if (mHavePointerIds) {
6934 int32_t trackingId = inSlot->getTrackingId();
6935 int32_t id = -1;
6936 if (trackingId >= 0) {
6937 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6938 uint32_t n = idBits.clearFirstMarkedBit();
6939 if (mPointerTrackingIdMap[n] == trackingId) {
6940 id = n;
6941 }
6942 }
6943
6944 if (id < 0 && !mPointerIdBits.isFull()) {
6945 id = mPointerIdBits.markFirstUnmarkedBit();
6946 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006947 }
Michael Wright842500e2015-03-13 17:32:02 -07006948 }
gaoshang1a632de2016-08-24 10:23:50 +08006949 if (id < 0) {
6950 mHavePointerIds = false;
6951 outState->rawPointerData.clearIdBits();
6952 newPointerIdBits.clear();
6953 } else {
6954 outPointer.id = id;
6955 outState->rawPointerData.idToIndex[id] = outCount;
6956 outState->rawPointerData.markIdBit(id, isHovering);
6957 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006958 }
Michael Wright842500e2015-03-13 17:32:02 -07006959 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006960 outCount += 1;
6961 }
6962
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006963 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006964 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006965 mPointerIdBits = newPointerIdBits;
6966
6967 mMultiTouchMotionAccumulator.finishSync();
6968}
6969
6970void MultiTouchInputMapper::configureRawPointerAxes() {
6971 TouchInputMapper::configureRawPointerAxes();
6972
6973 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6974 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6975 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6976 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6977 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6978 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6979 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6980 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6981 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6982 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6983 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6984
6985 if (mRawPointerAxes.trackingId.valid
6986 && mRawPointerAxes.slot.valid
6987 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6988 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6989 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006990 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6991 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006992 getDeviceName().string(), slotCount, MAX_SLOTS);
6993 slotCount = MAX_SLOTS;
6994 }
6995 mMultiTouchMotionAccumulator.configure(getDevice(),
6996 slotCount, true /*usingSlotsProtocol*/);
6997 } else {
6998 mMultiTouchMotionAccumulator.configure(getDevice(),
6999 MAX_POINTERS, false /*usingSlotsProtocol*/);
7000 }
7001}
7002
7003bool MultiTouchInputMapper::hasStylus() const {
7004 return mMultiTouchMotionAccumulator.hasStylus()
7005 || mTouchButtonAccumulator.hasStylus();
7006}
7007
Michael Wright842500e2015-03-13 17:32:02 -07007008// --- ExternalStylusInputMapper
7009
7010ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7011 InputMapper(device) {
7012
7013}
7014
7015uint32_t ExternalStylusInputMapper::getSources() {
7016 return AINPUT_SOURCE_STYLUS;
7017}
7018
7019void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7020 InputMapper::populateDeviceInfo(info);
7021 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7022 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7023}
7024
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007025void ExternalStylusInputMapper::dump(std::string& dump) {
7026 dump += INDENT2 "External Stylus Input Mapper:\n";
7027 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007028 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007029 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007030 dumpStylusState(dump, mStylusState);
7031}
7032
7033void ExternalStylusInputMapper::configure(nsecs_t when,
7034 const InputReaderConfiguration* config, uint32_t changes) {
7035 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7036 mTouchButtonAccumulator.configure(getDevice());
7037}
7038
7039void ExternalStylusInputMapper::reset(nsecs_t when) {
7040 InputDevice* device = getDevice();
7041 mSingleTouchMotionAccumulator.reset(device);
7042 mTouchButtonAccumulator.reset(device);
7043 InputMapper::reset(when);
7044}
7045
7046void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7047 mSingleTouchMotionAccumulator.process(rawEvent);
7048 mTouchButtonAccumulator.process(rawEvent);
7049
7050 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7051 sync(rawEvent->when);
7052 }
7053}
7054
7055void ExternalStylusInputMapper::sync(nsecs_t when) {
7056 mStylusState.clear();
7057
7058 mStylusState.when = when;
7059
Michael Wright45ccacf2015-04-21 19:01:58 +01007060 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7061 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7062 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7063 }
7064
Michael Wright842500e2015-03-13 17:32:02 -07007065 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7066 if (mRawPressureAxis.valid) {
7067 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7068 } else if (mTouchButtonAccumulator.isToolActive()) {
7069 mStylusState.pressure = 1.0f;
7070 } else {
7071 mStylusState.pressure = 0.0f;
7072 }
7073
7074 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007075
7076 mContext->dispatchExternalStylusState(mStylusState);
7077}
7078
Michael Wrightd02c5b62014-02-10 15:10:22 -08007079
7080// --- JoystickInputMapper ---
7081
7082JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7083 InputMapper(device) {
7084}
7085
7086JoystickInputMapper::~JoystickInputMapper() {
7087}
7088
7089uint32_t JoystickInputMapper::getSources() {
7090 return AINPUT_SOURCE_JOYSTICK;
7091}
7092
7093void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7094 InputMapper::populateDeviceInfo(info);
7095
7096 for (size_t i = 0; i < mAxes.size(); i++) {
7097 const Axis& axis = mAxes.valueAt(i);
7098 addMotionRange(axis.axisInfo.axis, axis, info);
7099
7100 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7101 addMotionRange(axis.axisInfo.highAxis, axis, info);
7102
7103 }
7104 }
7105}
7106
7107void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7108 InputDeviceInfo* info) {
7109 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7110 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7111 /* In order to ease the transition for developers from using the old axes
7112 * to the newer, more semantically correct axes, we'll continue to register
7113 * the old axes as duplicates of their corresponding new ones. */
7114 int32_t compatAxis = getCompatAxis(axisId);
7115 if (compatAxis >= 0) {
7116 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7117 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7118 }
7119}
7120
7121/* A mapping from axes the joystick actually has to the axes that should be
7122 * artificially created for compatibility purposes.
7123 * Returns -1 if no compatibility axis is needed. */
7124int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7125 switch(axis) {
7126 case AMOTION_EVENT_AXIS_LTRIGGER:
7127 return AMOTION_EVENT_AXIS_BRAKE;
7128 case AMOTION_EVENT_AXIS_RTRIGGER:
7129 return AMOTION_EVENT_AXIS_GAS;
7130 }
7131 return -1;
7132}
7133
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007134void JoystickInputMapper::dump(std::string& dump) {
7135 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007136
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007137 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007138 size_t numAxes = mAxes.size();
7139 for (size_t i = 0; i < numAxes; i++) {
7140 const Axis& axis = mAxes.valueAt(i);
7141 const char* label = getAxisLabel(axis.axisInfo.axis);
7142 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007143 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007144 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007145 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007146 }
7147 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7148 label = getAxisLabel(axis.axisInfo.highAxis);
7149 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007150 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007151 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007152 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007153 axis.axisInfo.splitValue);
7154 }
7155 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007156 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007157 }
7158
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007159 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 -08007160 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007161 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007162 "highScale=%0.5f, highOffset=%0.5f\n",
7163 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007164 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007165 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7166 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7167 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7168 }
7169}
7170
7171void JoystickInputMapper::configure(nsecs_t when,
7172 const InputReaderConfiguration* config, uint32_t changes) {
7173 InputMapper::configure(when, config, changes);
7174
7175 if (!changes) { // first time only
7176 // Collect all axes.
7177 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7178 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7179 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7180 continue; // axis must be claimed by a different device
7181 }
7182
7183 RawAbsoluteAxisInfo rawAxisInfo;
7184 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7185 if (rawAxisInfo.valid) {
7186 // Map axis.
7187 AxisInfo axisInfo;
7188 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7189 if (!explicitlyMapped) {
7190 // Axis is not explicitly mapped, will choose a generic axis later.
7191 axisInfo.mode = AxisInfo::MODE_NORMAL;
7192 axisInfo.axis = -1;
7193 }
7194
7195 // Apply flat override.
7196 int32_t rawFlat = axisInfo.flatOverride < 0
7197 ? rawAxisInfo.flat : axisInfo.flatOverride;
7198
7199 // Calculate scaling factors and limits.
7200 Axis axis;
7201 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7202 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7203 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7204 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7205 scale, 0.0f, highScale, 0.0f,
7206 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7207 rawAxisInfo.resolution * scale);
7208 } else if (isCenteredAxis(axisInfo.axis)) {
7209 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7210 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7211 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7212 scale, offset, scale, offset,
7213 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7214 rawAxisInfo.resolution * scale);
7215 } else {
7216 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7217 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7218 scale, 0.0f, scale, 0.0f,
7219 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7220 rawAxisInfo.resolution * scale);
7221 }
7222
7223 // To eliminate noise while the joystick is at rest, filter out small variations
7224 // in axis values up front.
7225 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7226
7227 mAxes.add(abs, axis);
7228 }
7229 }
7230
7231 // If there are too many axes, start dropping them.
7232 // Prefer to keep explicitly mapped axes.
7233 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007234 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007235 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7236 pruneAxes(true);
7237 pruneAxes(false);
7238 }
7239
7240 // Assign generic axis ids to remaining axes.
7241 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7242 size_t numAxes = mAxes.size();
7243 for (size_t i = 0; i < numAxes; i++) {
7244 Axis& axis = mAxes.editValueAt(i);
7245 if (axis.axisInfo.axis < 0) {
7246 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7247 && haveAxis(nextGenericAxisId)) {
7248 nextGenericAxisId += 1;
7249 }
7250
7251 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7252 axis.axisInfo.axis = nextGenericAxisId;
7253 nextGenericAxisId += 1;
7254 } else {
7255 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7256 "have already been assigned to other axes.",
7257 getDeviceName().string(), mAxes.keyAt(i));
7258 mAxes.removeItemsAt(i--);
7259 numAxes -= 1;
7260 }
7261 }
7262 }
7263 }
7264}
7265
7266bool JoystickInputMapper::haveAxis(int32_t axisId) {
7267 size_t numAxes = mAxes.size();
7268 for (size_t i = 0; i < numAxes; i++) {
7269 const Axis& axis = mAxes.valueAt(i);
7270 if (axis.axisInfo.axis == axisId
7271 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7272 && axis.axisInfo.highAxis == axisId)) {
7273 return true;
7274 }
7275 }
7276 return false;
7277}
7278
7279void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7280 size_t i = mAxes.size();
7281 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7282 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7283 continue;
7284 }
7285 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7286 getDeviceName().string(), mAxes.keyAt(i));
7287 mAxes.removeItemsAt(i);
7288 }
7289}
7290
7291bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7292 switch (axis) {
7293 case AMOTION_EVENT_AXIS_X:
7294 case AMOTION_EVENT_AXIS_Y:
7295 case AMOTION_EVENT_AXIS_Z:
7296 case AMOTION_EVENT_AXIS_RX:
7297 case AMOTION_EVENT_AXIS_RY:
7298 case AMOTION_EVENT_AXIS_RZ:
7299 case AMOTION_EVENT_AXIS_HAT_X:
7300 case AMOTION_EVENT_AXIS_HAT_Y:
7301 case AMOTION_EVENT_AXIS_ORIENTATION:
7302 case AMOTION_EVENT_AXIS_RUDDER:
7303 case AMOTION_EVENT_AXIS_WHEEL:
7304 return true;
7305 default:
7306 return false;
7307 }
7308}
7309
7310void JoystickInputMapper::reset(nsecs_t when) {
7311 // Recenter all axes.
7312 size_t numAxes = mAxes.size();
7313 for (size_t i = 0; i < numAxes; i++) {
7314 Axis& axis = mAxes.editValueAt(i);
7315 axis.resetValue();
7316 }
7317
7318 InputMapper::reset(when);
7319}
7320
7321void JoystickInputMapper::process(const RawEvent* rawEvent) {
7322 switch (rawEvent->type) {
7323 case EV_ABS: {
7324 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7325 if (index >= 0) {
7326 Axis& axis = mAxes.editValueAt(index);
7327 float newValue, highNewValue;
7328 switch (axis.axisInfo.mode) {
7329 case AxisInfo::MODE_INVERT:
7330 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7331 * axis.scale + axis.offset;
7332 highNewValue = 0.0f;
7333 break;
7334 case AxisInfo::MODE_SPLIT:
7335 if (rawEvent->value < axis.axisInfo.splitValue) {
7336 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7337 * axis.scale + axis.offset;
7338 highNewValue = 0.0f;
7339 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7340 newValue = 0.0f;
7341 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7342 * axis.highScale + axis.highOffset;
7343 } else {
7344 newValue = 0.0f;
7345 highNewValue = 0.0f;
7346 }
7347 break;
7348 default:
7349 newValue = rawEvent->value * axis.scale + axis.offset;
7350 highNewValue = 0.0f;
7351 break;
7352 }
7353 axis.newValue = newValue;
7354 axis.highNewValue = highNewValue;
7355 }
7356 break;
7357 }
7358
7359 case EV_SYN:
7360 switch (rawEvent->code) {
7361 case SYN_REPORT:
7362 sync(rawEvent->when, false /*force*/);
7363 break;
7364 }
7365 break;
7366 }
7367}
7368
7369void JoystickInputMapper::sync(nsecs_t when, bool force) {
7370 if (!filterAxes(force)) {
7371 return;
7372 }
7373
7374 int32_t metaState = mContext->getGlobalMetaState();
7375 int32_t buttonState = 0;
7376
7377 PointerProperties pointerProperties;
7378 pointerProperties.clear();
7379 pointerProperties.id = 0;
7380 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7381
7382 PointerCoords pointerCoords;
7383 pointerCoords.clear();
7384
7385 size_t numAxes = mAxes.size();
7386 for (size_t i = 0; i < numAxes; i++) {
7387 const Axis& axis = mAxes.valueAt(i);
7388 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7389 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7390 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7391 axis.highCurrentValue);
7392 }
7393 }
7394
7395 // Moving a joystick axis should not wake the device because joysticks can
7396 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7397 // button will likely wake the device.
7398 // TODO: Use the input device configuration to control this behavior more finely.
7399 uint32_t policyFlags = 0;
7400
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007401 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE,
7402 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007403 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007404 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007405 0, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007406 getListener()->notifyMotion(&args);
7407}
7408
7409void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7410 int32_t axis, float value) {
7411 pointerCoords->setAxisValue(axis, value);
7412 /* In order to ease the transition for developers from using the old axes
7413 * to the newer, more semantically correct axes, we'll continue to produce
7414 * values for the old axes as mirrors of the value of their corresponding
7415 * new axes. */
7416 int32_t compatAxis = getCompatAxis(axis);
7417 if (compatAxis >= 0) {
7418 pointerCoords->setAxisValue(compatAxis, value);
7419 }
7420}
7421
7422bool JoystickInputMapper::filterAxes(bool force) {
7423 bool atLeastOneSignificantChange = force;
7424 size_t numAxes = mAxes.size();
7425 for (size_t i = 0; i < numAxes; i++) {
7426 Axis& axis = mAxes.editValueAt(i);
7427 if (force || hasValueChangedSignificantly(axis.filter,
7428 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7429 axis.currentValue = axis.newValue;
7430 atLeastOneSignificantChange = true;
7431 }
7432 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7433 if (force || hasValueChangedSignificantly(axis.filter,
7434 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7435 axis.highCurrentValue = axis.highNewValue;
7436 atLeastOneSignificantChange = true;
7437 }
7438 }
7439 }
7440 return atLeastOneSignificantChange;
7441}
7442
7443bool JoystickInputMapper::hasValueChangedSignificantly(
7444 float filter, float newValue, float currentValue, float min, float max) {
7445 if (newValue != currentValue) {
7446 // Filter out small changes in value unless the value is converging on the axis
7447 // bounds or center point. This is intended to reduce the amount of information
7448 // sent to applications by particularly noisy joysticks (such as PS3).
7449 if (fabs(newValue - currentValue) > filter
7450 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7451 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7452 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7453 return true;
7454 }
7455 }
7456 return false;
7457}
7458
7459bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7460 float filter, float newValue, float currentValue, float thresholdValue) {
7461 float newDistance = fabs(newValue - thresholdValue);
7462 if (newDistance < filter) {
7463 float oldDistance = fabs(currentValue - thresholdValue);
7464 if (newDistance < oldDistance) {
7465 return true;
7466 }
7467 }
7468 return false;
7469}
7470
7471} // namespace android