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