blob: 4c4786fea832127afa96ad599e5565041834a607 [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)) {
2282 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2283 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002284 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 mOrientation = v.orientation;
2286 } else {
2287 mOrientation = DISPLAY_ORIENTATION_0;
2288 }
2289 } else {
2290 mOrientation = DISPLAY_ORIENTATION_0;
2291 }
2292 }
2293}
2294
Ivan Podogovb9afef32017-02-13 15:34:32 +00002295static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2296 int32_t mapped = 0;
2297 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2298 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2299 if (stemKeyRotationMap[i][0] == keyCode) {
2300 stemKeyRotationMap[i][1] = mapped;
2301 return;
2302 }
2303 }
2304 }
2305}
2306
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307void KeyboardInputMapper::configureParameters() {
2308 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002309 const PropertyMap& config = getDevice()->getConfiguration();
2310 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 mParameters.orientationAware);
2312
2313 mParameters.hasAssociatedDisplay = false;
2314 if (mParameters.orientationAware) {
2315 mParameters.hasAssociatedDisplay = true;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002316
2317 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2318 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2319 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2320 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002322
2323 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002324 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002325 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326}
2327
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002328void KeyboardInputMapper::dumpParameters(std::string& dump) {
2329 dump += INDENT3 "Parameters:\n";
2330 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 toString(mParameters.hasAssociatedDisplay));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002332 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002334 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002335 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336}
2337
2338void KeyboardInputMapper::reset(nsecs_t when) {
2339 mMetaState = AMETA_NONE;
2340 mDownTime = 0;
2341 mKeyDowns.clear();
2342 mCurrentHidUsage = 0;
2343
2344 resetLedState();
2345
2346 InputMapper::reset(when);
2347}
2348
2349void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2350 switch (rawEvent->type) {
2351 case EV_KEY: {
2352 int32_t scanCode = rawEvent->code;
2353 int32_t usageCode = mCurrentHidUsage;
2354 mCurrentHidUsage = 0;
2355
2356 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002357 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 }
2359 break;
2360 }
2361 case EV_MSC: {
2362 if (rawEvent->code == MSC_SCAN) {
2363 mCurrentHidUsage = rawEvent->value;
2364 }
2365 break;
2366 }
2367 case EV_SYN: {
2368 if (rawEvent->code == SYN_REPORT) {
2369 mCurrentHidUsage = 0;
2370 }
2371 }
2372 }
2373}
2374
2375bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2376 return scanCode < BTN_MOUSE
2377 || scanCode >= KEY_OK
2378 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2379 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2380}
2381
Michael Wright58ba9882017-07-26 16:19:11 +01002382bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2383 switch (keyCode) {
2384 case AKEYCODE_MEDIA_PLAY:
2385 case AKEYCODE_MEDIA_PAUSE:
2386 case AKEYCODE_MEDIA_PLAY_PAUSE:
2387 case AKEYCODE_MUTE:
2388 case AKEYCODE_HEADSETHOOK:
2389 case AKEYCODE_MEDIA_STOP:
2390 case AKEYCODE_MEDIA_NEXT:
2391 case AKEYCODE_MEDIA_PREVIOUS:
2392 case AKEYCODE_MEDIA_REWIND:
2393 case AKEYCODE_MEDIA_RECORD:
2394 case AKEYCODE_MEDIA_FAST_FORWARD:
2395 case AKEYCODE_MEDIA_SKIP_FORWARD:
2396 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2397 case AKEYCODE_MEDIA_STEP_FORWARD:
2398 case AKEYCODE_MEDIA_STEP_BACKWARD:
2399 case AKEYCODE_MEDIA_AUDIO_TRACK:
2400 case AKEYCODE_VOLUME_UP:
2401 case AKEYCODE_VOLUME_DOWN:
2402 case AKEYCODE_VOLUME_MUTE:
2403 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2404 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2405 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2406 return true;
2407 }
2408 return false;
2409}
2410
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002411void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2412 int32_t usageCode) {
2413 int32_t keyCode;
2414 int32_t keyMetaState;
2415 uint32_t policyFlags;
2416
2417 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2418 &keyCode, &keyMetaState, &policyFlags)) {
2419 keyCode = AKEYCODE_UNKNOWN;
2420 keyMetaState = mMetaState;
2421 policyFlags = 0;
2422 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423
2424 if (down) {
2425 // Rotate key codes according to orientation if needed.
2426 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2427 keyCode = rotateKeyCode(keyCode, mOrientation);
2428 }
2429
2430 // Add key down.
2431 ssize_t keyDownIndex = findKeyDown(scanCode);
2432 if (keyDownIndex >= 0) {
2433 // key repeat, be sure to use same keycode as before in case of rotation
2434 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2435 } else {
2436 // key down
2437 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2438 && mContext->shouldDropVirtualKey(when,
2439 getDevice(), keyCode, scanCode)) {
2440 return;
2441 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002442 if (policyFlags & POLICY_FLAG_GESTURE) {
2443 mDevice->cancelTouch(when);
2444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445
2446 mKeyDowns.push();
2447 KeyDown& keyDown = mKeyDowns.editTop();
2448 keyDown.keyCode = keyCode;
2449 keyDown.scanCode = scanCode;
2450 }
2451
2452 mDownTime = when;
2453 } else {
2454 // Remove key down.
2455 ssize_t keyDownIndex = findKeyDown(scanCode);
2456 if (keyDownIndex >= 0) {
2457 // key up, be sure to use same keycode as before in case of rotation
2458 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2459 mKeyDowns.removeAt(size_t(keyDownIndex));
2460 } else {
2461 // key was not actually down
2462 ALOGI("Dropping key up from device %s because the key was not down. "
2463 "keyCode=%d, scanCode=%d",
2464 getDeviceName().string(), keyCode, scanCode);
2465 return;
2466 }
2467 }
2468
Andrii Kulian763a3a42016-03-08 10:46:16 -08002469 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002470 // If global meta state changed send it along with the key.
2471 // If it has not changed then we'll use what keymap gave us,
2472 // since key replacement logic might temporarily reset a few
2473 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002474 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002475 }
2476
2477 nsecs_t downTime = mDownTime;
2478
2479 // Key down on external an keyboard should wake the device.
2480 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2481 // For internal keyboards, the key layout file should specify the policy flags for
2482 // each wake key individually.
2483 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002484 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002485 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002486 }
2487
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002488 if (mParameters.handlesKeyRepeat) {
2489 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2490 }
2491
Michael Wrightd02c5b62014-02-10 15:10:22 -08002492 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2493 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002494 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495 getListener()->notifyKey(&args);
2496}
2497
2498ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2499 size_t n = mKeyDowns.size();
2500 for (size_t i = 0; i < n; i++) {
2501 if (mKeyDowns[i].scanCode == scanCode) {
2502 return i;
2503 }
2504 }
2505 return -1;
2506}
2507
2508int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2509 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2510}
2511
2512int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2513 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2514}
2515
2516bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2517 const int32_t* keyCodes, uint8_t* outFlags) {
2518 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2519}
2520
2521int32_t KeyboardInputMapper::getMetaState() {
2522 return mMetaState;
2523}
2524
Andrii Kulian763a3a42016-03-08 10:46:16 -08002525void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2526 updateMetaStateIfNeeded(keyCode, false);
2527}
2528
2529bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2530 int32_t oldMetaState = mMetaState;
2531 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2532 bool metaStateChanged = oldMetaState != newMetaState;
2533 if (metaStateChanged) {
2534 mMetaState = newMetaState;
2535 updateLedState(false);
2536
2537 getContext()->updateGlobalMetaState();
2538 }
2539
2540 return metaStateChanged;
2541}
2542
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543void KeyboardInputMapper::resetLedState() {
2544 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2545 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2546 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2547
2548 updateLedState(true);
2549}
2550
2551void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2552 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2553 ledState.on = false;
2554}
2555
2556void KeyboardInputMapper::updateLedState(bool reset) {
2557 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2558 AMETA_CAPS_LOCK_ON, reset);
2559 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2560 AMETA_NUM_LOCK_ON, reset);
2561 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2562 AMETA_SCROLL_LOCK_ON, reset);
2563}
2564
2565void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2566 int32_t led, int32_t modifier, bool reset) {
2567 if (ledState.avail) {
2568 bool desiredState = (mMetaState & modifier) != 0;
2569 if (reset || ledState.on != desiredState) {
2570 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2571 ledState.on = desiredState;
2572 }
2573 }
2574}
2575
2576
2577// --- CursorInputMapper ---
2578
2579CursorInputMapper::CursorInputMapper(InputDevice* device) :
2580 InputMapper(device) {
2581}
2582
2583CursorInputMapper::~CursorInputMapper() {
2584}
2585
2586uint32_t CursorInputMapper::getSources() {
2587 return mSource;
2588}
2589
2590void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2591 InputMapper::populateDeviceInfo(info);
2592
2593 if (mParameters.mode == Parameters::MODE_POINTER) {
2594 float minX, minY, maxX, maxY;
2595 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2596 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2597 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2598 }
2599 } else {
2600 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2601 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2602 }
2603 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2604
2605 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2606 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2607 }
2608 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2609 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2610 }
2611}
2612
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002613void CursorInputMapper::dump(std::string& dump) {
2614 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002615 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002616 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2617 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2618 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2619 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2620 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002622 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002624 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2625 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2626 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2627 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2628 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2629 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630}
2631
2632void CursorInputMapper::configure(nsecs_t when,
2633 const InputReaderConfiguration* config, uint32_t changes) {
2634 InputMapper::configure(when, config, changes);
2635
2636 if (!changes) { // first time only
2637 mCursorScrollAccumulator.configure(getDevice());
2638
2639 // Configure basic parameters.
2640 configureParameters();
2641
2642 // Configure device mode.
2643 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002644 case Parameters::MODE_POINTER_RELATIVE:
2645 // Should not happen during first time configuration.
2646 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2647 mParameters.mode = Parameters::MODE_POINTER;
2648 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 case Parameters::MODE_POINTER:
2650 mSource = AINPUT_SOURCE_MOUSE;
2651 mXPrecision = 1.0f;
2652 mYPrecision = 1.0f;
2653 mXScale = 1.0f;
2654 mYScale = 1.0f;
2655 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2656 break;
2657 case Parameters::MODE_NAVIGATION:
2658 mSource = AINPUT_SOURCE_TRACKBALL;
2659 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2660 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2661 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2662 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2663 break;
2664 }
2665
2666 mVWheelScale = 1.0f;
2667 mHWheelScale = 1.0f;
2668 }
2669
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002670 if ((!changes && config->pointerCapture)
2671 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2672 if (config->pointerCapture) {
2673 if (mParameters.mode == Parameters::MODE_POINTER) {
2674 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2675 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2676 // Keep PointerController around in order to preserve the pointer position.
2677 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2678 } else {
2679 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2680 }
2681 } else {
2682 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2683 mParameters.mode = Parameters::MODE_POINTER;
2684 mSource = AINPUT_SOURCE_MOUSE;
2685 } else {
2686 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2687 }
2688 }
2689 bumpGeneration();
2690 if (changes) {
2691 getDevice()->notifyReset(when);
2692 }
2693 }
2694
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2696 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2697 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2698 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2699 }
2700
2701 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2702 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2703 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002704 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705 mOrientation = v.orientation;
2706 } else {
2707 mOrientation = DISPLAY_ORIENTATION_0;
2708 }
2709 } else {
2710 mOrientation = DISPLAY_ORIENTATION_0;
2711 }
2712 bumpGeneration();
2713 }
2714}
2715
2716void CursorInputMapper::configureParameters() {
2717 mParameters.mode = Parameters::MODE_POINTER;
2718 String8 cursorModeString;
2719 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2720 if (cursorModeString == "navigation") {
2721 mParameters.mode = Parameters::MODE_NAVIGATION;
2722 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2723 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2724 }
2725 }
2726
2727 mParameters.orientationAware = false;
2728 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2729 mParameters.orientationAware);
2730
2731 mParameters.hasAssociatedDisplay = false;
2732 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2733 mParameters.hasAssociatedDisplay = true;
2734 }
2735}
2736
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002737void CursorInputMapper::dumpParameters(std::string& dump) {
2738 dump += INDENT3 "Parameters:\n";
2739 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 toString(mParameters.hasAssociatedDisplay));
2741
2742 switch (mParameters.mode) {
2743 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002744 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002746 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002747 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002748 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002750 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002751 break;
2752 default:
2753 ALOG_ASSERT(false);
2754 }
2755
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002756 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 toString(mParameters.orientationAware));
2758}
2759
2760void CursorInputMapper::reset(nsecs_t when) {
2761 mButtonState = 0;
2762 mDownTime = 0;
2763
2764 mPointerVelocityControl.reset();
2765 mWheelXVelocityControl.reset();
2766 mWheelYVelocityControl.reset();
2767
2768 mCursorButtonAccumulator.reset(getDevice());
2769 mCursorMotionAccumulator.reset(getDevice());
2770 mCursorScrollAccumulator.reset(getDevice());
2771
2772 InputMapper::reset(when);
2773}
2774
2775void CursorInputMapper::process(const RawEvent* rawEvent) {
2776 mCursorButtonAccumulator.process(rawEvent);
2777 mCursorMotionAccumulator.process(rawEvent);
2778 mCursorScrollAccumulator.process(rawEvent);
2779
2780 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2781 sync(rawEvent->when);
2782 }
2783}
2784
2785void CursorInputMapper::sync(nsecs_t when) {
2786 int32_t lastButtonState = mButtonState;
2787 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2788 mButtonState = currentButtonState;
2789
2790 bool wasDown = isPointerDown(lastButtonState);
2791 bool down = isPointerDown(currentButtonState);
2792 bool downChanged;
2793 if (!wasDown && down) {
2794 mDownTime = when;
2795 downChanged = true;
2796 } else if (wasDown && !down) {
2797 downChanged = true;
2798 } else {
2799 downChanged = false;
2800 }
2801 nsecs_t downTime = mDownTime;
2802 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002803 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2804 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805
2806 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2807 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2808 bool moved = deltaX != 0 || deltaY != 0;
2809
2810 // Rotate delta according to orientation if needed.
2811 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2812 && (deltaX != 0.0f || deltaY != 0.0f)) {
2813 rotateDelta(mOrientation, &deltaX, &deltaY);
2814 }
2815
2816 // Move the pointer.
2817 PointerProperties pointerProperties;
2818 pointerProperties.clear();
2819 pointerProperties.id = 0;
2820 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2821
2822 PointerCoords pointerCoords;
2823 pointerCoords.clear();
2824
2825 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2826 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2827 bool scrolled = vscroll != 0 || hscroll != 0;
2828
2829 mWheelYVelocityControl.move(when, NULL, &vscroll);
2830 mWheelXVelocityControl.move(when, &hscroll, NULL);
2831
2832 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2833
2834 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002835 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 if (moved || scrolled || buttonsChanged) {
2837 mPointerController->setPresentation(
2838 PointerControllerInterface::PRESENTATION_POINTER);
2839
2840 if (moved) {
2841 mPointerController->move(deltaX, deltaY);
2842 }
2843
2844 if (buttonsChanged) {
2845 mPointerController->setButtonState(currentButtonState);
2846 }
2847
2848 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2849 }
2850
2851 float x, y;
2852 mPointerController->getPosition(&x, &y);
2853 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2854 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002855 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2856 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857 displayId = ADISPLAY_ID_DEFAULT;
2858 } else {
2859 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2860 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2861 displayId = ADISPLAY_ID_NONE;
2862 }
2863
2864 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2865
2866 // Moving an external trackball or mouse should wake the device.
2867 // We don't do this for internal cursor devices to prevent them from waking up
2868 // the device in your pocket.
2869 // TODO: Use the input device configuration to control this behavior more finely.
2870 uint32_t policyFlags = 0;
2871 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002872 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 }
2874
2875 // Synthesize key down from buttons if needed.
2876 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2877 policyFlags, lastButtonState, currentButtonState);
2878
2879 // Send motion event.
2880 if (downChanged || moved || scrolled || buttonsChanged) {
2881 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002882 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883 int32_t motionEventAction;
2884 if (downChanged) {
2885 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002886 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2888 } else {
2889 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2890 }
2891
Michael Wright7b159c92015-05-14 14:48:03 +01002892 if (buttonsReleased) {
2893 BitSet32 released(buttonsReleased);
2894 while (!released.isEmpty()) {
2895 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2896 buttonState &= ~actionButton;
2897 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2898 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2899 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08002900 displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002901 mXPrecision, mYPrecision, downTime);
2902 getListener()->notifyMotion(&releaseArgs);
2903 }
2904 }
2905
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002907 motionEventAction, 0, 0, metaState, currentButtonState,
2908 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08002909 displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910 mXPrecision, mYPrecision, downTime);
2911 getListener()->notifyMotion(&args);
2912
Michael Wright7b159c92015-05-14 14:48:03 +01002913 if (buttonsPressed) {
2914 BitSet32 pressed(buttonsPressed);
2915 while (!pressed.isEmpty()) {
2916 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2917 buttonState |= actionButton;
2918 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2919 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2920 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08002921 displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002922 mXPrecision, mYPrecision, downTime);
2923 getListener()->notifyMotion(&pressArgs);
2924 }
2925 }
2926
2927 ALOG_ASSERT(buttonState == currentButtonState);
2928
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 // Send hover move after UP to tell the application that the mouse is hovering now.
2930 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002931 && (mSource == AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002933 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08002935 displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936 mXPrecision, mYPrecision, downTime);
2937 getListener()->notifyMotion(&hoverArgs);
2938 }
2939
2940 // Send scroll events.
2941 if (scrolled) {
2942 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2943 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2944
2945 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002946 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08002948 displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 mXPrecision, mYPrecision, downTime);
2950 getListener()->notifyMotion(&scrollArgs);
2951 }
2952 }
2953
2954 // Synthesize key up from buttons if needed.
2955 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2956 policyFlags, lastButtonState, currentButtonState);
2957
2958 mCursorMotionAccumulator.finishSync();
2959 mCursorScrollAccumulator.finishSync();
2960}
2961
2962int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2963 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2964 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2965 } else {
2966 return AKEY_STATE_UNKNOWN;
2967 }
2968}
2969
2970void CursorInputMapper::fadePointer() {
2971 if (mPointerController != NULL) {
2972 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2973 }
2974}
2975
Prashant Malani1941ff52015-08-11 18:29:28 -07002976// --- RotaryEncoderInputMapper ---
2977
2978RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002979 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002980 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2981}
2982
2983RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2984}
2985
2986uint32_t RotaryEncoderInputMapper::getSources() {
2987 return mSource;
2988}
2989
2990void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2991 InputMapper::populateDeviceInfo(info);
2992
2993 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002994 float res = 0.0f;
2995 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2996 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2997 }
2998 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2999 mScalingFactor)) {
3000 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
3001 "default to 1.0!\n");
3002 mScalingFactor = 1.0f;
3003 }
3004 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3005 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003006 }
3007}
3008
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003009void RotaryEncoderInputMapper::dump(std::string& dump) {
3010 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
3011 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07003012 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
3013}
3014
3015void RotaryEncoderInputMapper::configure(nsecs_t when,
3016 const InputReaderConfiguration* config, uint32_t changes) {
3017 InputMapper::configure(when, config, changes);
3018 if (!changes) {
3019 mRotaryEncoderScrollAccumulator.configure(getDevice());
3020 }
Ivan Podogovad437252016-09-29 16:29:55 +01003021 if (!changes || (InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
3022 DisplayViewport v;
3023 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
3024 mOrientation = v.orientation;
3025 } else {
3026 mOrientation = DISPLAY_ORIENTATION_0;
3027 }
3028 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003029}
3030
3031void RotaryEncoderInputMapper::reset(nsecs_t when) {
3032 mRotaryEncoderScrollAccumulator.reset(getDevice());
3033
3034 InputMapper::reset(when);
3035}
3036
3037void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3038 mRotaryEncoderScrollAccumulator.process(rawEvent);
3039
3040 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3041 sync(rawEvent->when);
3042 }
3043}
3044
3045void RotaryEncoderInputMapper::sync(nsecs_t when) {
3046 PointerCoords pointerCoords;
3047 pointerCoords.clear();
3048
3049 PointerProperties pointerProperties;
3050 pointerProperties.clear();
3051 pointerProperties.id = 0;
3052 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3053
3054 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3055 bool scrolled = scroll != 0;
3056
3057 // This is not a pointer, so it's not associated with a display.
3058 int32_t displayId = ADISPLAY_ID_NONE;
3059
3060 // Moving the rotary encoder should wake the device (if specified).
3061 uint32_t policyFlags = 0;
3062 if (scrolled && getDevice()->isExternal()) {
3063 policyFlags |= POLICY_FLAG_WAKE;
3064 }
3065
Ivan Podogovad437252016-09-29 16:29:55 +01003066 if (mOrientation == DISPLAY_ORIENTATION_180) {
3067 scroll = -scroll;
3068 }
3069
Prashant Malani1941ff52015-08-11 18:29:28 -07003070 // Send motion event.
3071 if (scrolled) {
3072 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003073 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003074
3075 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
3076 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3077 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08003078 displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Prashant Malani1941ff52015-08-11 18:29:28 -07003079 0, 0, 0);
3080 getListener()->notifyMotion(&scrollArgs);
3081 }
3082
3083 mRotaryEncoderScrollAccumulator.finishSync();
3084}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085
3086// --- TouchInputMapper ---
3087
3088TouchInputMapper::TouchInputMapper(InputDevice* device) :
3089 InputMapper(device),
3090 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3091 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003092 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3094}
3095
3096TouchInputMapper::~TouchInputMapper() {
3097}
3098
3099uint32_t TouchInputMapper::getSources() {
3100 return mSource;
3101}
3102
3103void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3104 InputMapper::populateDeviceInfo(info);
3105
3106 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3107 info->addMotionRange(mOrientedRanges.x);
3108 info->addMotionRange(mOrientedRanges.y);
3109 info->addMotionRange(mOrientedRanges.pressure);
3110
3111 if (mOrientedRanges.haveSize) {
3112 info->addMotionRange(mOrientedRanges.size);
3113 }
3114
3115 if (mOrientedRanges.haveTouchSize) {
3116 info->addMotionRange(mOrientedRanges.touchMajor);
3117 info->addMotionRange(mOrientedRanges.touchMinor);
3118 }
3119
3120 if (mOrientedRanges.haveToolSize) {
3121 info->addMotionRange(mOrientedRanges.toolMajor);
3122 info->addMotionRange(mOrientedRanges.toolMinor);
3123 }
3124
3125 if (mOrientedRanges.haveOrientation) {
3126 info->addMotionRange(mOrientedRanges.orientation);
3127 }
3128
3129 if (mOrientedRanges.haveDistance) {
3130 info->addMotionRange(mOrientedRanges.distance);
3131 }
3132
3133 if (mOrientedRanges.haveTilt) {
3134 info->addMotionRange(mOrientedRanges.tilt);
3135 }
3136
3137 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3138 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3139 0.0f);
3140 }
3141 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3142 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3143 0.0f);
3144 }
3145 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3146 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3147 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3148 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3149 x.fuzz, x.resolution);
3150 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3151 y.fuzz, y.resolution);
3152 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3153 x.fuzz, x.resolution);
3154 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3155 y.fuzz, y.resolution);
3156 }
3157 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3158 }
3159}
3160
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003161void TouchInputMapper::dump(std::string& dump) {
3162 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 dumpParameters(dump);
3164 dumpVirtualKeys(dump);
3165 dumpRawPointerAxes(dump);
3166 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003167 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 dumpSurface(dump);
3169
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003170 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3171 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3172 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3173 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3174 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3175 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3176 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3177 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3178 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3179 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3180 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3181 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3182 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3183 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3184 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3185 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3186 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003188 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3189 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003190 mLastRawState.rawPointerData.pointerCount);
3191 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3192 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003193 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3195 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3196 "toolType=%d, isHovering=%s\n", i,
3197 pointer.id, pointer.x, pointer.y, pointer.pressure,
3198 pointer.touchMajor, pointer.touchMinor,
3199 pointer.toolMajor, pointer.toolMinor,
3200 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3201 pointer.toolType, toString(pointer.isHovering));
3202 }
3203
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003204 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3205 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003206 mLastCookedState.cookedPointerData.pointerCount);
3207 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3208 const PointerProperties& pointerProperties =
3209 mLastCookedState.cookedPointerData.pointerProperties[i];
3210 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003211 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3213 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3214 "toolType=%d, isHovering=%s\n", i,
3215 pointerProperties.id,
3216 pointerCoords.getX(),
3217 pointerCoords.getY(),
3218 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3219 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3220 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3221 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3222 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3223 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3224 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3225 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3226 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003227 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 }
3229
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003230 dump += INDENT3 "Stylus Fusion:\n";
3231 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003232 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003233 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3234 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003235 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003236 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003237 dumpStylusState(dump, mExternalStylusState);
3238
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003240 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3241 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003243 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003245 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003247 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003249 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 mPointerGestureMaxSwipeWidth);
3251 }
3252}
3253
Santos Cordonfa5cf462017-04-05 10:37:00 -07003254const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3255 switch (deviceMode) {
3256 case DEVICE_MODE_DISABLED:
3257 return "disabled";
3258 case DEVICE_MODE_DIRECT:
3259 return "direct";
3260 case DEVICE_MODE_UNSCALED:
3261 return "unscaled";
3262 case DEVICE_MODE_NAVIGATION:
3263 return "navigation";
3264 case DEVICE_MODE_POINTER:
3265 return "pointer";
3266 }
3267 return "unknown";
3268}
3269
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270void TouchInputMapper::configure(nsecs_t when,
3271 const InputReaderConfiguration* config, uint32_t changes) {
3272 InputMapper::configure(when, config, changes);
3273
3274 mConfig = *config;
3275
3276 if (!changes) { // first time only
3277 // Configure basic parameters.
3278 configureParameters();
3279
3280 // Configure common accumulators.
3281 mCursorScrollAccumulator.configure(getDevice());
3282 mTouchButtonAccumulator.configure(getDevice());
3283
3284 // Configure absolute axis information.
3285 configureRawPointerAxes();
3286
3287 // Prepare input device calibration.
3288 parseCalibration();
3289 resolveCalibration();
3290 }
3291
Michael Wright842500e2015-03-13 17:32:02 -07003292 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003293 // Update location calibration to reflect current settings
3294 updateAffineTransformation();
3295 }
3296
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3298 // Update pointer speed.
3299 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3300 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3301 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3302 }
3303
3304 bool resetNeeded = false;
3305 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3306 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003307 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3308 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 // Configure device sources, surface dimensions, orientation and
3310 // scaling factors.
3311 configureSurface(when, &resetNeeded);
3312 }
3313
3314 if (changes && resetNeeded) {
3315 // Send reset, unless this is the first time the device has been configured,
3316 // in which case the reader will call reset itself after all mappers are ready.
3317 getDevice()->notifyReset(when);
3318 }
3319}
3320
Michael Wright842500e2015-03-13 17:32:02 -07003321void TouchInputMapper::resolveExternalStylusPresence() {
3322 Vector<InputDeviceInfo> devices;
3323 mContext->getExternalStylusDevices(devices);
3324 mExternalStylusConnected = !devices.isEmpty();
3325
3326 if (!mExternalStylusConnected) {
3327 resetExternalStylus();
3328 }
3329}
3330
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331void TouchInputMapper::configureParameters() {
3332 // Use the pointer presentation mode for devices that do not support distinct
3333 // multitouch. The spot-based presentation relies on being able to accurately
3334 // locate two or more fingers on the touch pad.
3335 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003336 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337
3338 String8 gestureModeString;
3339 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3340 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003341 if (gestureModeString == "single-touch") {
3342 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3343 } else if (gestureModeString == "multi-touch") {
3344 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345 } else if (gestureModeString != "default") {
3346 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3347 }
3348 }
3349
3350 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3351 // The device is a touch screen.
3352 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3353 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3354 // The device is a pointing device like a track pad.
3355 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3356 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3357 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3358 // The device is a cursor device with a touch pad attached.
3359 // By default don't use the touch pad to move the pointer.
3360 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3361 } else {
3362 // The device is a touch pad of unknown purpose.
3363 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3364 }
3365
3366 mParameters.hasButtonUnderPad=
3367 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3368
3369 String8 deviceTypeString;
3370 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3371 deviceTypeString)) {
3372 if (deviceTypeString == "touchScreen") {
3373 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3374 } else if (deviceTypeString == "touchPad") {
3375 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3376 } else if (deviceTypeString == "touchNavigation") {
3377 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3378 } else if (deviceTypeString == "pointer") {
3379 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3380 } else if (deviceTypeString != "default") {
3381 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3382 }
3383 }
3384
3385 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3386 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3387 mParameters.orientationAware);
3388
3389 mParameters.hasAssociatedDisplay = false;
3390 mParameters.associatedDisplayIsExternal = false;
3391 if (mParameters.orientationAware
3392 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3393 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3394 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003395 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3396 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3397 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3398 mParameters.uniqueDisplayId);
3399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003401
3402 // Initial downs on external touch devices should wake the device.
3403 // Normally we don't do this for internal touch screens to prevent them from waking
3404 // up in your pocket but you can enable it using the input device configuration.
3405 mParameters.wake = getDevice()->isExternal();
3406 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3407 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408}
3409
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003410void TouchInputMapper::dumpParameters(std::string& dump) {
3411 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412
3413 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003414 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003415 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003417 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003418 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 break;
3420 default:
3421 assert(false);
3422 }
3423
3424 switch (mParameters.deviceType) {
3425 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003426 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 break;
3428 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003429 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 break;
3431 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003432 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 break;
3434 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003435 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 break;
3437 default:
3438 ALOG_ASSERT(false);
3439 }
3440
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003441 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003442 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003444 toString(mParameters.associatedDisplayIsExternal),
3445 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003446 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447 toString(mParameters.orientationAware));
3448}
3449
3450void TouchInputMapper::configureRawPointerAxes() {
3451 mRawPointerAxes.clear();
3452}
3453
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003454void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3455 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3457 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3458 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3459 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3460 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3461 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3462 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3463 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3464 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3465 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3466 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3467 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3468 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3469}
3470
Michael Wright842500e2015-03-13 17:32:02 -07003471bool TouchInputMapper::hasExternalStylus() const {
3472 return mExternalStylusConnected;
3473}
3474
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3476 int32_t oldDeviceMode = mDeviceMode;
3477
Michael Wright842500e2015-03-13 17:32:02 -07003478 resolveExternalStylusPresence();
3479
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480 // Determine device mode.
3481 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3482 && mConfig.pointerGesturesEnabled) {
3483 mSource = AINPUT_SOURCE_MOUSE;
3484 mDeviceMode = DEVICE_MODE_POINTER;
3485 if (hasStylus()) {
3486 mSource |= AINPUT_SOURCE_STYLUS;
3487 }
3488 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3489 && mParameters.hasAssociatedDisplay) {
3490 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3491 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003492 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493 mSource |= AINPUT_SOURCE_STYLUS;
3494 }
Michael Wright2f78b682015-06-12 15:25:08 +01003495 if (hasExternalStylus()) {
3496 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3499 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3500 mDeviceMode = DEVICE_MODE_NAVIGATION;
3501 } else {
3502 mSource = AINPUT_SOURCE_TOUCHPAD;
3503 mDeviceMode = DEVICE_MODE_UNSCALED;
3504 }
3505
3506 // Ensure we have valid X and Y axes.
3507 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3508 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3509 "The device will be inoperable.", getDeviceName().string());
3510 mDeviceMode = DEVICE_MODE_DISABLED;
3511 return;
3512 }
3513
3514 // Raw width and height in the natural orientation.
3515 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3516 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3517
3518 // Get associated display dimensions.
3519 DisplayViewport newViewport;
3520 if (mParameters.hasAssociatedDisplay) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003521 const String8* uniqueDisplayId = NULL;
3522 ViewportType viewportTypeToUse;
3523
3524 if (mParameters.associatedDisplayIsExternal) {
3525 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3526 } else if (!mParameters.uniqueDisplayId.isEmpty()) {
3527 // If the IDC file specified a unique display Id, then it expects to be linked to a
3528 // virtual display with the same unique ID.
3529 uniqueDisplayId = &mParameters.uniqueDisplayId;
3530 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3531 } else {
3532 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3533 }
3534
3535 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3537 "display. The device will be inoperable until the display size "
3538 "becomes available.",
3539 getDeviceName().string());
3540 mDeviceMode = DEVICE_MODE_DISABLED;
3541 return;
3542 }
3543 } else {
3544 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3545 }
3546 bool viewportChanged = mViewport != newViewport;
3547 if (viewportChanged) {
3548 mViewport = newViewport;
3549
3550 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3551 // Convert rotated viewport to natural surface coordinates.
3552 int32_t naturalLogicalWidth, naturalLogicalHeight;
3553 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3554 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3555 int32_t naturalDeviceWidth, naturalDeviceHeight;
3556 switch (mViewport.orientation) {
3557 case DISPLAY_ORIENTATION_90:
3558 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3559 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3560 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3561 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3562 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3563 naturalPhysicalTop = mViewport.physicalLeft;
3564 naturalDeviceWidth = mViewport.deviceHeight;
3565 naturalDeviceHeight = mViewport.deviceWidth;
3566 break;
3567 case DISPLAY_ORIENTATION_180:
3568 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3569 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3570 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3571 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3572 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3573 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3574 naturalDeviceWidth = mViewport.deviceWidth;
3575 naturalDeviceHeight = mViewport.deviceHeight;
3576 break;
3577 case DISPLAY_ORIENTATION_270:
3578 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3579 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3580 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3581 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3582 naturalPhysicalLeft = mViewport.physicalTop;
3583 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3584 naturalDeviceWidth = mViewport.deviceHeight;
3585 naturalDeviceHeight = mViewport.deviceWidth;
3586 break;
3587 case DISPLAY_ORIENTATION_0:
3588 default:
3589 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3590 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3591 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3592 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3593 naturalPhysicalLeft = mViewport.physicalLeft;
3594 naturalPhysicalTop = mViewport.physicalTop;
3595 naturalDeviceWidth = mViewport.deviceWidth;
3596 naturalDeviceHeight = mViewport.deviceHeight;
3597 break;
3598 }
3599
Michael Wright358bcc72018-08-21 04:01:07 +01003600 mPhysicalWidth = naturalPhysicalWidth;
3601 mPhysicalHeight = naturalPhysicalHeight;
3602 mPhysicalLeft = naturalPhysicalLeft;
3603 mPhysicalTop = naturalPhysicalTop;
3604
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3606 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3607 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3608 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3609
3610 mSurfaceOrientation = mParameters.orientationAware ?
3611 mViewport.orientation : DISPLAY_ORIENTATION_0;
3612 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003613 mPhysicalWidth = rawWidth;
3614 mPhysicalHeight = rawHeight;
3615 mPhysicalLeft = 0;
3616 mPhysicalTop = 0;
3617
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 mSurfaceWidth = rawWidth;
3619 mSurfaceHeight = rawHeight;
3620 mSurfaceLeft = 0;
3621 mSurfaceTop = 0;
3622 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3623 }
3624 }
3625
3626 // If moving between pointer modes, need to reset some state.
3627 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3628 if (deviceModeChanged) {
3629 mOrientedRanges.clear();
3630 }
3631
3632 // Create pointer controller if needed.
3633 if (mDeviceMode == DEVICE_MODE_POINTER ||
3634 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3635 if (mPointerController == NULL) {
3636 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3637 }
3638 } else {
3639 mPointerController.clear();
3640 }
3641
3642 if (viewportChanged || deviceModeChanged) {
3643 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3644 "display id %d",
3645 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3646 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3647
3648 // Configure X and Y factors.
3649 mXScale = float(mSurfaceWidth) / rawWidth;
3650 mYScale = float(mSurfaceHeight) / rawHeight;
3651 mXTranslate = -mSurfaceLeft;
3652 mYTranslate = -mSurfaceTop;
3653 mXPrecision = 1.0f / mXScale;
3654 mYPrecision = 1.0f / mYScale;
3655
3656 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3657 mOrientedRanges.x.source = mSource;
3658 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3659 mOrientedRanges.y.source = mSource;
3660
3661 configureVirtualKeys();
3662
3663 // Scale factor for terms that are not oriented in a particular axis.
3664 // If the pixels are square then xScale == yScale otherwise we fake it
3665 // by choosing an average.
3666 mGeometricScale = avg(mXScale, mYScale);
3667
3668 // Size of diagonal axis.
3669 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3670
3671 // Size factors.
3672 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3673 if (mRawPointerAxes.touchMajor.valid
3674 && mRawPointerAxes.touchMajor.maxValue != 0) {
3675 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3676 } else if (mRawPointerAxes.toolMajor.valid
3677 && mRawPointerAxes.toolMajor.maxValue != 0) {
3678 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3679 } else {
3680 mSizeScale = 0.0f;
3681 }
3682
3683 mOrientedRanges.haveTouchSize = true;
3684 mOrientedRanges.haveToolSize = true;
3685 mOrientedRanges.haveSize = true;
3686
3687 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3688 mOrientedRanges.touchMajor.source = mSource;
3689 mOrientedRanges.touchMajor.min = 0;
3690 mOrientedRanges.touchMajor.max = diagonalSize;
3691 mOrientedRanges.touchMajor.flat = 0;
3692 mOrientedRanges.touchMajor.fuzz = 0;
3693 mOrientedRanges.touchMajor.resolution = 0;
3694
3695 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3696 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3697
3698 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3699 mOrientedRanges.toolMajor.source = mSource;
3700 mOrientedRanges.toolMajor.min = 0;
3701 mOrientedRanges.toolMajor.max = diagonalSize;
3702 mOrientedRanges.toolMajor.flat = 0;
3703 mOrientedRanges.toolMajor.fuzz = 0;
3704 mOrientedRanges.toolMajor.resolution = 0;
3705
3706 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3707 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3708
3709 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3710 mOrientedRanges.size.source = mSource;
3711 mOrientedRanges.size.min = 0;
3712 mOrientedRanges.size.max = 1.0;
3713 mOrientedRanges.size.flat = 0;
3714 mOrientedRanges.size.fuzz = 0;
3715 mOrientedRanges.size.resolution = 0;
3716 } else {
3717 mSizeScale = 0.0f;
3718 }
3719
3720 // Pressure factors.
3721 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003722 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3724 || mCalibration.pressureCalibration
3725 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3726 if (mCalibration.havePressureScale) {
3727 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003728 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 } else if (mRawPointerAxes.pressure.valid
3730 && mRawPointerAxes.pressure.maxValue != 0) {
3731 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3732 }
3733 }
3734
3735 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3736 mOrientedRanges.pressure.source = mSource;
3737 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003738 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 mOrientedRanges.pressure.flat = 0;
3740 mOrientedRanges.pressure.fuzz = 0;
3741 mOrientedRanges.pressure.resolution = 0;
3742
3743 // Tilt
3744 mTiltXCenter = 0;
3745 mTiltXScale = 0;
3746 mTiltYCenter = 0;
3747 mTiltYScale = 0;
3748 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3749 if (mHaveTilt) {
3750 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3751 mRawPointerAxes.tiltX.maxValue);
3752 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3753 mRawPointerAxes.tiltY.maxValue);
3754 mTiltXScale = M_PI / 180;
3755 mTiltYScale = M_PI / 180;
3756
3757 mOrientedRanges.haveTilt = true;
3758
3759 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3760 mOrientedRanges.tilt.source = mSource;
3761 mOrientedRanges.tilt.min = 0;
3762 mOrientedRanges.tilt.max = M_PI_2;
3763 mOrientedRanges.tilt.flat = 0;
3764 mOrientedRanges.tilt.fuzz = 0;
3765 mOrientedRanges.tilt.resolution = 0;
3766 }
3767
3768 // Orientation
3769 mOrientationScale = 0;
3770 if (mHaveTilt) {
3771 mOrientedRanges.haveOrientation = true;
3772
3773 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3774 mOrientedRanges.orientation.source = mSource;
3775 mOrientedRanges.orientation.min = -M_PI;
3776 mOrientedRanges.orientation.max = M_PI;
3777 mOrientedRanges.orientation.flat = 0;
3778 mOrientedRanges.orientation.fuzz = 0;
3779 mOrientedRanges.orientation.resolution = 0;
3780 } else if (mCalibration.orientationCalibration !=
3781 Calibration::ORIENTATION_CALIBRATION_NONE) {
3782 if (mCalibration.orientationCalibration
3783 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3784 if (mRawPointerAxes.orientation.valid) {
3785 if (mRawPointerAxes.orientation.maxValue > 0) {
3786 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3787 } else if (mRawPointerAxes.orientation.minValue < 0) {
3788 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3789 } else {
3790 mOrientationScale = 0;
3791 }
3792 }
3793 }
3794
3795 mOrientedRanges.haveOrientation = true;
3796
3797 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3798 mOrientedRanges.orientation.source = mSource;
3799 mOrientedRanges.orientation.min = -M_PI_2;
3800 mOrientedRanges.orientation.max = M_PI_2;
3801 mOrientedRanges.orientation.flat = 0;
3802 mOrientedRanges.orientation.fuzz = 0;
3803 mOrientedRanges.orientation.resolution = 0;
3804 }
3805
3806 // Distance
3807 mDistanceScale = 0;
3808 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3809 if (mCalibration.distanceCalibration
3810 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3811 if (mCalibration.haveDistanceScale) {
3812 mDistanceScale = mCalibration.distanceScale;
3813 } else {
3814 mDistanceScale = 1.0f;
3815 }
3816 }
3817
3818 mOrientedRanges.haveDistance = true;
3819
3820 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3821 mOrientedRanges.distance.source = mSource;
3822 mOrientedRanges.distance.min =
3823 mRawPointerAxes.distance.minValue * mDistanceScale;
3824 mOrientedRanges.distance.max =
3825 mRawPointerAxes.distance.maxValue * mDistanceScale;
3826 mOrientedRanges.distance.flat = 0;
3827 mOrientedRanges.distance.fuzz =
3828 mRawPointerAxes.distance.fuzz * mDistanceScale;
3829 mOrientedRanges.distance.resolution = 0;
3830 }
3831
3832 // Compute oriented precision, scales and ranges.
3833 // Note that the maximum value reported is an inclusive maximum value so it is one
3834 // unit less than the total width or height of surface.
3835 switch (mSurfaceOrientation) {
3836 case DISPLAY_ORIENTATION_90:
3837 case DISPLAY_ORIENTATION_270:
3838 mOrientedXPrecision = mYPrecision;
3839 mOrientedYPrecision = mXPrecision;
3840
3841 mOrientedRanges.x.min = mYTranslate;
3842 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3843 mOrientedRanges.x.flat = 0;
3844 mOrientedRanges.x.fuzz = 0;
3845 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3846
3847 mOrientedRanges.y.min = mXTranslate;
3848 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3849 mOrientedRanges.y.flat = 0;
3850 mOrientedRanges.y.fuzz = 0;
3851 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3852 break;
3853
3854 default:
3855 mOrientedXPrecision = mXPrecision;
3856 mOrientedYPrecision = mYPrecision;
3857
3858 mOrientedRanges.x.min = mXTranslate;
3859 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3860 mOrientedRanges.x.flat = 0;
3861 mOrientedRanges.x.fuzz = 0;
3862 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3863
3864 mOrientedRanges.y.min = mYTranslate;
3865 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3866 mOrientedRanges.y.flat = 0;
3867 mOrientedRanges.y.fuzz = 0;
3868 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3869 break;
3870 }
3871
Jason Gerecke71b16e82014-03-10 09:47:59 -07003872 // Location
3873 updateAffineTransformation();
3874
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 if (mDeviceMode == DEVICE_MODE_POINTER) {
3876 // Compute pointer gesture detection parameters.
3877 float rawDiagonal = hypotf(rawWidth, rawHeight);
3878 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3879
3880 // Scale movements such that one whole swipe of the touch pad covers a
3881 // given area relative to the diagonal size of the display when no acceleration
3882 // is applied.
3883 // Assume that the touch pad has a square aspect ratio such that movements in
3884 // X and Y of the same number of raw units cover the same physical distance.
3885 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3886 * displayDiagonal / rawDiagonal;
3887 mPointerYMovementScale = mPointerXMovementScale;
3888
3889 // Scale zooms to cover a smaller range of the display than movements do.
3890 // This value determines the area around the pointer that is affected by freeform
3891 // pointer gestures.
3892 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3893 * displayDiagonal / rawDiagonal;
3894 mPointerYZoomScale = mPointerXZoomScale;
3895
3896 // Max width between pointers to detect a swipe gesture is more than some fraction
3897 // of the diagonal axis of the touch pad. Touches that are wider than this are
3898 // translated into freeform gestures.
3899 mPointerGestureMaxSwipeWidth =
3900 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3901
3902 // Abort current pointer usages because the state has changed.
3903 abortPointerUsage(when, 0 /*policyFlags*/);
3904 }
3905
3906 // Inform the dispatcher about the changes.
3907 *outResetNeeded = true;
3908 bumpGeneration();
3909 }
3910}
3911
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003912void TouchInputMapper::dumpSurface(std::string& dump) {
3913 dump += StringPrintf(INDENT3 "Viewport: displayId=%d, orientation=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914 "logicalFrame=[%d, %d, %d, %d], "
3915 "physicalFrame=[%d, %d, %d, %d], "
3916 "deviceSize=[%d, %d]\n",
3917 mViewport.displayId, mViewport.orientation,
3918 mViewport.logicalLeft, mViewport.logicalTop,
3919 mViewport.logicalRight, mViewport.logicalBottom,
3920 mViewport.physicalLeft, mViewport.physicalTop,
3921 mViewport.physicalRight, mViewport.physicalBottom,
3922 mViewport.deviceWidth, mViewport.deviceHeight);
3923
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003924 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3925 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3926 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3927 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003928 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3929 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3930 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3931 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003932 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933}
3934
3935void TouchInputMapper::configureVirtualKeys() {
3936 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3937 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3938
3939 mVirtualKeys.clear();
3940
3941 if (virtualKeyDefinitions.size() == 0) {
3942 return;
3943 }
3944
3945 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3946
3947 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3948 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3949 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3950 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3951
3952 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3953 const VirtualKeyDefinition& virtualKeyDefinition =
3954 virtualKeyDefinitions[i];
3955
3956 mVirtualKeys.add();
3957 VirtualKey& virtualKey = mVirtualKeys.editTop();
3958
3959 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3960 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003961 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003963 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3964 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3966 virtualKey.scanCode);
3967 mVirtualKeys.pop(); // drop the key
3968 continue;
3969 }
3970
3971 virtualKey.keyCode = keyCode;
3972 virtualKey.flags = flags;
3973
3974 // convert the key definition's display coordinates into touch coordinates for a hit box
3975 int32_t halfWidth = virtualKeyDefinition.width / 2;
3976 int32_t halfHeight = virtualKeyDefinition.height / 2;
3977
3978 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3979 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3980 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3981 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3982 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3983 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3984 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3985 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3986 }
3987}
3988
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003989void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003991 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992
3993 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3994 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003995 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3997 i, virtualKey.scanCode, virtualKey.keyCode,
3998 virtualKey.hitLeft, virtualKey.hitRight,
3999 virtualKey.hitTop, virtualKey.hitBottom);
4000 }
4001 }
4002}
4003
4004void TouchInputMapper::parseCalibration() {
4005 const PropertyMap& in = getDevice()->getConfiguration();
4006 Calibration& out = mCalibration;
4007
4008 // Size
4009 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4010 String8 sizeCalibrationString;
4011 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4012 if (sizeCalibrationString == "none") {
4013 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4014 } else if (sizeCalibrationString == "geometric") {
4015 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4016 } else if (sizeCalibrationString == "diameter") {
4017 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4018 } else if (sizeCalibrationString == "box") {
4019 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4020 } else if (sizeCalibrationString == "area") {
4021 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4022 } else if (sizeCalibrationString != "default") {
4023 ALOGW("Invalid value for touch.size.calibration: '%s'",
4024 sizeCalibrationString.string());
4025 }
4026 }
4027
4028 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4029 out.sizeScale);
4030 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4031 out.sizeBias);
4032 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4033 out.sizeIsSummed);
4034
4035 // Pressure
4036 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4037 String8 pressureCalibrationString;
4038 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4039 if (pressureCalibrationString == "none") {
4040 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4041 } else if (pressureCalibrationString == "physical") {
4042 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4043 } else if (pressureCalibrationString == "amplitude") {
4044 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4045 } else if (pressureCalibrationString != "default") {
4046 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4047 pressureCalibrationString.string());
4048 }
4049 }
4050
4051 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4052 out.pressureScale);
4053
4054 // Orientation
4055 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4056 String8 orientationCalibrationString;
4057 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4058 if (orientationCalibrationString == "none") {
4059 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4060 } else if (orientationCalibrationString == "interpolated") {
4061 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4062 } else if (orientationCalibrationString == "vector") {
4063 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4064 } else if (orientationCalibrationString != "default") {
4065 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4066 orientationCalibrationString.string());
4067 }
4068 }
4069
4070 // Distance
4071 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4072 String8 distanceCalibrationString;
4073 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4074 if (distanceCalibrationString == "none") {
4075 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4076 } else if (distanceCalibrationString == "scaled") {
4077 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4078 } else if (distanceCalibrationString != "default") {
4079 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4080 distanceCalibrationString.string());
4081 }
4082 }
4083
4084 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4085 out.distanceScale);
4086
4087 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4088 String8 coverageCalibrationString;
4089 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4090 if (coverageCalibrationString == "none") {
4091 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4092 } else if (coverageCalibrationString == "box") {
4093 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4094 } else if (coverageCalibrationString != "default") {
4095 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4096 coverageCalibrationString.string());
4097 }
4098 }
4099}
4100
4101void TouchInputMapper::resolveCalibration() {
4102 // Size
4103 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4104 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4105 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4106 }
4107 } else {
4108 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4109 }
4110
4111 // Pressure
4112 if (mRawPointerAxes.pressure.valid) {
4113 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4114 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4115 }
4116 } else {
4117 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4118 }
4119
4120 // Orientation
4121 if (mRawPointerAxes.orientation.valid) {
4122 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4123 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4124 }
4125 } else {
4126 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4127 }
4128
4129 // Distance
4130 if (mRawPointerAxes.distance.valid) {
4131 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4132 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4133 }
4134 } else {
4135 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4136 }
4137
4138 // Coverage
4139 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4140 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4141 }
4142}
4143
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004144void TouchInputMapper::dumpCalibration(std::string& dump) {
4145 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146
4147 // Size
4148 switch (mCalibration.sizeCalibration) {
4149 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004150 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 break;
4152 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004153 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 break;
4155 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 break;
4158 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004159 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 break;
4161 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004162 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 break;
4164 default:
4165 ALOG_ASSERT(false);
4166 }
4167
4168 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004169 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 mCalibration.sizeScale);
4171 }
4172
4173 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004174 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 mCalibration.sizeBias);
4176 }
4177
4178 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004179 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 toString(mCalibration.sizeIsSummed));
4181 }
4182
4183 // Pressure
4184 switch (mCalibration.pressureCalibration) {
4185 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004186 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 break;
4188 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004189 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 break;
4191 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 break;
4194 default:
4195 ALOG_ASSERT(false);
4196 }
4197
4198 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004199 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 mCalibration.pressureScale);
4201 }
4202
4203 // Orientation
4204 switch (mCalibration.orientationCalibration) {
4205 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004206 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 break;
4208 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004209 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 break;
4211 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 break;
4214 default:
4215 ALOG_ASSERT(false);
4216 }
4217
4218 // Distance
4219 switch (mCalibration.distanceCalibration) {
4220 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004221 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 break;
4223 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004224 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 break;
4226 default:
4227 ALOG_ASSERT(false);
4228 }
4229
4230 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004231 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 mCalibration.distanceScale);
4233 }
4234
4235 switch (mCalibration.coverageCalibration) {
4236 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004237 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 break;
4239 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004240 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 break;
4242 default:
4243 ALOG_ASSERT(false);
4244 }
4245}
4246
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004247void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4248 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004249
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004250 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4251 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4252 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4253 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4254 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4255 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004256}
4257
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004258void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004259 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4260 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004261}
4262
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263void TouchInputMapper::reset(nsecs_t when) {
4264 mCursorButtonAccumulator.reset(getDevice());
4265 mCursorScrollAccumulator.reset(getDevice());
4266 mTouchButtonAccumulator.reset(getDevice());
4267
4268 mPointerVelocityControl.reset();
4269 mWheelXVelocityControl.reset();
4270 mWheelYVelocityControl.reset();
4271
Michael Wright842500e2015-03-13 17:32:02 -07004272 mRawStatesPending.clear();
4273 mCurrentRawState.clear();
4274 mCurrentCookedState.clear();
4275 mLastRawState.clear();
4276 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 mPointerUsage = POINTER_USAGE_NONE;
4278 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004279 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004280 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 mDownTime = 0;
4282
4283 mCurrentVirtualKey.down = false;
4284
4285 mPointerGesture.reset();
4286 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004287 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288
4289 if (mPointerController != NULL) {
4290 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4291 mPointerController->clearSpots();
4292 }
4293
4294 InputMapper::reset(when);
4295}
4296
Michael Wright842500e2015-03-13 17:32:02 -07004297void TouchInputMapper::resetExternalStylus() {
4298 mExternalStylusState.clear();
4299 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004300 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004301 mExternalStylusDataPending = false;
4302}
4303
Michael Wright43fd19f2015-04-21 19:02:58 +01004304void TouchInputMapper::clearStylusDataPendingFlags() {
4305 mExternalStylusDataPending = false;
4306 mExternalStylusFusionTimeout = LLONG_MAX;
4307}
4308
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309void TouchInputMapper::process(const RawEvent* rawEvent) {
4310 mCursorButtonAccumulator.process(rawEvent);
4311 mCursorScrollAccumulator.process(rawEvent);
4312 mTouchButtonAccumulator.process(rawEvent);
4313
4314 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4315 sync(rawEvent->when);
4316 }
4317}
4318
4319void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004320 const RawState* last = mRawStatesPending.isEmpty() ?
4321 &mCurrentRawState : &mRawStatesPending.top();
4322
4323 // Push a new state.
4324 mRawStatesPending.push();
4325 RawState* next = &mRawStatesPending.editTop();
4326 next->clear();
4327 next->when = when;
4328
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004330 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 | mCursorButtonAccumulator.getButtonState();
4332
Michael Wright842500e2015-03-13 17:32:02 -07004333 // Sync scroll
4334 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4335 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 mCursorScrollAccumulator.finishSync();
4337
Michael Wright842500e2015-03-13 17:32:02 -07004338 // Sync touch
4339 syncTouch(when, next);
4340
4341 // Assign pointer ids.
4342 if (!mHavePointerIds) {
4343 assignPointerIds(last, next);
4344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345
4346#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004347 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4348 "hovering ids 0x%08x -> 0x%08x",
4349 last->rawPointerData.pointerCount,
4350 next->rawPointerData.pointerCount,
4351 last->rawPointerData.touchingIdBits.value,
4352 next->rawPointerData.touchingIdBits.value,
4353 last->rawPointerData.hoveringIdBits.value,
4354 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355#endif
4356
Michael Wright842500e2015-03-13 17:32:02 -07004357 processRawTouches(false /*timeout*/);
4358}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359
Michael Wright842500e2015-03-13 17:32:02 -07004360void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4362 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004363 mCurrentRawState.clear();
4364 mRawStatesPending.clear();
4365 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 }
4367
Michael Wright842500e2015-03-13 17:32:02 -07004368 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4369 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4370 // touching the current state will only observe the events that have been dispatched to the
4371 // rest of the pipeline.
4372 const size_t N = mRawStatesPending.size();
4373 size_t count;
4374 for(count = 0; count < N; count++) {
4375 const RawState& next = mRawStatesPending[count];
4376
4377 // A failure to assign the stylus id means that we're waiting on stylus data
4378 // and so should defer the rest of the pipeline.
4379 if (assignExternalStylusId(next, timeout)) {
4380 break;
4381 }
4382
4383 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004384 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004385 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004386 if (mCurrentRawState.when < mLastRawState.when) {
4387 mCurrentRawState.when = mLastRawState.when;
4388 }
Michael Wright842500e2015-03-13 17:32:02 -07004389 cookAndDispatch(mCurrentRawState.when);
4390 }
4391 if (count != 0) {
4392 mRawStatesPending.removeItemsAt(0, count);
4393 }
4394
Michael Wright842500e2015-03-13 17:32:02 -07004395 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004396 if (timeout) {
4397 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4398 clearStylusDataPendingFlags();
4399 mCurrentRawState.copyFrom(mLastRawState);
4400#if DEBUG_STYLUS_FUSION
4401 ALOGD("Timeout expired, synthesizing event with new stylus data");
4402#endif
4403 cookAndDispatch(when);
4404 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4405 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4406 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4407 }
Michael Wright842500e2015-03-13 17:32:02 -07004408 }
4409}
4410
4411void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4412 // Always start with a clean state.
4413 mCurrentCookedState.clear();
4414
4415 // Apply stylus buttons to current raw state.
4416 applyExternalStylusButtonState(when);
4417
4418 // Handle policy on initial down or hover events.
4419 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4420 && mCurrentRawState.rawPointerData.pointerCount != 0;
4421
4422 uint32_t policyFlags = 0;
4423 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4424 if (initialDown || buttonsPressed) {
4425 // If this is a touch screen, hide the pointer on an initial down.
4426 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4427 getContext()->fadePointer();
4428 }
4429
4430 if (mParameters.wake) {
4431 policyFlags |= POLICY_FLAG_WAKE;
4432 }
4433 }
4434
4435 // Consume raw off-screen touches before cooking pointer data.
4436 // If touches are consumed, subsequent code will not receive any pointer data.
4437 if (consumeRawTouches(when, policyFlags)) {
4438 mCurrentRawState.rawPointerData.clear();
4439 }
4440
4441 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4442 // with cooked pointer data that has the same ids and indices as the raw data.
4443 // The following code can use either the raw or cooked data, as needed.
4444 cookPointerData();
4445
4446 // Apply stylus pressure to current cooked state.
4447 applyExternalStylusTouchState(when);
4448
4449 // Synthesize key down from raw buttons if needed.
4450 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004451 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004452
4453 // Dispatch the touches either directly or by translation through a pointer on screen.
4454 if (mDeviceMode == DEVICE_MODE_POINTER) {
4455 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4456 !idBits.isEmpty(); ) {
4457 uint32_t id = idBits.clearFirstMarkedBit();
4458 const RawPointerData::Pointer& pointer =
4459 mCurrentRawState.rawPointerData.pointerForId(id);
4460 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4461 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4462 mCurrentCookedState.stylusIdBits.markBit(id);
4463 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4464 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4465 mCurrentCookedState.fingerIdBits.markBit(id);
4466 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4467 mCurrentCookedState.mouseIdBits.markBit(id);
4468 }
4469 }
4470 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4471 !idBits.isEmpty(); ) {
4472 uint32_t id = idBits.clearFirstMarkedBit();
4473 const RawPointerData::Pointer& pointer =
4474 mCurrentRawState.rawPointerData.pointerForId(id);
4475 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4476 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4477 mCurrentCookedState.stylusIdBits.markBit(id);
4478 }
4479 }
4480
4481 // Stylus takes precedence over all tools, then mouse, then finger.
4482 PointerUsage pointerUsage = mPointerUsage;
4483 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4484 mCurrentCookedState.mouseIdBits.clear();
4485 mCurrentCookedState.fingerIdBits.clear();
4486 pointerUsage = POINTER_USAGE_STYLUS;
4487 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4488 mCurrentCookedState.fingerIdBits.clear();
4489 pointerUsage = POINTER_USAGE_MOUSE;
4490 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4491 isPointerDown(mCurrentRawState.buttonState)) {
4492 pointerUsage = POINTER_USAGE_GESTURES;
4493 }
4494
4495 dispatchPointerUsage(when, policyFlags, pointerUsage);
4496 } else {
4497 if (mDeviceMode == DEVICE_MODE_DIRECT
4498 && mConfig.showTouches && mPointerController != NULL) {
4499 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4500 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4501
4502 mPointerController->setButtonState(mCurrentRawState.buttonState);
4503 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4504 mCurrentCookedState.cookedPointerData.idToIndex,
4505 mCurrentCookedState.cookedPointerData.touchingIdBits);
4506 }
4507
Michael Wright8e812822015-06-22 16:18:21 +01004508 if (!mCurrentMotionAborted) {
4509 dispatchButtonRelease(when, policyFlags);
4510 dispatchHoverExit(when, policyFlags);
4511 dispatchTouches(when, policyFlags);
4512 dispatchHoverEnterAndMove(when, policyFlags);
4513 dispatchButtonPress(when, policyFlags);
4514 }
4515
4516 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4517 mCurrentMotionAborted = false;
4518 }
Michael Wright842500e2015-03-13 17:32:02 -07004519 }
4520
4521 // Synthesize key up from raw buttons if needed.
4522 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004523 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004524
4525 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004526 mCurrentRawState.rawVScroll = 0;
4527 mCurrentRawState.rawHScroll = 0;
4528
4529 // Copy current touch to last touch in preparation for the next cycle.
4530 mLastRawState.copyFrom(mCurrentRawState);
4531 mLastCookedState.copyFrom(mCurrentCookedState);
4532}
4533
4534void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004535 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004536 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4537 }
4538}
4539
4540void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004541 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4542 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004543
Michael Wright53dca3a2015-04-23 17:39:53 +01004544 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4545 float pressure = mExternalStylusState.pressure;
4546 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4547 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4548 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4549 }
4550 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4551 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4552
4553 PointerProperties& properties =
4554 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004555 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4556 properties.toolType = mExternalStylusState.toolType;
4557 }
4558 }
4559}
4560
4561bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4562 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4563 return false;
4564 }
4565
4566 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4567 && state.rawPointerData.pointerCount != 0;
4568 if (initialDown) {
4569 if (mExternalStylusState.pressure != 0.0f) {
4570#if DEBUG_STYLUS_FUSION
4571 ALOGD("Have both stylus and touch data, beginning fusion");
4572#endif
4573 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4574 } else if (timeout) {
4575#if DEBUG_STYLUS_FUSION
4576 ALOGD("Timeout expired, assuming touch is not a stylus.");
4577#endif
4578 resetExternalStylus();
4579 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004580 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4581 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004582 }
4583#if DEBUG_STYLUS_FUSION
4584 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004585 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004586#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004587 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004588 return true;
4589 }
4590 }
4591
4592 // Check if the stylus pointer has gone up.
4593 if (mExternalStylusId != -1 &&
4594 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4595#if DEBUG_STYLUS_FUSION
4596 ALOGD("Stylus pointer is going up");
4597#endif
4598 mExternalStylusId = -1;
4599 }
4600
4601 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004602}
4603
4604void TouchInputMapper::timeoutExpired(nsecs_t when) {
4605 if (mDeviceMode == DEVICE_MODE_POINTER) {
4606 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4607 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4608 }
Michael Wright842500e2015-03-13 17:32:02 -07004609 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004610 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004611 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004612 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4613 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004614 }
4615 }
4616}
4617
4618void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004619 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004620 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004621 // We're either in the middle of a fused stream of data or we're waiting on data before
4622 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4623 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004624 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004625 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626 }
4627}
4628
4629bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4630 // Check for release of a virtual key.
4631 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004632 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004633 // Pointer went up while virtual key was down.
4634 mCurrentVirtualKey.down = false;
4635 if (!mCurrentVirtualKey.ignored) {
4636#if DEBUG_VIRTUAL_KEYS
4637 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4638 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4639#endif
4640 dispatchVirtualKey(when, policyFlags,
4641 AKEY_EVENT_ACTION_UP,
4642 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4643 }
4644 return true;
4645 }
4646
Michael Wright842500e2015-03-13 17:32:02 -07004647 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4648 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4649 const RawPointerData::Pointer& pointer =
4650 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4652 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4653 // Pointer is still within the space of the virtual key.
4654 return true;
4655 }
4656 }
4657
4658 // Pointer left virtual key area or another pointer also went down.
4659 // Send key cancellation but do not consume the touch yet.
4660 // This is useful when the user swipes through from the virtual key area
4661 // into the main display surface.
4662 mCurrentVirtualKey.down = false;
4663 if (!mCurrentVirtualKey.ignored) {
4664#if DEBUG_VIRTUAL_KEYS
4665 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4666 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4667#endif
4668 dispatchVirtualKey(when, policyFlags,
4669 AKEY_EVENT_ACTION_UP,
4670 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4671 | AKEY_EVENT_FLAG_CANCELED);
4672 }
4673 }
4674
Michael Wright842500e2015-03-13 17:32:02 -07004675 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4676 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004678 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4679 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004680 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4681 // If exactly one pointer went down, check for virtual key hit.
4682 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004683 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4685 if (virtualKey) {
4686 mCurrentVirtualKey.down = true;
4687 mCurrentVirtualKey.downTime = when;
4688 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4689 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4690 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4691 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4692
4693 if (!mCurrentVirtualKey.ignored) {
4694#if DEBUG_VIRTUAL_KEYS
4695 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4696 mCurrentVirtualKey.keyCode,
4697 mCurrentVirtualKey.scanCode);
4698#endif
4699 dispatchVirtualKey(when, policyFlags,
4700 AKEY_EVENT_ACTION_DOWN,
4701 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4702 }
4703 }
4704 }
4705 return true;
4706 }
4707 }
4708
4709 // Disable all virtual key touches that happen within a short time interval of the
4710 // most recent touch within the screen area. The idea is to filter out stray
4711 // virtual key presses when interacting with the touch screen.
4712 //
4713 // Problems we're trying to solve:
4714 //
4715 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4716 // virtual key area that is implemented by a separate touch panel and accidentally
4717 // triggers a virtual key.
4718 //
4719 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4720 // area and accidentally triggers a virtual key. This often happens when virtual keys
4721 // are layed out below the screen near to where the on screen keyboard's space bar
4722 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004723 if (mConfig.virtualKeyQuietTime > 0 &&
4724 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4726 }
4727 return false;
4728}
4729
4730void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4731 int32_t keyEventAction, int32_t keyEventFlags) {
4732 int32_t keyCode = mCurrentVirtualKey.keyCode;
4733 int32_t scanCode = mCurrentVirtualKey.scanCode;
4734 nsecs_t downTime = mCurrentVirtualKey.downTime;
4735 int32_t metaState = mContext->getGlobalMetaState();
4736 policyFlags |= POLICY_FLAG_VIRTUAL;
4737
4738 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4739 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4740 getListener()->notifyKey(&args);
4741}
4742
Michael Wright8e812822015-06-22 16:18:21 +01004743void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4744 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4745 if (!currentIdBits.isEmpty()) {
4746 int32_t metaState = getContext()->getGlobalMetaState();
4747 int32_t buttonState = mCurrentCookedState.buttonState;
4748 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4749 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004750 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004751 mCurrentCookedState.cookedPointerData.pointerProperties,
4752 mCurrentCookedState.cookedPointerData.pointerCoords,
4753 mCurrentCookedState.cookedPointerData.idToIndex,
4754 currentIdBits, -1,
4755 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4756 mCurrentMotionAborted = true;
4757 }
4758}
4759
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004761 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4762 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004763 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004764 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765
4766 if (currentIdBits == lastIdBits) {
4767 if (!currentIdBits.isEmpty()) {
4768 // No pointer id changes so this is a move event.
4769 // The listener takes care of batching moves so we don't have to deal with that here.
4770 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004771 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004773 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004774 mCurrentCookedState.cookedPointerData.pointerProperties,
4775 mCurrentCookedState.cookedPointerData.pointerCoords,
4776 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777 currentIdBits, -1,
4778 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4779 }
4780 } else {
4781 // There may be pointers going up and pointers going down and pointers moving
4782 // all at the same time.
4783 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4784 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4785 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4786 BitSet32 dispatchedIdBits(lastIdBits.value);
4787
4788 // Update last coordinates of pointers that have moved so that we observe the new
4789 // pointer positions at the same time as other pointers that have just gone up.
4790 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004791 mCurrentCookedState.cookedPointerData.pointerProperties,
4792 mCurrentCookedState.cookedPointerData.pointerCoords,
4793 mCurrentCookedState.cookedPointerData.idToIndex,
4794 mLastCookedState.cookedPointerData.pointerProperties,
4795 mLastCookedState.cookedPointerData.pointerCoords,
4796 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004798 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 moveNeeded = true;
4800 }
4801
4802 // Dispatch pointer up events.
4803 while (!upIdBits.isEmpty()) {
4804 uint32_t upId = upIdBits.clearFirstMarkedBit();
4805
4806 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004807 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004808 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004809 mLastCookedState.cookedPointerData.pointerProperties,
4810 mLastCookedState.cookedPointerData.pointerCoords,
4811 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004812 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 dispatchedIdBits.clearBit(upId);
4814 }
4815
4816 // Dispatch move events if any of the remaining pointers moved from their old locations.
4817 // Although applications receive new locations as part of individual pointer up
4818 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004819 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4821 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004822 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004823 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004824 mCurrentCookedState.cookedPointerData.pointerProperties,
4825 mCurrentCookedState.cookedPointerData.pointerCoords,
4826 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004827 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 }
4829
4830 // Dispatch pointer down events using the new pointer locations.
4831 while (!downIdBits.isEmpty()) {
4832 uint32_t downId = downIdBits.clearFirstMarkedBit();
4833 dispatchedIdBits.markBit(downId);
4834
4835 if (dispatchedIdBits.count() == 1) {
4836 // First pointer is going down. Set down time.
4837 mDownTime = when;
4838 }
4839
4840 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004841 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004842 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004843 mCurrentCookedState.cookedPointerData.pointerProperties,
4844 mCurrentCookedState.cookedPointerData.pointerCoords,
4845 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004846 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 }
4848 }
4849}
4850
4851void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4852 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004853 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4854 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 int32_t metaState = getContext()->getGlobalMetaState();
4856 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004857 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004858 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004859 mLastCookedState.cookedPointerData.pointerProperties,
4860 mLastCookedState.cookedPointerData.pointerCoords,
4861 mLastCookedState.cookedPointerData.idToIndex,
4862 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4864 mSentHoverEnter = false;
4865 }
4866}
4867
4868void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004869 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4870 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 int32_t metaState = getContext()->getGlobalMetaState();
4872 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004873 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004874 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004875 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004876 mCurrentCookedState.cookedPointerData.pointerProperties,
4877 mCurrentCookedState.cookedPointerData.pointerCoords,
4878 mCurrentCookedState.cookedPointerData.idToIndex,
4879 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004880 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4881 mSentHoverEnter = true;
4882 }
4883
4884 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004885 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004886 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004887 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004888 mCurrentCookedState.cookedPointerData.pointerProperties,
4889 mCurrentCookedState.cookedPointerData.pointerCoords,
4890 mCurrentCookedState.cookedPointerData.idToIndex,
4891 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004892 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4893 }
4894}
4895
Michael Wright7b159c92015-05-14 14:48:03 +01004896void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4897 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4898 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4899 const int32_t metaState = getContext()->getGlobalMetaState();
4900 int32_t buttonState = mLastCookedState.buttonState;
4901 while (!releasedButtons.isEmpty()) {
4902 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4903 buttonState &= ~actionButton;
4904 dispatchMotion(when, policyFlags, mSource,
4905 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4906 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004907 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004908 mCurrentCookedState.cookedPointerData.pointerProperties,
4909 mCurrentCookedState.cookedPointerData.pointerCoords,
4910 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4911 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4912 }
4913}
4914
4915void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4916 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4917 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4918 const int32_t metaState = getContext()->getGlobalMetaState();
4919 int32_t buttonState = mLastCookedState.buttonState;
4920 while (!pressedButtons.isEmpty()) {
4921 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4922 buttonState |= actionButton;
4923 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4924 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004925 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004926 mCurrentCookedState.cookedPointerData.pointerProperties,
4927 mCurrentCookedState.cookedPointerData.pointerCoords,
4928 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4929 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4930 }
4931}
4932
4933const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4934 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4935 return cookedPointerData.touchingIdBits;
4936 }
4937 return cookedPointerData.hoveringIdBits;
4938}
4939
Michael Wrightd02c5b62014-02-10 15:10:22 -08004940void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004941 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942
Michael Wright842500e2015-03-13 17:32:02 -07004943 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004944 mCurrentCookedState.deviceTimestamp =
4945 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004946 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4947 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4948 mCurrentRawState.rawPointerData.hoveringIdBits;
4949 mCurrentCookedState.cookedPointerData.touchingIdBits =
4950 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004951
Michael Wright7b159c92015-05-14 14:48:03 +01004952 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4953 mCurrentCookedState.buttonState = 0;
4954 } else {
4955 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4956 }
4957
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958 // Walk through the the active pointers and map device coordinates onto
4959 // surface coordinates and adjust for display orientation.
4960 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004961 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962
4963 // Size
4964 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4965 switch (mCalibration.sizeCalibration) {
4966 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4967 case Calibration::SIZE_CALIBRATION_DIAMETER:
4968 case Calibration::SIZE_CALIBRATION_BOX:
4969 case Calibration::SIZE_CALIBRATION_AREA:
4970 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4971 touchMajor = in.touchMajor;
4972 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4973 toolMajor = in.toolMajor;
4974 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4975 size = mRawPointerAxes.touchMinor.valid
4976 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4977 } else if (mRawPointerAxes.touchMajor.valid) {
4978 toolMajor = touchMajor = in.touchMajor;
4979 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4980 ? in.touchMinor : in.touchMajor;
4981 size = mRawPointerAxes.touchMinor.valid
4982 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4983 } else if (mRawPointerAxes.toolMajor.valid) {
4984 touchMajor = toolMajor = in.toolMajor;
4985 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4986 ? in.toolMinor : in.toolMajor;
4987 size = mRawPointerAxes.toolMinor.valid
4988 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4989 } else {
4990 ALOG_ASSERT(false, "No touch or tool axes. "
4991 "Size calibration should have been resolved to NONE.");
4992 touchMajor = 0;
4993 touchMinor = 0;
4994 toolMajor = 0;
4995 toolMinor = 0;
4996 size = 0;
4997 }
4998
4999 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005000 uint32_t touchingCount =
5001 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002 if (touchingCount > 1) {
5003 touchMajor /= touchingCount;
5004 touchMinor /= touchingCount;
5005 toolMajor /= touchingCount;
5006 toolMinor /= touchingCount;
5007 size /= touchingCount;
5008 }
5009 }
5010
5011 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5012 touchMajor *= mGeometricScale;
5013 touchMinor *= mGeometricScale;
5014 toolMajor *= mGeometricScale;
5015 toolMinor *= mGeometricScale;
5016 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5017 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5018 touchMinor = touchMajor;
5019 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5020 toolMinor = toolMajor;
5021 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5022 touchMinor = touchMajor;
5023 toolMinor = toolMajor;
5024 }
5025
5026 mCalibration.applySizeScaleAndBias(&touchMajor);
5027 mCalibration.applySizeScaleAndBias(&touchMinor);
5028 mCalibration.applySizeScaleAndBias(&toolMajor);
5029 mCalibration.applySizeScaleAndBias(&toolMinor);
5030 size *= mSizeScale;
5031 break;
5032 default:
5033 touchMajor = 0;
5034 touchMinor = 0;
5035 toolMajor = 0;
5036 toolMinor = 0;
5037 size = 0;
5038 break;
5039 }
5040
5041 // Pressure
5042 float pressure;
5043 switch (mCalibration.pressureCalibration) {
5044 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5045 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5046 pressure = in.pressure * mPressureScale;
5047 break;
5048 default:
5049 pressure = in.isHovering ? 0 : 1;
5050 break;
5051 }
5052
5053 // Tilt and Orientation
5054 float tilt;
5055 float orientation;
5056 if (mHaveTilt) {
5057 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5058 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5059 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5060 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5061 } else {
5062 tilt = 0;
5063
5064 switch (mCalibration.orientationCalibration) {
5065 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5066 orientation = in.orientation * mOrientationScale;
5067 break;
5068 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5069 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5070 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5071 if (c1 != 0 || c2 != 0) {
5072 orientation = atan2f(c1, c2) * 0.5f;
5073 float confidence = hypotf(c1, c2);
5074 float scale = 1.0f + confidence / 16.0f;
5075 touchMajor *= scale;
5076 touchMinor /= scale;
5077 toolMajor *= scale;
5078 toolMinor /= scale;
5079 } else {
5080 orientation = 0;
5081 }
5082 break;
5083 }
5084 default:
5085 orientation = 0;
5086 }
5087 }
5088
5089 // Distance
5090 float distance;
5091 switch (mCalibration.distanceCalibration) {
5092 case Calibration::DISTANCE_CALIBRATION_SCALED:
5093 distance = in.distance * mDistanceScale;
5094 break;
5095 default:
5096 distance = 0;
5097 }
5098
5099 // Coverage
5100 int32_t rawLeft, rawTop, rawRight, rawBottom;
5101 switch (mCalibration.coverageCalibration) {
5102 case Calibration::COVERAGE_CALIBRATION_BOX:
5103 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5104 rawRight = in.toolMinor & 0x0000ffff;
5105 rawBottom = in.toolMajor & 0x0000ffff;
5106 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5107 break;
5108 default:
5109 rawLeft = rawTop = rawRight = rawBottom = 0;
5110 break;
5111 }
5112
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005113 // Adjust X,Y coords for device calibration
5114 // TODO: Adjust coverage coords?
5115 float xTransformed = in.x, yTransformed = in.y;
5116 mAffineTransform.applyTo(xTransformed, yTransformed);
5117
5118 // Adjust X, Y, and coverage coords for surface orientation.
5119 float x, y;
5120 float left, top, right, bottom;
5121
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122 switch (mSurfaceOrientation) {
5123 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005124 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5125 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005126 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5127 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5128 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5129 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5130 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005131 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5133 }
5134 break;
5135 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005136 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005137 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005138 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5139 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5141 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5142 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005143 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005144 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5145 }
5146 break;
5147 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005148 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005149 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005150 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5151 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5153 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5154 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005155 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5157 }
5158 break;
5159 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005160 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5161 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005162 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5163 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5164 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5165 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5166 break;
5167 }
5168
5169 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005170 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 out.clear();
5172 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5173 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5174 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5175 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5176 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5177 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5178 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5179 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5180 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5181 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5182 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5183 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5184 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5185 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5186 } else {
5187 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5188 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5189 }
5190
5191 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005192 PointerProperties& properties =
5193 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005194 uint32_t id = in.id;
5195 properties.clear();
5196 properties.id = id;
5197 properties.toolType = in.toolType;
5198
5199 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005200 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005201 }
5202}
5203
5204void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5205 PointerUsage pointerUsage) {
5206 if (pointerUsage != mPointerUsage) {
5207 abortPointerUsage(when, policyFlags);
5208 mPointerUsage = pointerUsage;
5209 }
5210
5211 switch (mPointerUsage) {
5212 case POINTER_USAGE_GESTURES:
5213 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5214 break;
5215 case POINTER_USAGE_STYLUS:
5216 dispatchPointerStylus(when, policyFlags);
5217 break;
5218 case POINTER_USAGE_MOUSE:
5219 dispatchPointerMouse(when, policyFlags);
5220 break;
5221 default:
5222 break;
5223 }
5224}
5225
5226void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5227 switch (mPointerUsage) {
5228 case POINTER_USAGE_GESTURES:
5229 abortPointerGestures(when, policyFlags);
5230 break;
5231 case POINTER_USAGE_STYLUS:
5232 abortPointerStylus(when, policyFlags);
5233 break;
5234 case POINTER_USAGE_MOUSE:
5235 abortPointerMouse(when, policyFlags);
5236 break;
5237 default:
5238 break;
5239 }
5240
5241 mPointerUsage = POINTER_USAGE_NONE;
5242}
5243
5244void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5245 bool isTimeout) {
5246 // Update current gesture coordinates.
5247 bool cancelPreviousGesture, finishPreviousGesture;
5248 bool sendEvents = preparePointerGestures(when,
5249 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5250 if (!sendEvents) {
5251 return;
5252 }
5253 if (finishPreviousGesture) {
5254 cancelPreviousGesture = false;
5255 }
5256
5257 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005258 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5259 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260 if (finishPreviousGesture || cancelPreviousGesture) {
5261 mPointerController->clearSpots();
5262 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005263
5264 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5265 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5266 mPointerGesture.currentGestureIdToIndex,
5267 mPointerGesture.currentGestureIdBits);
5268 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269 } else {
5270 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5271 }
5272
5273 // Show or hide the pointer if needed.
5274 switch (mPointerGesture.currentGestureMode) {
5275 case PointerGesture::NEUTRAL:
5276 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005277 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5278 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279 // Remind the user of where the pointer is after finishing a gesture with spots.
5280 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5281 }
5282 break;
5283 case PointerGesture::TAP:
5284 case PointerGesture::TAP_DRAG:
5285 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5286 case PointerGesture::HOVER:
5287 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005288 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289 // Unfade the pointer when the current gesture manipulates the
5290 // area directly under the pointer.
5291 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5292 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293 case PointerGesture::FREEFORM:
5294 // Fade the pointer when the current gesture manipulates a different
5295 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005296 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005297 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5298 } else {
5299 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5300 }
5301 break;
5302 }
5303
5304 // Send events!
5305 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005306 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307
5308 // Update last coordinates of pointers that have moved so that we observe the new
5309 // pointer positions at the same time as other pointers that have just gone up.
5310 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5311 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5312 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5313 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5314 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5315 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5316 bool moveNeeded = false;
5317 if (down && !cancelPreviousGesture && !finishPreviousGesture
5318 && !mPointerGesture.lastGestureIdBits.isEmpty()
5319 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5320 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5321 & mPointerGesture.lastGestureIdBits.value);
5322 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5323 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5324 mPointerGesture.lastGestureProperties,
5325 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5326 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005327 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328 moveNeeded = true;
5329 }
5330 }
5331
5332 // Send motion events for all pointers that went up or were canceled.
5333 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5334 if (!dispatchedGestureIdBits.isEmpty()) {
5335 if (cancelPreviousGesture) {
5336 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005337 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005338 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 mPointerGesture.lastGestureProperties,
5340 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005341 dispatchedGestureIdBits, -1, 0,
5342 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343
5344 dispatchedGestureIdBits.clear();
5345 } else {
5346 BitSet32 upGestureIdBits;
5347 if (finishPreviousGesture) {
5348 upGestureIdBits = dispatchedGestureIdBits;
5349 } else {
5350 upGestureIdBits.value = dispatchedGestureIdBits.value
5351 & ~mPointerGesture.currentGestureIdBits.value;
5352 }
5353 while (!upGestureIdBits.isEmpty()) {
5354 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5355
5356 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005357 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005358 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005359 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360 mPointerGesture.lastGestureProperties,
5361 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5362 dispatchedGestureIdBits, id,
5363 0, 0, mPointerGesture.downTime);
5364
5365 dispatchedGestureIdBits.clearBit(id);
5366 }
5367 }
5368 }
5369
5370 // Send motion events for all pointers that moved.
5371 if (moveNeeded) {
5372 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005373 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005374 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 mPointerGesture.currentGestureProperties,
5376 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5377 dispatchedGestureIdBits, -1,
5378 0, 0, mPointerGesture.downTime);
5379 }
5380
5381 // Send motion events for all pointers that went down.
5382 if (down) {
5383 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5384 & ~dispatchedGestureIdBits.value);
5385 while (!downGestureIdBits.isEmpty()) {
5386 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5387 dispatchedGestureIdBits.markBit(id);
5388
5389 if (dispatchedGestureIdBits.count() == 1) {
5390 mPointerGesture.downTime = when;
5391 }
5392
5393 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005394 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005395 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 mPointerGesture.currentGestureProperties,
5397 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5398 dispatchedGestureIdBits, id,
5399 0, 0, mPointerGesture.downTime);
5400 }
5401 }
5402
5403 // Send motion events for hover.
5404 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5405 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005406 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005407 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 mPointerGesture.currentGestureProperties,
5409 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5410 mPointerGesture.currentGestureIdBits, -1,
5411 0, 0, mPointerGesture.downTime);
5412 } else if (dispatchedGestureIdBits.isEmpty()
5413 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5414 // Synthesize a hover move event after all pointers go up to indicate that
5415 // the pointer is hovering again even if the user is not currently touching
5416 // the touch pad. This ensures that a view will receive a fresh hover enter
5417 // event after a tap.
5418 float x, y;
5419 mPointerController->getPosition(&x, &y);
5420
5421 PointerProperties pointerProperties;
5422 pointerProperties.clear();
5423 pointerProperties.id = 0;
5424 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5425
5426 PointerCoords pointerCoords;
5427 pointerCoords.clear();
5428 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5429 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5430
5431 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005432 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005434 mViewport.displayId, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435 0, 0, mPointerGesture.downTime);
5436 getListener()->notifyMotion(&args);
5437 }
5438
5439 // Update state.
5440 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5441 if (!down) {
5442 mPointerGesture.lastGestureIdBits.clear();
5443 } else {
5444 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5445 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5446 uint32_t id = idBits.clearFirstMarkedBit();
5447 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5448 mPointerGesture.lastGestureProperties[index].copyFrom(
5449 mPointerGesture.currentGestureProperties[index]);
5450 mPointerGesture.lastGestureCoords[index].copyFrom(
5451 mPointerGesture.currentGestureCoords[index]);
5452 mPointerGesture.lastGestureIdToIndex[id] = index;
5453 }
5454 }
5455}
5456
5457void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5458 // Cancel previously dispatches pointers.
5459 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5460 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005461 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005462 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005463 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005464 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005465 mPointerGesture.lastGestureProperties,
5466 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5467 mPointerGesture.lastGestureIdBits, -1,
5468 0, 0, mPointerGesture.downTime);
5469 }
5470
5471 // Reset the current pointer gesture.
5472 mPointerGesture.reset();
5473 mPointerVelocityControl.reset();
5474
5475 // Remove any current spots.
5476 if (mPointerController != NULL) {
5477 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5478 mPointerController->clearSpots();
5479 }
5480}
5481
5482bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5483 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5484 *outCancelPreviousGesture = false;
5485 *outFinishPreviousGesture = false;
5486
5487 // Handle TAP timeout.
5488 if (isTimeout) {
5489#if DEBUG_GESTURES
5490 ALOGD("Gestures: Processing timeout");
5491#endif
5492
5493 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5494 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5495 // The tap/drag timeout has not yet expired.
5496 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5497 + mConfig.pointerGestureTapDragInterval);
5498 } else {
5499 // The tap is finished.
5500#if DEBUG_GESTURES
5501 ALOGD("Gestures: TAP finished");
5502#endif
5503 *outFinishPreviousGesture = true;
5504
5505 mPointerGesture.activeGestureId = -1;
5506 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5507 mPointerGesture.currentGestureIdBits.clear();
5508
5509 mPointerVelocityControl.reset();
5510 return true;
5511 }
5512 }
5513
5514 // We did not handle this timeout.
5515 return false;
5516 }
5517
Michael Wright842500e2015-03-13 17:32:02 -07005518 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5519 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520
5521 // Update the velocity tracker.
5522 {
5523 VelocityTracker::Position positions[MAX_POINTERS];
5524 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005525 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005526 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005527 const RawPointerData::Pointer& pointer =
5528 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529 positions[count].x = pointer.x * mPointerXMovementScale;
5530 positions[count].y = pointer.y * mPointerYMovementScale;
5531 }
5532 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005533 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 }
5535
5536 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5537 // to NEUTRAL, then we should not generate tap event.
5538 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5539 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5540 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5541 mPointerGesture.resetTap();
5542 }
5543
5544 // Pick a new active touch id if needed.
5545 // Choose an arbitrary pointer that just went down, if there is one.
5546 // Otherwise choose an arbitrary remaining pointer.
5547 // This guarantees we always have an active touch id when there is at least one pointer.
5548 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5550 int32_t activeTouchId = lastActiveTouchId;
5551 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005552 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005553 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005554 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555 mPointerGesture.firstTouchTime = when;
5556 }
Michael Wright842500e2015-03-13 17:32:02 -07005557 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005558 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005559 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005560 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005561 } else {
5562 activeTouchId = mPointerGesture.activeTouchId = -1;
5563 }
5564 }
5565
5566 // Determine whether we are in quiet time.
5567 bool isQuietTime = false;
5568 if (activeTouchId < 0) {
5569 mPointerGesture.resetQuietTime();
5570 } else {
5571 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5572 if (!isQuietTime) {
5573 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5574 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5575 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5576 && currentFingerCount < 2) {
5577 // Enter quiet time when exiting swipe or freeform state.
5578 // This is to prevent accidentally entering the hover state and flinging the
5579 // pointer when finishing a swipe and there is still one pointer left onscreen.
5580 isQuietTime = true;
5581 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5582 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005583 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005584 // Enter quiet time when releasing the button and there are still two or more
5585 // fingers down. This may indicate that one finger was used to press the button
5586 // but it has not gone up yet.
5587 isQuietTime = true;
5588 }
5589 if (isQuietTime) {
5590 mPointerGesture.quietTime = when;
5591 }
5592 }
5593 }
5594
5595 // Switch states based on button and pointer state.
5596 if (isQuietTime) {
5597 // Case 1: Quiet time. (QUIET)
5598#if DEBUG_GESTURES
5599 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5600 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5601#endif
5602 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5603 *outFinishPreviousGesture = true;
5604 }
5605
5606 mPointerGesture.activeGestureId = -1;
5607 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5608 mPointerGesture.currentGestureIdBits.clear();
5609
5610 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005611 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5613 // The pointer follows the active touch point.
5614 // Emit DOWN, MOVE, UP events at the pointer location.
5615 //
5616 // Only the active touch matters; other fingers are ignored. This policy helps
5617 // to handle the case where the user places a second finger on the touch pad
5618 // to apply the necessary force to depress an integrated button below the surface.
5619 // We don't want the second finger to be delivered to applications.
5620 //
5621 // For this to work well, we need to make sure to track the pointer that is really
5622 // active. If the user first puts one finger down to click then adds another
5623 // finger to drag then the active pointer should switch to the finger that is
5624 // being dragged.
5625#if DEBUG_GESTURES
5626 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5627 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5628#endif
5629 // Reset state when just starting.
5630 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5631 *outFinishPreviousGesture = true;
5632 mPointerGesture.activeGestureId = 0;
5633 }
5634
5635 // Switch pointers if needed.
5636 // Find the fastest pointer and follow it.
5637 if (activeTouchId >= 0 && currentFingerCount > 1) {
5638 int32_t bestId = -1;
5639 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005640 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641 uint32_t id = idBits.clearFirstMarkedBit();
5642 float vx, vy;
5643 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5644 float speed = hypotf(vx, vy);
5645 if (speed > bestSpeed) {
5646 bestId = id;
5647 bestSpeed = speed;
5648 }
5649 }
5650 }
5651 if (bestId >= 0 && bestId != activeTouchId) {
5652 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005653#if DEBUG_GESTURES
5654 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5655 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5656#endif
5657 }
5658 }
5659
Jun Mukaifa1706a2015-12-03 01:14:46 -08005660 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005661 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005662 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005663 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005665 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005666 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5667 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005668
5669 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5670 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5671
5672 // Move the pointer using a relative motion.
5673 // When using spots, the click will occur at the position of the anchor
5674 // spot and all other spots will move there.
5675 mPointerController->move(deltaX, deltaY);
5676 } else {
5677 mPointerVelocityControl.reset();
5678 }
5679
5680 float x, y;
5681 mPointerController->getPosition(&x, &y);
5682
5683 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5684 mPointerGesture.currentGestureIdBits.clear();
5685 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5686 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5687 mPointerGesture.currentGestureProperties[0].clear();
5688 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5689 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5690 mPointerGesture.currentGestureCoords[0].clear();
5691 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5692 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5693 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5694 } else if (currentFingerCount == 0) {
5695 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5696 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5697 *outFinishPreviousGesture = true;
5698 }
5699
5700 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5701 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5702 bool tapped = false;
5703 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5704 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5705 && lastFingerCount == 1) {
5706 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5707 float x, y;
5708 mPointerController->getPosition(&x, &y);
5709 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5710 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5711#if DEBUG_GESTURES
5712 ALOGD("Gestures: TAP");
5713#endif
5714
5715 mPointerGesture.tapUpTime = when;
5716 getContext()->requestTimeoutAtTime(when
5717 + mConfig.pointerGestureTapDragInterval);
5718
5719 mPointerGesture.activeGestureId = 0;
5720 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5721 mPointerGesture.currentGestureIdBits.clear();
5722 mPointerGesture.currentGestureIdBits.markBit(
5723 mPointerGesture.activeGestureId);
5724 mPointerGesture.currentGestureIdToIndex[
5725 mPointerGesture.activeGestureId] = 0;
5726 mPointerGesture.currentGestureProperties[0].clear();
5727 mPointerGesture.currentGestureProperties[0].id =
5728 mPointerGesture.activeGestureId;
5729 mPointerGesture.currentGestureProperties[0].toolType =
5730 AMOTION_EVENT_TOOL_TYPE_FINGER;
5731 mPointerGesture.currentGestureCoords[0].clear();
5732 mPointerGesture.currentGestureCoords[0].setAxisValue(
5733 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5734 mPointerGesture.currentGestureCoords[0].setAxisValue(
5735 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5736 mPointerGesture.currentGestureCoords[0].setAxisValue(
5737 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5738
5739 tapped = true;
5740 } else {
5741#if DEBUG_GESTURES
5742 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5743 x - mPointerGesture.tapX,
5744 y - mPointerGesture.tapY);
5745#endif
5746 }
5747 } else {
5748#if DEBUG_GESTURES
5749 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5750 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5751 (when - mPointerGesture.tapDownTime) * 0.000001f);
5752 } else {
5753 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5754 }
5755#endif
5756 }
5757 }
5758
5759 mPointerVelocityControl.reset();
5760
5761 if (!tapped) {
5762#if DEBUG_GESTURES
5763 ALOGD("Gestures: NEUTRAL");
5764#endif
5765 mPointerGesture.activeGestureId = -1;
5766 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5767 mPointerGesture.currentGestureIdBits.clear();
5768 }
5769 } else if (currentFingerCount == 1) {
5770 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5771 // The pointer follows the active touch point.
5772 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5773 // When in TAP_DRAG, emit MOVE events at the pointer location.
5774 ALOG_ASSERT(activeTouchId >= 0);
5775
5776 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5777 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5778 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5779 float x, y;
5780 mPointerController->getPosition(&x, &y);
5781 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5782 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5783 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5784 } else {
5785#if DEBUG_GESTURES
5786 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5787 x - mPointerGesture.tapX,
5788 y - mPointerGesture.tapY);
5789#endif
5790 }
5791 } else {
5792#if DEBUG_GESTURES
5793 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5794 (when - mPointerGesture.tapUpTime) * 0.000001f);
5795#endif
5796 }
5797 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5798 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5799 }
5800
Jun Mukaifa1706a2015-12-03 01:14:46 -08005801 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005802 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005803 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005804 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005806 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005807 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5808 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005809
5810 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5811 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5812
5813 // Move the pointer using a relative motion.
5814 // When using spots, the hover or drag will occur at the position of the anchor spot.
5815 mPointerController->move(deltaX, deltaY);
5816 } else {
5817 mPointerVelocityControl.reset();
5818 }
5819
5820 bool down;
5821 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5822#if DEBUG_GESTURES
5823 ALOGD("Gestures: TAP_DRAG");
5824#endif
5825 down = true;
5826 } else {
5827#if DEBUG_GESTURES
5828 ALOGD("Gestures: HOVER");
5829#endif
5830 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5831 *outFinishPreviousGesture = true;
5832 }
5833 mPointerGesture.activeGestureId = 0;
5834 down = false;
5835 }
5836
5837 float x, y;
5838 mPointerController->getPosition(&x, &y);
5839
5840 mPointerGesture.currentGestureIdBits.clear();
5841 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5842 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5843 mPointerGesture.currentGestureProperties[0].clear();
5844 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5845 mPointerGesture.currentGestureProperties[0].toolType =
5846 AMOTION_EVENT_TOOL_TYPE_FINGER;
5847 mPointerGesture.currentGestureCoords[0].clear();
5848 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5849 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5850 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5851 down ? 1.0f : 0.0f);
5852
5853 if (lastFingerCount == 0 && currentFingerCount != 0) {
5854 mPointerGesture.resetTap();
5855 mPointerGesture.tapDownTime = when;
5856 mPointerGesture.tapX = x;
5857 mPointerGesture.tapY = y;
5858 }
5859 } else {
5860 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5861 // We need to provide feedback for each finger that goes down so we cannot wait
5862 // for the fingers to move before deciding what to do.
5863 //
5864 // The ambiguous case is deciding what to do when there are two fingers down but they
5865 // have not moved enough to determine whether they are part of a drag or part of a
5866 // freeform gesture, or just a press or long-press at the pointer location.
5867 //
5868 // When there are two fingers we start with the PRESS hypothesis and we generate a
5869 // down at the pointer location.
5870 //
5871 // When the two fingers move enough or when additional fingers are added, we make
5872 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5873 ALOG_ASSERT(activeTouchId >= 0);
5874
5875 bool settled = when >= mPointerGesture.firstTouchTime
5876 + mConfig.pointerGestureMultitouchSettleInterval;
5877 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5878 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5879 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5880 *outFinishPreviousGesture = true;
5881 } else if (!settled && currentFingerCount > lastFingerCount) {
5882 // Additional pointers have gone down but not yet settled.
5883 // Reset the gesture.
5884#if DEBUG_GESTURES
5885 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5886 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5887 + mConfig.pointerGestureMultitouchSettleInterval - when)
5888 * 0.000001f);
5889#endif
5890 *outCancelPreviousGesture = true;
5891 } else {
5892 // Continue previous gesture.
5893 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5894 }
5895
5896 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5897 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5898 mPointerGesture.activeGestureId = 0;
5899 mPointerGesture.referenceIdBits.clear();
5900 mPointerVelocityControl.reset();
5901
5902 // Use the centroid and pointer location as the reference points for the gesture.
5903#if DEBUG_GESTURES
5904 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5905 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5906 + mConfig.pointerGestureMultitouchSettleInterval - when)
5907 * 0.000001f);
5908#endif
Michael Wright842500e2015-03-13 17:32:02 -07005909 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910 &mPointerGesture.referenceTouchX,
5911 &mPointerGesture.referenceTouchY);
5912 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5913 &mPointerGesture.referenceGestureY);
5914 }
5915
5916 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005917 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5919 uint32_t id = idBits.clearFirstMarkedBit();
5920 mPointerGesture.referenceDeltas[id].dx = 0;
5921 mPointerGesture.referenceDeltas[id].dy = 0;
5922 }
Michael Wright842500e2015-03-13 17:32:02 -07005923 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005924
5925 // Add delta for all fingers and calculate a common movement delta.
5926 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005927 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5928 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5930 bool first = (idBits == commonIdBits);
5931 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005932 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5933 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5935 delta.dx += cpd.x - lpd.x;
5936 delta.dy += cpd.y - lpd.y;
5937
5938 if (first) {
5939 commonDeltaX = delta.dx;
5940 commonDeltaY = delta.dy;
5941 } else {
5942 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5943 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5944 }
5945 }
5946
5947 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5948 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5949 float dist[MAX_POINTER_ID + 1];
5950 int32_t distOverThreshold = 0;
5951 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5952 uint32_t id = idBits.clearFirstMarkedBit();
5953 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5954 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5955 delta.dy * mPointerYZoomScale);
5956 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5957 distOverThreshold += 1;
5958 }
5959 }
5960
5961 // Only transition when at least two pointers have moved further than
5962 // the minimum distance threshold.
5963 if (distOverThreshold >= 2) {
5964 if (currentFingerCount > 2) {
5965 // There are more than two pointers, switch to FREEFORM.
5966#if DEBUG_GESTURES
5967 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5968 currentFingerCount);
5969#endif
5970 *outCancelPreviousGesture = true;
5971 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5972 } else {
5973 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005974 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005975 uint32_t id1 = idBits.clearFirstMarkedBit();
5976 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005977 const RawPointerData::Pointer& p1 =
5978 mCurrentRawState.rawPointerData.pointerForId(id1);
5979 const RawPointerData::Pointer& p2 =
5980 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005981 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5982 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5983 // There are two pointers but they are too far apart for a SWIPE,
5984 // switch to FREEFORM.
5985#if DEBUG_GESTURES
5986 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5987 mutualDistance, mPointerGestureMaxSwipeWidth);
5988#endif
5989 *outCancelPreviousGesture = true;
5990 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5991 } else {
5992 // There are two pointers. Wait for both pointers to start moving
5993 // before deciding whether this is a SWIPE or FREEFORM gesture.
5994 float dist1 = dist[id1];
5995 float dist2 = dist[id2];
5996 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5997 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5998 // Calculate the dot product of the displacement vectors.
5999 // When the vectors are oriented in approximately the same direction,
6000 // the angle betweeen them is near zero and the cosine of the angle
6001 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6002 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6003 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6004 float dx1 = delta1.dx * mPointerXZoomScale;
6005 float dy1 = delta1.dy * mPointerYZoomScale;
6006 float dx2 = delta2.dx * mPointerXZoomScale;
6007 float dy2 = delta2.dy * mPointerYZoomScale;
6008 float dot = dx1 * dx2 + dy1 * dy2;
6009 float cosine = dot / (dist1 * dist2); // denominator always > 0
6010 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6011 // Pointers are moving in the same direction. Switch to SWIPE.
6012#if DEBUG_GESTURES
6013 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6014 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6015 "cosine %0.3f >= %0.3f",
6016 dist1, mConfig.pointerGestureMultitouchMinDistance,
6017 dist2, mConfig.pointerGestureMultitouchMinDistance,
6018 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6019#endif
6020 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6021 } else {
6022 // Pointers are moving in different directions. Switch to FREEFORM.
6023#if DEBUG_GESTURES
6024 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6025 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6026 "cosine %0.3f < %0.3f",
6027 dist1, mConfig.pointerGestureMultitouchMinDistance,
6028 dist2, mConfig.pointerGestureMultitouchMinDistance,
6029 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6030#endif
6031 *outCancelPreviousGesture = true;
6032 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6033 }
6034 }
6035 }
6036 }
6037 }
6038 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6039 // Switch from SWIPE to FREEFORM if additional pointers go down.
6040 // Cancel previous gesture.
6041 if (currentFingerCount > 2) {
6042#if DEBUG_GESTURES
6043 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6044 currentFingerCount);
6045#endif
6046 *outCancelPreviousGesture = true;
6047 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6048 }
6049 }
6050
6051 // Move the reference points based on the overall group motion of the fingers
6052 // except in PRESS mode while waiting for a transition to occur.
6053 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6054 && (commonDeltaX || commonDeltaY)) {
6055 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6056 uint32_t id = idBits.clearFirstMarkedBit();
6057 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6058 delta.dx = 0;
6059 delta.dy = 0;
6060 }
6061
6062 mPointerGesture.referenceTouchX += commonDeltaX;
6063 mPointerGesture.referenceTouchY += commonDeltaY;
6064
6065 commonDeltaX *= mPointerXMovementScale;
6066 commonDeltaY *= mPointerYMovementScale;
6067
6068 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6069 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6070
6071 mPointerGesture.referenceGestureX += commonDeltaX;
6072 mPointerGesture.referenceGestureY += commonDeltaY;
6073 }
6074
6075 // Report gestures.
6076 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6077 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6078 // PRESS or SWIPE mode.
6079#if DEBUG_GESTURES
6080 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6081 "activeGestureId=%d, currentTouchPointerCount=%d",
6082 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6083#endif
6084 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6085
6086 mPointerGesture.currentGestureIdBits.clear();
6087 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6088 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6089 mPointerGesture.currentGestureProperties[0].clear();
6090 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6091 mPointerGesture.currentGestureProperties[0].toolType =
6092 AMOTION_EVENT_TOOL_TYPE_FINGER;
6093 mPointerGesture.currentGestureCoords[0].clear();
6094 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6095 mPointerGesture.referenceGestureX);
6096 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6097 mPointerGesture.referenceGestureY);
6098 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6099 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6100 // FREEFORM mode.
6101#if DEBUG_GESTURES
6102 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6103 "activeGestureId=%d, currentTouchPointerCount=%d",
6104 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6105#endif
6106 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6107
6108 mPointerGesture.currentGestureIdBits.clear();
6109
6110 BitSet32 mappedTouchIdBits;
6111 BitSet32 usedGestureIdBits;
6112 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6113 // Initially, assign the active gesture id to the active touch point
6114 // if there is one. No other touch id bits are mapped yet.
6115 if (!*outCancelPreviousGesture) {
6116 mappedTouchIdBits.markBit(activeTouchId);
6117 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6118 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6119 mPointerGesture.activeGestureId;
6120 } else {
6121 mPointerGesture.activeGestureId = -1;
6122 }
6123 } else {
6124 // Otherwise, assume we mapped all touches from the previous frame.
6125 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006126 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6127 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006128 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6129
6130 // Check whether we need to choose a new active gesture id because the
6131 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006132 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6133 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006134 !upTouchIdBits.isEmpty(); ) {
6135 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6136 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6137 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6138 mPointerGesture.activeGestureId = -1;
6139 break;
6140 }
6141 }
6142 }
6143
6144#if DEBUG_GESTURES
6145 ALOGD("Gestures: FREEFORM follow up "
6146 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6147 "activeGestureId=%d",
6148 mappedTouchIdBits.value, usedGestureIdBits.value,
6149 mPointerGesture.activeGestureId);
6150#endif
6151
Michael Wright842500e2015-03-13 17:32:02 -07006152 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006153 for (uint32_t i = 0; i < currentFingerCount; i++) {
6154 uint32_t touchId = idBits.clearFirstMarkedBit();
6155 uint32_t gestureId;
6156 if (!mappedTouchIdBits.hasBit(touchId)) {
6157 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6158 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6159#if DEBUG_GESTURES
6160 ALOGD("Gestures: FREEFORM "
6161 "new mapping for touch id %d -> gesture id %d",
6162 touchId, gestureId);
6163#endif
6164 } else {
6165 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6166#if DEBUG_GESTURES
6167 ALOGD("Gestures: FREEFORM "
6168 "existing mapping for touch id %d -> gesture id %d",
6169 touchId, gestureId);
6170#endif
6171 }
6172 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6173 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6174
6175 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006176 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006177 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6178 * mPointerXZoomScale;
6179 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6180 * mPointerYZoomScale;
6181 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6182
6183 mPointerGesture.currentGestureProperties[i].clear();
6184 mPointerGesture.currentGestureProperties[i].id = gestureId;
6185 mPointerGesture.currentGestureProperties[i].toolType =
6186 AMOTION_EVENT_TOOL_TYPE_FINGER;
6187 mPointerGesture.currentGestureCoords[i].clear();
6188 mPointerGesture.currentGestureCoords[i].setAxisValue(
6189 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6190 mPointerGesture.currentGestureCoords[i].setAxisValue(
6191 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6192 mPointerGesture.currentGestureCoords[i].setAxisValue(
6193 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6194 }
6195
6196 if (mPointerGesture.activeGestureId < 0) {
6197 mPointerGesture.activeGestureId =
6198 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6199#if DEBUG_GESTURES
6200 ALOGD("Gestures: FREEFORM new "
6201 "activeGestureId=%d", mPointerGesture.activeGestureId);
6202#endif
6203 }
6204 }
6205 }
6206
Michael Wright842500e2015-03-13 17:32:02 -07006207 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006208
6209#if DEBUG_GESTURES
6210 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6211 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6212 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6213 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6214 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6215 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6216 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6217 uint32_t id = idBits.clearFirstMarkedBit();
6218 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6219 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6220 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6221 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6222 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6223 id, index, properties.toolType,
6224 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6225 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6226 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6227 }
6228 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6229 uint32_t id = idBits.clearFirstMarkedBit();
6230 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6231 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6232 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6233 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6234 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6235 id, index, properties.toolType,
6236 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6237 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6238 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6239 }
6240#endif
6241 return true;
6242}
6243
6244void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6245 mPointerSimple.currentCoords.clear();
6246 mPointerSimple.currentProperties.clear();
6247
6248 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006249 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6250 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6251 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6252 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6253 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006254 mPointerController->setPosition(x, y);
6255
Michael Wright842500e2015-03-13 17:32:02 -07006256 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006257 down = !hovering;
6258
6259 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006260 mPointerSimple.currentCoords.copyFrom(
6261 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6263 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6264 mPointerSimple.currentProperties.id = 0;
6265 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006266 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006267 } else {
6268 down = false;
6269 hovering = false;
6270 }
6271
6272 dispatchPointerSimple(when, policyFlags, down, hovering);
6273}
6274
6275void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6276 abortPointerSimple(when, policyFlags);
6277}
6278
6279void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6280 mPointerSimple.currentCoords.clear();
6281 mPointerSimple.currentProperties.clear();
6282
6283 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006284 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6285 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6286 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006287 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006288 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6289 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006290 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006291 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006292 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006293 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006294 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295 * mPointerYMovementScale;
6296
6297 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6298 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6299
6300 mPointerController->move(deltaX, deltaY);
6301 } else {
6302 mPointerVelocityControl.reset();
6303 }
6304
Michael Wright842500e2015-03-13 17:32:02 -07006305 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006306 hovering = !down;
6307
6308 float x, y;
6309 mPointerController->getPosition(&x, &y);
6310 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006311 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006312 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6313 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6314 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6315 hovering ? 0.0f : 1.0f);
6316 mPointerSimple.currentProperties.id = 0;
6317 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006318 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006319 } else {
6320 mPointerVelocityControl.reset();
6321
6322 down = false;
6323 hovering = false;
6324 }
6325
6326 dispatchPointerSimple(when, policyFlags, down, hovering);
6327}
6328
6329void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6330 abortPointerSimple(when, policyFlags);
6331
6332 mPointerVelocityControl.reset();
6333}
6334
6335void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6336 bool down, bool hovering) {
6337 int32_t metaState = getContext()->getGlobalMetaState();
6338
6339 if (mPointerController != NULL) {
6340 if (down || hovering) {
6341 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6342 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006343 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006344 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6345 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6346 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6347 }
6348 }
6349
6350 if (mPointerSimple.down && !down) {
6351 mPointerSimple.down = false;
6352
6353 // Send up.
6354 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006355 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006356 mViewport.displayId, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006357 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6358 mOrientedXPrecision, mOrientedYPrecision,
6359 mPointerSimple.downTime);
6360 getListener()->notifyMotion(&args);
6361 }
6362
6363 if (mPointerSimple.hovering && !hovering) {
6364 mPointerSimple.hovering = false;
6365
6366 // Send hover exit.
6367 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006368 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006369 mViewport.displayId, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006370 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6371 mOrientedXPrecision, mOrientedYPrecision,
6372 mPointerSimple.downTime);
6373 getListener()->notifyMotion(&args);
6374 }
6375
6376 if (down) {
6377 if (!mPointerSimple.down) {
6378 mPointerSimple.down = true;
6379 mPointerSimple.downTime = when;
6380
6381 // Send down.
6382 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006383 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006384 mViewport.displayId, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006385 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6386 mOrientedXPrecision, mOrientedYPrecision,
6387 mPointerSimple.downTime);
6388 getListener()->notifyMotion(&args);
6389 }
6390
6391 // Send move.
6392 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006393 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006394 mViewport.displayId, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006395 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6396 mOrientedXPrecision, mOrientedYPrecision,
6397 mPointerSimple.downTime);
6398 getListener()->notifyMotion(&args);
6399 }
6400
6401 if (hovering) {
6402 if (!mPointerSimple.hovering) {
6403 mPointerSimple.hovering = true;
6404
6405 // Send hover enter.
6406 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006407 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006408 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006409 mViewport.displayId, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006410 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6411 mOrientedXPrecision, mOrientedYPrecision,
6412 mPointerSimple.downTime);
6413 getListener()->notifyMotion(&args);
6414 }
6415
6416 // Send hover move.
6417 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006418 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006419 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006420 mViewport.displayId, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006421 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6422 mOrientedXPrecision, mOrientedYPrecision,
6423 mPointerSimple.downTime);
6424 getListener()->notifyMotion(&args);
6425 }
6426
Michael Wright842500e2015-03-13 17:32:02 -07006427 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6428 float vscroll = mCurrentRawState.rawVScroll;
6429 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006430 mWheelYVelocityControl.move(when, NULL, &vscroll);
6431 mWheelXVelocityControl.move(when, &hscroll, NULL);
6432
6433 // Send scroll.
6434 PointerCoords pointerCoords;
6435 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6436 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6437 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6438
6439 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006440 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006441 mViewport.displayId, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006442 1, &mPointerSimple.currentProperties, &pointerCoords,
6443 mOrientedXPrecision, mOrientedYPrecision,
6444 mPointerSimple.downTime);
6445 getListener()->notifyMotion(&args);
6446 }
6447
6448 // Save state.
6449 if (down || hovering) {
6450 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6451 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6452 } else {
6453 mPointerSimple.reset();
6454 }
6455}
6456
6457void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6458 mPointerSimple.currentCoords.clear();
6459 mPointerSimple.currentProperties.clear();
6460
6461 dispatchPointerSimple(when, policyFlags, false, false);
6462}
6463
6464void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006465 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006466 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006467 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006468 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6469 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006470 PointerCoords pointerCoords[MAX_POINTERS];
6471 PointerProperties pointerProperties[MAX_POINTERS];
6472 uint32_t pointerCount = 0;
6473 while (!idBits.isEmpty()) {
6474 uint32_t id = idBits.clearFirstMarkedBit();
6475 uint32_t index = idToIndex[id];
6476 pointerProperties[pointerCount].copyFrom(properties[index]);
6477 pointerCoords[pointerCount].copyFrom(coords[index]);
6478
6479 if (changedId >= 0 && id == uint32_t(changedId)) {
6480 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6481 }
6482
6483 pointerCount += 1;
6484 }
6485
6486 ALOG_ASSERT(pointerCount != 0);
6487
6488 if (changedId >= 0 && pointerCount == 1) {
6489 // Replace initial down and final up action.
6490 // We can compare the action without masking off the changed pointer index
6491 // because we know the index is 0.
6492 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6493 action = AMOTION_EVENT_ACTION_DOWN;
6494 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6495 action = AMOTION_EVENT_ACTION_UP;
6496 } else {
6497 // Can't happen.
6498 ALOG_ASSERT(false);
6499 }
6500 }
6501
6502 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006503 action, actionButton, flags, metaState, buttonState, edgeFlags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006504 mViewport.displayId, deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006505 xPrecision, yPrecision, downTime);
6506 getListener()->notifyMotion(&args);
6507}
6508
6509bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6510 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6511 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6512 BitSet32 idBits) const {
6513 bool changed = false;
6514 while (!idBits.isEmpty()) {
6515 uint32_t id = idBits.clearFirstMarkedBit();
6516 uint32_t inIndex = inIdToIndex[id];
6517 uint32_t outIndex = outIdToIndex[id];
6518
6519 const PointerProperties& curInProperties = inProperties[inIndex];
6520 const PointerCoords& curInCoords = inCoords[inIndex];
6521 PointerProperties& curOutProperties = outProperties[outIndex];
6522 PointerCoords& curOutCoords = outCoords[outIndex];
6523
6524 if (curInProperties != curOutProperties) {
6525 curOutProperties.copyFrom(curInProperties);
6526 changed = true;
6527 }
6528
6529 if (curInCoords != curOutCoords) {
6530 curOutCoords.copyFrom(curInCoords);
6531 changed = true;
6532 }
6533 }
6534 return changed;
6535}
6536
6537void TouchInputMapper::fadePointer() {
6538 if (mPointerController != NULL) {
6539 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6540 }
6541}
6542
Jeff Brownc9aa6282015-02-11 19:03:28 -08006543void TouchInputMapper::cancelTouch(nsecs_t when) {
6544 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006545 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006546}
6547
Michael Wrightd02c5b62014-02-10 15:10:22 -08006548bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006549 const float scaledX = x * mXScale;
6550 const float scaledY = x * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006551 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006552 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6553 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6554 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006555}
6556
6557const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6558 int32_t x, int32_t y) {
6559 size_t numVirtualKeys = mVirtualKeys.size();
6560 for (size_t i = 0; i < numVirtualKeys; i++) {
6561 const VirtualKey& virtualKey = mVirtualKeys[i];
6562
6563#if DEBUG_VIRTUAL_KEYS
6564 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6565 "left=%d, top=%d, right=%d, bottom=%d",
6566 x, y,
6567 virtualKey.keyCode, virtualKey.scanCode,
6568 virtualKey.hitLeft, virtualKey.hitTop,
6569 virtualKey.hitRight, virtualKey.hitBottom);
6570#endif
6571
6572 if (virtualKey.isHit(x, y)) {
6573 return & virtualKey;
6574 }
6575 }
6576
6577 return NULL;
6578}
6579
Michael Wright842500e2015-03-13 17:32:02 -07006580void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6581 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6582 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006583
Michael Wright842500e2015-03-13 17:32:02 -07006584 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006585
6586 if (currentPointerCount == 0) {
6587 // No pointers to assign.
6588 return;
6589 }
6590
6591 if (lastPointerCount == 0) {
6592 // All pointers are new.
6593 for (uint32_t i = 0; i < currentPointerCount; i++) {
6594 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006595 current->rawPointerData.pointers[i].id = id;
6596 current->rawPointerData.idToIndex[id] = i;
6597 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006598 }
6599 return;
6600 }
6601
6602 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006603 && current->rawPointerData.pointers[0].toolType
6604 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006605 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006606 uint32_t id = last->rawPointerData.pointers[0].id;
6607 current->rawPointerData.pointers[0].id = id;
6608 current->rawPointerData.idToIndex[id] = 0;
6609 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006610 return;
6611 }
6612
6613 // General case.
6614 // We build a heap of squared euclidean distances between current and last pointers
6615 // associated with the current and last pointer indices. Then, we find the best
6616 // match (by distance) for each current pointer.
6617 // The pointers must have the same tool type but it is possible for them to
6618 // transition from hovering to touching or vice-versa while retaining the same id.
6619 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6620
6621 uint32_t heapSize = 0;
6622 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6623 currentPointerIndex++) {
6624 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6625 lastPointerIndex++) {
6626 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006627 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006628 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006629 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006630 if (currentPointer.toolType == lastPointer.toolType) {
6631 int64_t deltaX = currentPointer.x - lastPointer.x;
6632 int64_t deltaY = currentPointer.y - lastPointer.y;
6633
6634 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6635
6636 // Insert new element into the heap (sift up).
6637 heap[heapSize].currentPointerIndex = currentPointerIndex;
6638 heap[heapSize].lastPointerIndex = lastPointerIndex;
6639 heap[heapSize].distance = distance;
6640 heapSize += 1;
6641 }
6642 }
6643 }
6644
6645 // Heapify
6646 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6647 startIndex -= 1;
6648 for (uint32_t parentIndex = startIndex; ;) {
6649 uint32_t childIndex = parentIndex * 2 + 1;
6650 if (childIndex >= heapSize) {
6651 break;
6652 }
6653
6654 if (childIndex + 1 < heapSize
6655 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6656 childIndex += 1;
6657 }
6658
6659 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6660 break;
6661 }
6662
6663 swap(heap[parentIndex], heap[childIndex]);
6664 parentIndex = childIndex;
6665 }
6666 }
6667
6668#if DEBUG_POINTER_ASSIGNMENT
6669 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6670 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006671 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006672 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6673 heap[i].distance);
6674 }
6675#endif
6676
6677 // Pull matches out by increasing order of distance.
6678 // To avoid reassigning pointers that have already been matched, the loop keeps track
6679 // of which last and current pointers have been matched using the matchedXXXBits variables.
6680 // It also tracks the used pointer id bits.
6681 BitSet32 matchedLastBits(0);
6682 BitSet32 matchedCurrentBits(0);
6683 BitSet32 usedIdBits(0);
6684 bool first = true;
6685 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6686 while (heapSize > 0) {
6687 if (first) {
6688 // The first time through the loop, we just consume the root element of
6689 // the heap (the one with smallest distance).
6690 first = false;
6691 } else {
6692 // Previous iterations consumed the root element of the heap.
6693 // Pop root element off of the heap (sift down).
6694 heap[0] = heap[heapSize];
6695 for (uint32_t parentIndex = 0; ;) {
6696 uint32_t childIndex = parentIndex * 2 + 1;
6697 if (childIndex >= heapSize) {
6698 break;
6699 }
6700
6701 if (childIndex + 1 < heapSize
6702 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6703 childIndex += 1;
6704 }
6705
6706 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6707 break;
6708 }
6709
6710 swap(heap[parentIndex], heap[childIndex]);
6711 parentIndex = childIndex;
6712 }
6713
6714#if DEBUG_POINTER_ASSIGNMENT
6715 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6716 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006717 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006718 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6719 heap[i].distance);
6720 }
6721#endif
6722 }
6723
6724 heapSize -= 1;
6725
6726 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6727 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6728
6729 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6730 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6731
6732 matchedCurrentBits.markBit(currentPointerIndex);
6733 matchedLastBits.markBit(lastPointerIndex);
6734
Michael Wright842500e2015-03-13 17:32:02 -07006735 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6736 current->rawPointerData.pointers[currentPointerIndex].id = id;
6737 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6738 current->rawPointerData.markIdBit(id,
6739 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006740 usedIdBits.markBit(id);
6741
6742#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006743 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6744 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006745 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6746#endif
6747 break;
6748 }
6749 }
6750
6751 // Assign fresh ids to pointers that were not matched in the process.
6752 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6753 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6754 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6755
Michael Wright842500e2015-03-13 17:32:02 -07006756 current->rawPointerData.pointers[currentPointerIndex].id = id;
6757 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6758 current->rawPointerData.markIdBit(id,
6759 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006760
6761#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006762 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006763#endif
6764 }
6765}
6766
6767int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6768 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6769 return AKEY_STATE_VIRTUAL;
6770 }
6771
6772 size_t numVirtualKeys = mVirtualKeys.size();
6773 for (size_t i = 0; i < numVirtualKeys; i++) {
6774 const VirtualKey& virtualKey = mVirtualKeys[i];
6775 if (virtualKey.keyCode == keyCode) {
6776 return AKEY_STATE_UP;
6777 }
6778 }
6779
6780 return AKEY_STATE_UNKNOWN;
6781}
6782
6783int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6784 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6785 return AKEY_STATE_VIRTUAL;
6786 }
6787
6788 size_t numVirtualKeys = mVirtualKeys.size();
6789 for (size_t i = 0; i < numVirtualKeys; i++) {
6790 const VirtualKey& virtualKey = mVirtualKeys[i];
6791 if (virtualKey.scanCode == scanCode) {
6792 return AKEY_STATE_UP;
6793 }
6794 }
6795
6796 return AKEY_STATE_UNKNOWN;
6797}
6798
6799bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6800 const int32_t* keyCodes, uint8_t* outFlags) {
6801 size_t numVirtualKeys = mVirtualKeys.size();
6802 for (size_t i = 0; i < numVirtualKeys; i++) {
6803 const VirtualKey& virtualKey = mVirtualKeys[i];
6804
6805 for (size_t i = 0; i < numCodes; i++) {
6806 if (virtualKey.keyCode == keyCodes[i]) {
6807 outFlags[i] = 1;
6808 }
6809 }
6810 }
6811
6812 return true;
6813}
6814
6815
6816// --- SingleTouchInputMapper ---
6817
6818SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6819 TouchInputMapper(device) {
6820}
6821
6822SingleTouchInputMapper::~SingleTouchInputMapper() {
6823}
6824
6825void SingleTouchInputMapper::reset(nsecs_t when) {
6826 mSingleTouchMotionAccumulator.reset(getDevice());
6827
6828 TouchInputMapper::reset(when);
6829}
6830
6831void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6832 TouchInputMapper::process(rawEvent);
6833
6834 mSingleTouchMotionAccumulator.process(rawEvent);
6835}
6836
Michael Wright842500e2015-03-13 17:32:02 -07006837void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006838 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006839 outState->rawPointerData.pointerCount = 1;
6840 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006841
6842 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6843 && (mTouchButtonAccumulator.isHovering()
6844 || (mRawPointerAxes.pressure.valid
6845 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006846 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006847
Michael Wright842500e2015-03-13 17:32:02 -07006848 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006849 outPointer.id = 0;
6850 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6851 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6852 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6853 outPointer.touchMajor = 0;
6854 outPointer.touchMinor = 0;
6855 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6856 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6857 outPointer.orientation = 0;
6858 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6859 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6860 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6861 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6862 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6863 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6864 }
6865 outPointer.isHovering = isHovering;
6866 }
6867}
6868
6869void SingleTouchInputMapper::configureRawPointerAxes() {
6870 TouchInputMapper::configureRawPointerAxes();
6871
6872 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6873 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6874 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6875 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6876 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6877 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6878 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6879}
6880
6881bool SingleTouchInputMapper::hasStylus() const {
6882 return mTouchButtonAccumulator.hasStylus();
6883}
6884
6885
6886// --- MultiTouchInputMapper ---
6887
6888MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6889 TouchInputMapper(device) {
6890}
6891
6892MultiTouchInputMapper::~MultiTouchInputMapper() {
6893}
6894
6895void MultiTouchInputMapper::reset(nsecs_t when) {
6896 mMultiTouchMotionAccumulator.reset(getDevice());
6897
6898 mPointerIdBits.clear();
6899
6900 TouchInputMapper::reset(when);
6901}
6902
6903void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6904 TouchInputMapper::process(rawEvent);
6905
6906 mMultiTouchMotionAccumulator.process(rawEvent);
6907}
6908
Michael Wright842500e2015-03-13 17:32:02 -07006909void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006910 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6911 size_t outCount = 0;
6912 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006913 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006914
6915 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6916 const MultiTouchMotionAccumulator::Slot* inSlot =
6917 mMultiTouchMotionAccumulator.getSlot(inIndex);
6918 if (!inSlot->isInUse()) {
6919 continue;
6920 }
6921
6922 if (outCount >= MAX_POINTERS) {
6923#if DEBUG_POINTERS
6924 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6925 "ignoring the rest.",
6926 getDeviceName().string(), MAX_POINTERS);
6927#endif
6928 break; // too many fingers!
6929 }
6930
Michael Wright842500e2015-03-13 17:32:02 -07006931 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006932 outPointer.x = inSlot->getX();
6933 outPointer.y = inSlot->getY();
6934 outPointer.pressure = inSlot->getPressure();
6935 outPointer.touchMajor = inSlot->getTouchMajor();
6936 outPointer.touchMinor = inSlot->getTouchMinor();
6937 outPointer.toolMajor = inSlot->getToolMajor();
6938 outPointer.toolMinor = inSlot->getToolMinor();
6939 outPointer.orientation = inSlot->getOrientation();
6940 outPointer.distance = inSlot->getDistance();
6941 outPointer.tiltX = 0;
6942 outPointer.tiltY = 0;
6943
6944 outPointer.toolType = inSlot->getToolType();
6945 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6946 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6947 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6948 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6949 }
6950 }
6951
6952 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6953 && (mTouchButtonAccumulator.isHovering()
6954 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6955 outPointer.isHovering = isHovering;
6956
6957 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006958 if (mHavePointerIds) {
6959 int32_t trackingId = inSlot->getTrackingId();
6960 int32_t id = -1;
6961 if (trackingId >= 0) {
6962 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6963 uint32_t n = idBits.clearFirstMarkedBit();
6964 if (mPointerTrackingIdMap[n] == trackingId) {
6965 id = n;
6966 }
6967 }
6968
6969 if (id < 0 && !mPointerIdBits.isFull()) {
6970 id = mPointerIdBits.markFirstUnmarkedBit();
6971 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006972 }
Michael Wright842500e2015-03-13 17:32:02 -07006973 }
gaoshang1a632de2016-08-24 10:23:50 +08006974 if (id < 0) {
6975 mHavePointerIds = false;
6976 outState->rawPointerData.clearIdBits();
6977 newPointerIdBits.clear();
6978 } else {
6979 outPointer.id = id;
6980 outState->rawPointerData.idToIndex[id] = outCount;
6981 outState->rawPointerData.markIdBit(id, isHovering);
6982 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006983 }
Michael Wright842500e2015-03-13 17:32:02 -07006984 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006985 outCount += 1;
6986 }
6987
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006988 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006989 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006990 mPointerIdBits = newPointerIdBits;
6991
6992 mMultiTouchMotionAccumulator.finishSync();
6993}
6994
6995void MultiTouchInputMapper::configureRawPointerAxes() {
6996 TouchInputMapper::configureRawPointerAxes();
6997
6998 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6999 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7000 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7001 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7002 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7003 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7004 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7005 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7006 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7007 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7008 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7009
7010 if (mRawPointerAxes.trackingId.valid
7011 && mRawPointerAxes.slot.valid
7012 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7013 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7014 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007015 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7016 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007017 getDeviceName().string(), slotCount, MAX_SLOTS);
7018 slotCount = MAX_SLOTS;
7019 }
7020 mMultiTouchMotionAccumulator.configure(getDevice(),
7021 slotCount, true /*usingSlotsProtocol*/);
7022 } else {
7023 mMultiTouchMotionAccumulator.configure(getDevice(),
7024 MAX_POINTERS, false /*usingSlotsProtocol*/);
7025 }
7026}
7027
7028bool MultiTouchInputMapper::hasStylus() const {
7029 return mMultiTouchMotionAccumulator.hasStylus()
7030 || mTouchButtonAccumulator.hasStylus();
7031}
7032
Michael Wright842500e2015-03-13 17:32:02 -07007033// --- ExternalStylusInputMapper
7034
7035ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7036 InputMapper(device) {
7037
7038}
7039
7040uint32_t ExternalStylusInputMapper::getSources() {
7041 return AINPUT_SOURCE_STYLUS;
7042}
7043
7044void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7045 InputMapper::populateDeviceInfo(info);
7046 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7047 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7048}
7049
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007050void ExternalStylusInputMapper::dump(std::string& dump) {
7051 dump += INDENT2 "External Stylus Input Mapper:\n";
7052 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007053 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007054 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007055 dumpStylusState(dump, mStylusState);
7056}
7057
7058void ExternalStylusInputMapper::configure(nsecs_t when,
7059 const InputReaderConfiguration* config, uint32_t changes) {
7060 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7061 mTouchButtonAccumulator.configure(getDevice());
7062}
7063
7064void ExternalStylusInputMapper::reset(nsecs_t when) {
7065 InputDevice* device = getDevice();
7066 mSingleTouchMotionAccumulator.reset(device);
7067 mTouchButtonAccumulator.reset(device);
7068 InputMapper::reset(when);
7069}
7070
7071void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7072 mSingleTouchMotionAccumulator.process(rawEvent);
7073 mTouchButtonAccumulator.process(rawEvent);
7074
7075 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7076 sync(rawEvent->when);
7077 }
7078}
7079
7080void ExternalStylusInputMapper::sync(nsecs_t when) {
7081 mStylusState.clear();
7082
7083 mStylusState.when = when;
7084
Michael Wright45ccacf2015-04-21 19:01:58 +01007085 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7086 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7087 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7088 }
7089
Michael Wright842500e2015-03-13 17:32:02 -07007090 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7091 if (mRawPressureAxis.valid) {
7092 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7093 } else if (mTouchButtonAccumulator.isToolActive()) {
7094 mStylusState.pressure = 1.0f;
7095 } else {
7096 mStylusState.pressure = 0.0f;
7097 }
7098
7099 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007100
7101 mContext->dispatchExternalStylusState(mStylusState);
7102}
7103
Michael Wrightd02c5b62014-02-10 15:10:22 -08007104
7105// --- JoystickInputMapper ---
7106
7107JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7108 InputMapper(device) {
7109}
7110
7111JoystickInputMapper::~JoystickInputMapper() {
7112}
7113
7114uint32_t JoystickInputMapper::getSources() {
7115 return AINPUT_SOURCE_JOYSTICK;
7116}
7117
7118void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7119 InputMapper::populateDeviceInfo(info);
7120
7121 for (size_t i = 0; i < mAxes.size(); i++) {
7122 const Axis& axis = mAxes.valueAt(i);
7123 addMotionRange(axis.axisInfo.axis, axis, info);
7124
7125 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7126 addMotionRange(axis.axisInfo.highAxis, axis, info);
7127
7128 }
7129 }
7130}
7131
7132void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7133 InputDeviceInfo* info) {
7134 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7135 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7136 /* In order to ease the transition for developers from using the old axes
7137 * to the newer, more semantically correct axes, we'll continue to register
7138 * the old axes as duplicates of their corresponding new ones. */
7139 int32_t compatAxis = getCompatAxis(axisId);
7140 if (compatAxis >= 0) {
7141 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7142 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7143 }
7144}
7145
7146/* A mapping from axes the joystick actually has to the axes that should be
7147 * artificially created for compatibility purposes.
7148 * Returns -1 if no compatibility axis is needed. */
7149int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7150 switch(axis) {
7151 case AMOTION_EVENT_AXIS_LTRIGGER:
7152 return AMOTION_EVENT_AXIS_BRAKE;
7153 case AMOTION_EVENT_AXIS_RTRIGGER:
7154 return AMOTION_EVENT_AXIS_GAS;
7155 }
7156 return -1;
7157}
7158
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007159void JoystickInputMapper::dump(std::string& dump) {
7160 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007161
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007162 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007163 size_t numAxes = mAxes.size();
7164 for (size_t i = 0; i < numAxes; i++) {
7165 const Axis& axis = mAxes.valueAt(i);
7166 const char* label = getAxisLabel(axis.axisInfo.axis);
7167 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007168 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007169 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007170 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007171 }
7172 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7173 label = getAxisLabel(axis.axisInfo.highAxis);
7174 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007175 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007176 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007177 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007178 axis.axisInfo.splitValue);
7179 }
7180 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007181 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007182 }
7183
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007184 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 -08007185 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007186 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007187 "highScale=%0.5f, highOffset=%0.5f\n",
7188 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007189 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007190 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7191 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7192 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7193 }
7194}
7195
7196void JoystickInputMapper::configure(nsecs_t when,
7197 const InputReaderConfiguration* config, uint32_t changes) {
7198 InputMapper::configure(when, config, changes);
7199
7200 if (!changes) { // first time only
7201 // Collect all axes.
7202 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7203 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7204 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7205 continue; // axis must be claimed by a different device
7206 }
7207
7208 RawAbsoluteAxisInfo rawAxisInfo;
7209 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7210 if (rawAxisInfo.valid) {
7211 // Map axis.
7212 AxisInfo axisInfo;
7213 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7214 if (!explicitlyMapped) {
7215 // Axis is not explicitly mapped, will choose a generic axis later.
7216 axisInfo.mode = AxisInfo::MODE_NORMAL;
7217 axisInfo.axis = -1;
7218 }
7219
7220 // Apply flat override.
7221 int32_t rawFlat = axisInfo.flatOverride < 0
7222 ? rawAxisInfo.flat : axisInfo.flatOverride;
7223
7224 // Calculate scaling factors and limits.
7225 Axis axis;
7226 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7227 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7228 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7229 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7230 scale, 0.0f, highScale, 0.0f,
7231 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7232 rawAxisInfo.resolution * scale);
7233 } else if (isCenteredAxis(axisInfo.axis)) {
7234 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7235 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7236 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7237 scale, offset, scale, offset,
7238 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7239 rawAxisInfo.resolution * scale);
7240 } else {
7241 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7242 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7243 scale, 0.0f, scale, 0.0f,
7244 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7245 rawAxisInfo.resolution * scale);
7246 }
7247
7248 // To eliminate noise while the joystick is at rest, filter out small variations
7249 // in axis values up front.
7250 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7251
7252 mAxes.add(abs, axis);
7253 }
7254 }
7255
7256 // If there are too many axes, start dropping them.
7257 // Prefer to keep explicitly mapped axes.
7258 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007259 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007260 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7261 pruneAxes(true);
7262 pruneAxes(false);
7263 }
7264
7265 // Assign generic axis ids to remaining axes.
7266 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7267 size_t numAxes = mAxes.size();
7268 for (size_t i = 0; i < numAxes; i++) {
7269 Axis& axis = mAxes.editValueAt(i);
7270 if (axis.axisInfo.axis < 0) {
7271 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7272 && haveAxis(nextGenericAxisId)) {
7273 nextGenericAxisId += 1;
7274 }
7275
7276 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7277 axis.axisInfo.axis = nextGenericAxisId;
7278 nextGenericAxisId += 1;
7279 } else {
7280 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7281 "have already been assigned to other axes.",
7282 getDeviceName().string(), mAxes.keyAt(i));
7283 mAxes.removeItemsAt(i--);
7284 numAxes -= 1;
7285 }
7286 }
7287 }
7288 }
7289}
7290
7291bool JoystickInputMapper::haveAxis(int32_t axisId) {
7292 size_t numAxes = mAxes.size();
7293 for (size_t i = 0; i < numAxes; i++) {
7294 const Axis& axis = mAxes.valueAt(i);
7295 if (axis.axisInfo.axis == axisId
7296 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7297 && axis.axisInfo.highAxis == axisId)) {
7298 return true;
7299 }
7300 }
7301 return false;
7302}
7303
7304void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7305 size_t i = mAxes.size();
7306 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7307 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7308 continue;
7309 }
7310 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7311 getDeviceName().string(), mAxes.keyAt(i));
7312 mAxes.removeItemsAt(i);
7313 }
7314}
7315
7316bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7317 switch (axis) {
7318 case AMOTION_EVENT_AXIS_X:
7319 case AMOTION_EVENT_AXIS_Y:
7320 case AMOTION_EVENT_AXIS_Z:
7321 case AMOTION_EVENT_AXIS_RX:
7322 case AMOTION_EVENT_AXIS_RY:
7323 case AMOTION_EVENT_AXIS_RZ:
7324 case AMOTION_EVENT_AXIS_HAT_X:
7325 case AMOTION_EVENT_AXIS_HAT_Y:
7326 case AMOTION_EVENT_AXIS_ORIENTATION:
7327 case AMOTION_EVENT_AXIS_RUDDER:
7328 case AMOTION_EVENT_AXIS_WHEEL:
7329 return true;
7330 default:
7331 return false;
7332 }
7333}
7334
7335void JoystickInputMapper::reset(nsecs_t when) {
7336 // Recenter all axes.
7337 size_t numAxes = mAxes.size();
7338 for (size_t i = 0; i < numAxes; i++) {
7339 Axis& axis = mAxes.editValueAt(i);
7340 axis.resetValue();
7341 }
7342
7343 InputMapper::reset(when);
7344}
7345
7346void JoystickInputMapper::process(const RawEvent* rawEvent) {
7347 switch (rawEvent->type) {
7348 case EV_ABS: {
7349 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7350 if (index >= 0) {
7351 Axis& axis = mAxes.editValueAt(index);
7352 float newValue, highNewValue;
7353 switch (axis.axisInfo.mode) {
7354 case AxisInfo::MODE_INVERT:
7355 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7356 * axis.scale + axis.offset;
7357 highNewValue = 0.0f;
7358 break;
7359 case AxisInfo::MODE_SPLIT:
7360 if (rawEvent->value < axis.axisInfo.splitValue) {
7361 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7362 * axis.scale + axis.offset;
7363 highNewValue = 0.0f;
7364 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7365 newValue = 0.0f;
7366 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7367 * axis.highScale + axis.highOffset;
7368 } else {
7369 newValue = 0.0f;
7370 highNewValue = 0.0f;
7371 }
7372 break;
7373 default:
7374 newValue = rawEvent->value * axis.scale + axis.offset;
7375 highNewValue = 0.0f;
7376 break;
7377 }
7378 axis.newValue = newValue;
7379 axis.highNewValue = highNewValue;
7380 }
7381 break;
7382 }
7383
7384 case EV_SYN:
7385 switch (rawEvent->code) {
7386 case SYN_REPORT:
7387 sync(rawEvent->when, false /*force*/);
7388 break;
7389 }
7390 break;
7391 }
7392}
7393
7394void JoystickInputMapper::sync(nsecs_t when, bool force) {
7395 if (!filterAxes(force)) {
7396 return;
7397 }
7398
7399 int32_t metaState = mContext->getGlobalMetaState();
7400 int32_t buttonState = 0;
7401
7402 PointerProperties pointerProperties;
7403 pointerProperties.clear();
7404 pointerProperties.id = 0;
7405 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7406
7407 PointerCoords pointerCoords;
7408 pointerCoords.clear();
7409
7410 size_t numAxes = mAxes.size();
7411 for (size_t i = 0; i < numAxes; i++) {
7412 const Axis& axis = mAxes.valueAt(i);
7413 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7414 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7415 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7416 axis.highCurrentValue);
7417 }
7418 }
7419
7420 // Moving a joystick axis should not wake the device because joysticks can
7421 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7422 // button will likely wake the device.
7423 // TODO: Use the input device configuration to control this behavior more finely.
7424 uint32_t policyFlags = 0;
7425
7426 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007427 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007428 ADISPLAY_ID_NONE, /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
7429 0, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007430 getListener()->notifyMotion(&args);
7431}
7432
7433void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7434 int32_t axis, float value) {
7435 pointerCoords->setAxisValue(axis, value);
7436 /* In order to ease the transition for developers from using the old axes
7437 * to the newer, more semantically correct axes, we'll continue to produce
7438 * values for the old axes as mirrors of the value of their corresponding
7439 * new axes. */
7440 int32_t compatAxis = getCompatAxis(axis);
7441 if (compatAxis >= 0) {
7442 pointerCoords->setAxisValue(compatAxis, value);
7443 }
7444}
7445
7446bool JoystickInputMapper::filterAxes(bool force) {
7447 bool atLeastOneSignificantChange = force;
7448 size_t numAxes = mAxes.size();
7449 for (size_t i = 0; i < numAxes; i++) {
7450 Axis& axis = mAxes.editValueAt(i);
7451 if (force || hasValueChangedSignificantly(axis.filter,
7452 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7453 axis.currentValue = axis.newValue;
7454 atLeastOneSignificantChange = true;
7455 }
7456 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7457 if (force || hasValueChangedSignificantly(axis.filter,
7458 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7459 axis.highCurrentValue = axis.highNewValue;
7460 atLeastOneSignificantChange = true;
7461 }
7462 }
7463 }
7464 return atLeastOneSignificantChange;
7465}
7466
7467bool JoystickInputMapper::hasValueChangedSignificantly(
7468 float filter, float newValue, float currentValue, float min, float max) {
7469 if (newValue != currentValue) {
7470 // Filter out small changes in value unless the value is converging on the axis
7471 // bounds or center point. This is intended to reduce the amount of information
7472 // sent to applications by particularly noisy joysticks (such as PS3).
7473 if (fabs(newValue - currentValue) > filter
7474 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7475 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7476 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7477 return true;
7478 }
7479 }
7480 return false;
7481}
7482
7483bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7484 float filter, float newValue, float currentValue, float thresholdValue) {
7485 float newDistance = fabs(newValue - thresholdValue);
7486 if (newDistance < filter) {
7487 float oldDistance = fabs(currentValue - thresholdValue);
7488 if (newDistance < oldDistance) {
7489 return true;
7490 }
7491 }
7492 return false;
7493}
7494
7495} // namespace android