blob: dae7879d48bca4beade4db2caaa5c3f892936c56 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputReader"
18
19//#define LOG_NDEBUG 0
20
21// Log debug messages for each raw event received from the EventHub.
22#define DEBUG_RAW_EVENTS 0
23
24// Log debug messages about touch screen filtering hacks.
25#define DEBUG_HACKS 0
26
27// Log debug messages about virtual key processing.
28#define DEBUG_VIRTUAL_KEYS 0
29
30// Log debug messages about pointers.
31#define DEBUG_POINTERS 0
32
33// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
36// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
39// Log debug messages about the vibrator.
40#define DEBUG_VIBRATOR 0
41
Michael Wright842500e2015-03-13 17:32:02 -070042// Log debug messages about fusing stylus data.
43#define DEBUG_STYLUS_FUSION 0
44
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include "InputReader.h"
46
Mark Salyzyna5e161b2016-09-29 08:08:05 -070047#include <errno.h>
Michael Wright842500e2015-03-13 17:32:02 -070048#include <inttypes.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070049#include <limits.h>
50#include <math.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <stddef.h>
52#include <stdlib.h>
53#include <unistd.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054
Mark Salyzyn7823e122016-09-29 08:08:05 -070055#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056
57#include <input/Keyboard.h>
58#include <input/VirtualKeyMap.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080059
60#define INDENT " "
61#define INDENT2 " "
62#define INDENT3 " "
63#define INDENT4 " "
64#define INDENT5 " "
65
66namespace android {
67
68// --- Constants ---
69
70// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
71static const size_t MAX_SLOTS = 32;
72
Michael Wright842500e2015-03-13 17:32:02 -070073// Maximum amount of latency to add to touch events while waiting for data from an
74// external stylus.
Michael Wright5e17a5d2015-04-21 22:45:13 +010075static const nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
Michael Wright842500e2015-03-13 17:32:02 -070076
Michael Wright43fd19f2015-04-21 19:02:58 +010077// Maximum amount of time to wait on touch data before pushing out new pressure data.
78static const nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
79
80// Artificial latency on synthetic events created from stylus data without corresponding touch
81// data.
82static const nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
83
Michael Wrightd02c5b62014-02-10 15:10:22 -080084// --- Static Functions ---
85
86template<typename T>
87inline static T abs(const T& value) {
88 return value < 0 ? - value : value;
89}
90
91template<typename T>
92inline static T min(const T& a, const T& b) {
93 return a < b ? a : b;
94}
95
96template<typename T>
97inline static void swap(T& a, T& b) {
98 T temp = a;
99 a = b;
100 b = temp;
101}
102
103inline static float avg(float x, float y) {
104 return (x + y) / 2;
105}
106
107inline static float distance(float x1, float y1, float x2, float y2) {
108 return hypotf(x1 - x2, y1 - y2);
109}
110
111inline static int32_t signExtendNybble(int32_t value) {
112 return value >= 8 ? value - 16 : value;
113}
114
115static inline const char* toString(bool value) {
116 return value ? "true" : "false";
117}
118
119static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
120 const int32_t map[][4], size_t mapSize) {
121 if (orientation != DISPLAY_ORIENTATION_0) {
122 for (size_t i = 0; i < mapSize; i++) {
123 if (value == map[i][0]) {
124 return map[i][orientation];
125 }
126 }
127 }
128 return value;
129}
130
131static const int32_t keyCodeRotationMap[][4] = {
132 // key codes enumerated counter-clockwise with the original (unrotated) key first
133 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
134 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
135 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
136 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
137 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jim Millere7a57d12016-06-22 15:58:31 -0700138 { AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
139 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT },
140 { AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
141 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN },
142 { AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
143 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT },
144 { AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
145 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP },
Michael Wrightd02c5b62014-02-10 15:10:22 -0800146};
147static const size_t keyCodeRotationMapSize =
148 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
149
Ivan Podogovb9afef32017-02-13 15:34:32 +0000150static int32_t rotateStemKey(int32_t value, int32_t orientation,
151 const int32_t map[][2], size_t mapSize) {
152 if (orientation == DISPLAY_ORIENTATION_180) {
153 for (size_t i = 0; i < mapSize; i++) {
154 if (value == map[i][0]) {
155 return map[i][1];
156 }
157 }
158 }
159 return value;
160}
161
162// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
163static int32_t stemKeyRotationMap[][2] = {
164 // key codes enumerated with the original (unrotated) key first
165 // no rotation, 180 degree rotation
166 { AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
167 { AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
168 { AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
169 { AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
170};
171static const size_t stemKeyRotationMapSize =
172 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
173
Michael Wrightd02c5b62014-02-10 15:10:22 -0800174static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000175 keyCode = rotateStemKey(keyCode, orientation,
176 stemKeyRotationMap, stemKeyRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 return rotateValueUsingRotationMap(keyCode, orientation,
178 keyCodeRotationMap, keyCodeRotationMapSize);
179}
180
181static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
182 float temp;
183 switch (orientation) {
184 case DISPLAY_ORIENTATION_90:
185 temp = *deltaX;
186 *deltaX = *deltaY;
187 *deltaY = -temp;
188 break;
189
190 case DISPLAY_ORIENTATION_180:
191 *deltaX = -*deltaX;
192 *deltaY = -*deltaY;
193 break;
194
195 case DISPLAY_ORIENTATION_270:
196 temp = *deltaX;
197 *deltaX = -*deltaY;
198 *deltaY = temp;
199 break;
200 }
201}
202
203static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
204 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
205}
206
207// Returns true if the pointer should be reported as being down given the specified
208// button states. This determines whether the event is reported as a touch event.
209static bool isPointerDown(int32_t buttonState) {
210 return buttonState &
211 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
212 | AMOTION_EVENT_BUTTON_TERTIARY);
213}
214
215static float calculateCommonVector(float a, float b) {
216 if (a > 0 && b > 0) {
217 return a < b ? a : b;
218 } else if (a < 0 && b < 0) {
219 return a > b ? a : b;
220 } else {
221 return 0;
222 }
223}
224
225static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
226 nsecs_t when, int32_t deviceId, uint32_t source,
227 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
228 int32_t buttonState, int32_t keyCode) {
229 if (
230 (action == AKEY_EVENT_ACTION_DOWN
231 && !(lastButtonState & buttonState)
232 && (currentButtonState & buttonState))
233 || (action == AKEY_EVENT_ACTION_UP
234 && (lastButtonState & buttonState)
235 && !(currentButtonState & buttonState))) {
236 NotifyKeyArgs args(when, deviceId, source, policyFlags,
237 action, 0, keyCode, 0, context->getGlobalMetaState(), when);
238 context->getListener()->notifyKey(&args);
239 }
240}
241
242static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
243 nsecs_t when, int32_t deviceId, uint32_t source,
244 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
245 synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
246 lastButtonState, currentButtonState,
247 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
248 synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
249 lastButtonState, currentButtonState,
250 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
251}
252
253
254// --- InputReaderConfiguration ---
255
Santos Cordonfa5cf462017-04-05 10:37:00 -0700256bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType,
257 const String8* uniqueDisplayId, DisplayViewport* outViewport) const {
258 const DisplayViewport* viewport = NULL;
259 if (viewportType == ViewportType::VIEWPORT_VIRTUAL && uniqueDisplayId != NULL) {
260 for (DisplayViewport currentViewport : mVirtualDisplays) {
261 if (currentViewport.uniqueId == *uniqueDisplayId) {
262 viewport = &currentViewport;
263 break;
264 }
265 }
266 } else if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
267 viewport = &mExternalDisplay;
268 } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
269 viewport = &mInternalDisplay;
270 }
271
272 if (viewport != NULL && viewport->displayId >= 0) {
273 *outViewport = *viewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800274 return true;
275 }
276 return false;
277}
278
Santos Cordonfa5cf462017-04-05 10:37:00 -0700279void InputReaderConfiguration::setPhysicalDisplayViewport(ViewportType viewportType,
280 const DisplayViewport& viewport) {
281 if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
282 mExternalDisplay = viewport;
283 } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
284 mInternalDisplay = viewport;
285 }
286}
287
288void InputReaderConfiguration::setVirtualDisplayViewports(
289 const Vector<DisplayViewport>& viewports) {
290 mVirtualDisplays = viewports;
291}
292
293void InputReaderConfiguration::dump(String8& dump) const {
294 dump.append(INDENT4 "ViewportInternal:\n");
295 dumpViewport(dump, mInternalDisplay);
296 dump.append(INDENT4 "ViewportExternal:\n");
297 dumpViewport(dump, mExternalDisplay);
298 dump.append(INDENT4 "ViewportVirtual:\n");
299 for (const DisplayViewport& viewport : mVirtualDisplays) {
300 dumpViewport(dump, viewport);
301 }
302}
303
304void InputReaderConfiguration::dumpViewport(String8& dump, const DisplayViewport& viewport) const {
305 dump.appendFormat(INDENT5 "Viewport: displayId=%d, orientation=%d, uniqueId='%s', "
306 "logicalFrame=[%d, %d, %d, %d], "
307 "physicalFrame=[%d, %d, %d, %d], "
308 "deviceSize=[%d, %d]\n",
309 viewport.displayId, viewport.orientation, viewport.uniqueId.c_str(),
310 viewport.logicalLeft, viewport.logicalTop,
311 viewport.logicalRight, viewport.logicalBottom,
312 viewport.physicalLeft, viewport.physicalTop,
313 viewport.physicalRight, viewport.physicalBottom,
314 viewport.deviceWidth, viewport.deviceHeight);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800315}
316
317
Jason Gereckeaf126fb2012-05-10 14:22:47 -0700318// -- TouchAffineTransformation --
319void TouchAffineTransformation::applyTo(float& x, float& y) const {
320 float newX, newY;
321 newX = x * x_scale + y * x_ymix + x_offset;
322 newY = x * y_xmix + y * y_scale + y_offset;
323
324 x = newX;
325 y = newY;
326}
327
328
Michael Wrightd02c5b62014-02-10 15:10:22 -0800329// --- InputReader ---
330
331InputReader::InputReader(const sp<EventHubInterface>& eventHub,
332 const sp<InputReaderPolicyInterface>& policy,
333 const sp<InputListenerInterface>& listener) :
334 mContext(this), mEventHub(eventHub), mPolicy(policy),
335 mGlobalMetaState(0), mGeneration(1),
336 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
337 mConfigurationChangesToRefresh(0) {
338 mQueuedListener = new QueuedInputListener(listener);
339
340 { // acquire lock
341 AutoMutex _l(mLock);
342
343 refreshConfigurationLocked(0);
344 updateGlobalMetaStateLocked();
345 } // release lock
346}
347
348InputReader::~InputReader() {
349 for (size_t i = 0; i < mDevices.size(); i++) {
350 delete mDevices.valueAt(i);
351 }
352}
353
354void InputReader::loopOnce() {
355 int32_t oldGeneration;
356 int32_t timeoutMillis;
357 bool inputDevicesChanged = false;
358 Vector<InputDeviceInfo> inputDevices;
359 { // acquire lock
360 AutoMutex _l(mLock);
361
362 oldGeneration = mGeneration;
363 timeoutMillis = -1;
364
365 uint32_t changes = mConfigurationChangesToRefresh;
366 if (changes) {
367 mConfigurationChangesToRefresh = 0;
368 timeoutMillis = 0;
369 refreshConfigurationLocked(changes);
370 } else if (mNextTimeout != LLONG_MAX) {
371 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
372 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
373 }
374 } // release lock
375
376 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
377
378 { // acquire lock
379 AutoMutex _l(mLock);
380 mReaderIsAliveCondition.broadcast();
381
382 if (count) {
383 processEventsLocked(mEventBuffer, count);
384 }
385
386 if (mNextTimeout != LLONG_MAX) {
387 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
388 if (now >= mNextTimeout) {
389#if DEBUG_RAW_EVENTS
390 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
391#endif
392 mNextTimeout = LLONG_MAX;
393 timeoutExpiredLocked(now);
394 }
395 }
396
397 if (oldGeneration != mGeneration) {
398 inputDevicesChanged = true;
399 getInputDevicesLocked(inputDevices);
400 }
401 } // release lock
402
403 // Send out a message that the describes the changed input devices.
404 if (inputDevicesChanged) {
405 mPolicy->notifyInputDevicesChanged(inputDevices);
406 }
407
408 // Flush queued events out to the listener.
409 // This must happen outside of the lock because the listener could potentially call
410 // back into the InputReader's methods, such as getScanCodeState, or become blocked
411 // on another thread similarly waiting to acquire the InputReader lock thereby
412 // resulting in a deadlock. This situation is actually quite plausible because the
413 // listener is actually the input dispatcher, which calls into the window manager,
414 // which occasionally calls into the input reader.
415 mQueuedListener->flush();
416}
417
418void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
419 for (const RawEvent* rawEvent = rawEvents; count;) {
420 int32_t type = rawEvent->type;
421 size_t batchSize = 1;
422 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
423 int32_t deviceId = rawEvent->deviceId;
424 while (batchSize < count) {
425 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
426 || rawEvent[batchSize].deviceId != deviceId) {
427 break;
428 }
429 batchSize += 1;
430 }
431#if DEBUG_RAW_EVENTS
432 ALOGD("BatchSize: %d Count: %d", batchSize, count);
433#endif
434 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
435 } else {
436 switch (rawEvent->type) {
437 case EventHubInterface::DEVICE_ADDED:
438 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
439 break;
440 case EventHubInterface::DEVICE_REMOVED:
441 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
442 break;
443 case EventHubInterface::FINISHED_DEVICE_SCAN:
444 handleConfigurationChangedLocked(rawEvent->when);
445 break;
446 default:
447 ALOG_ASSERT(false); // can't happen
448 break;
449 }
450 }
451 count -= batchSize;
452 rawEvent += batchSize;
453 }
454}
455
456void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
457 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
458 if (deviceIndex >= 0) {
459 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
460 return;
461 }
462
463 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
464 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
465 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
466
467 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
468 device->configure(when, &mConfig, 0);
469 device->reset(when);
470
471 if (device->isIgnored()) {
472 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
473 identifier.name.string());
474 } else {
475 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
476 identifier.name.string(), device->getSources());
477 }
478
479 mDevices.add(deviceId, device);
480 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700481
482 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
483 notifyExternalStylusPresenceChanged();
484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485}
486
487void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
488 InputDevice* device = NULL;
489 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
490 if (deviceIndex < 0) {
491 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
492 return;
493 }
494
495 device = mDevices.valueAt(deviceIndex);
496 mDevices.removeItemsAt(deviceIndex, 1);
497 bumpGenerationLocked();
498
499 if (device->isIgnored()) {
500 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
501 device->getId(), device->getName().string());
502 } else {
503 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
504 device->getId(), device->getName().string(), device->getSources());
505 }
506
Michael Wright842500e2015-03-13 17:32:02 -0700507 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
508 notifyExternalStylusPresenceChanged();
509 }
510
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 device->reset(when);
512 delete device;
513}
514
515InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
516 const InputDeviceIdentifier& identifier, uint32_t classes) {
517 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
518 controllerNumber, identifier, classes);
519
520 // External devices.
521 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
522 device->setExternal(true);
523 }
524
Tim Kilbourn063ff532015-04-08 10:26:18 -0700525 // Devices with mics.
526 if (classes & INPUT_DEVICE_CLASS_MIC) {
527 device->setMic(true);
528 }
529
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530 // Switch-like devices.
531 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
532 device->addMapper(new SwitchInputMapper(device));
533 }
534
Prashant Malani1941ff52015-08-11 18:29:28 -0700535 // Scroll wheel-like devices.
536 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
537 device->addMapper(new RotaryEncoderInputMapper(device));
538 }
539
Michael Wrightd02c5b62014-02-10 15:10:22 -0800540 // Vibrator-like devices.
541 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
542 device->addMapper(new VibratorInputMapper(device));
543 }
544
545 // Keyboard-like devices.
546 uint32_t keyboardSource = 0;
547 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
548 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
549 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
550 }
551 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
552 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
553 }
554 if (classes & INPUT_DEVICE_CLASS_DPAD) {
555 keyboardSource |= AINPUT_SOURCE_DPAD;
556 }
557 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
558 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
559 }
560
561 if (keyboardSource != 0) {
562 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
563 }
564
565 // Cursor-like devices.
566 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
567 device->addMapper(new CursorInputMapper(device));
568 }
569
570 // Touchscreens and touchpad devices.
571 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
572 device->addMapper(new MultiTouchInputMapper(device));
573 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
574 device->addMapper(new SingleTouchInputMapper(device));
575 }
576
577 // Joystick-like devices.
578 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
579 device->addMapper(new JoystickInputMapper(device));
580 }
581
Michael Wright842500e2015-03-13 17:32:02 -0700582 // External stylus-like devices.
583 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
584 device->addMapper(new ExternalStylusInputMapper(device));
585 }
586
Michael Wrightd02c5b62014-02-10 15:10:22 -0800587 return device;
588}
589
590void InputReader::processEventsForDeviceLocked(int32_t deviceId,
591 const RawEvent* rawEvents, size_t count) {
592 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
593 if (deviceIndex < 0) {
594 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
595 return;
596 }
597
598 InputDevice* device = mDevices.valueAt(deviceIndex);
599 if (device->isIgnored()) {
600 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
601 return;
602 }
603
604 device->process(rawEvents, count);
605}
606
607void InputReader::timeoutExpiredLocked(nsecs_t when) {
608 for (size_t i = 0; i < mDevices.size(); i++) {
609 InputDevice* device = mDevices.valueAt(i);
610 if (!device->isIgnored()) {
611 device->timeoutExpired(when);
612 }
613 }
614}
615
616void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
617 // Reset global meta state because it depends on the list of all configured devices.
618 updateGlobalMetaStateLocked();
619
620 // Enqueue configuration changed.
621 NotifyConfigurationChangedArgs args(when);
622 mQueuedListener->notifyConfigurationChanged(&args);
623}
624
625void InputReader::refreshConfigurationLocked(uint32_t changes) {
626 mPolicy->getReaderConfiguration(&mConfig);
627 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
628
629 if (changes) {
630 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
631 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
632
633 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
634 mEventHub->requestReopenDevices();
635 } else {
636 for (size_t i = 0; i < mDevices.size(); i++) {
637 InputDevice* device = mDevices.valueAt(i);
638 device->configure(now, &mConfig, changes);
639 }
640 }
641 }
642}
643
644void InputReader::updateGlobalMetaStateLocked() {
645 mGlobalMetaState = 0;
646
647 for (size_t i = 0; i < mDevices.size(); i++) {
648 InputDevice* device = mDevices.valueAt(i);
649 mGlobalMetaState |= device->getMetaState();
650 }
651}
652
653int32_t InputReader::getGlobalMetaStateLocked() {
654 return mGlobalMetaState;
655}
656
Michael Wright842500e2015-03-13 17:32:02 -0700657void InputReader::notifyExternalStylusPresenceChanged() {
658 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
659}
660
661void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
662 for (size_t i = 0; i < mDevices.size(); i++) {
663 InputDevice* device = mDevices.valueAt(i);
664 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
665 outDevices.push();
666 device->getDeviceInfo(&outDevices.editTop());
667 }
668 }
669}
670
671void InputReader::dispatchExternalStylusState(const StylusState& state) {
672 for (size_t i = 0; i < mDevices.size(); i++) {
673 InputDevice* device = mDevices.valueAt(i);
674 device->updateExternalStylusState(state);
675 }
676}
677
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
679 mDisableVirtualKeysTimeout = time;
680}
681
682bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
683 InputDevice* device, int32_t keyCode, int32_t scanCode) {
684 if (now < mDisableVirtualKeysTimeout) {
685 ALOGI("Dropping virtual key from device %s because virtual keys are "
686 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
687 device->getName().string(),
688 (mDisableVirtualKeysTimeout - now) * 0.000001,
689 keyCode, scanCode);
690 return true;
691 } else {
692 return false;
693 }
694}
695
696void InputReader::fadePointerLocked() {
697 for (size_t i = 0; i < mDevices.size(); i++) {
698 InputDevice* device = mDevices.valueAt(i);
699 device->fadePointer();
700 }
701}
702
703void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
704 if (when < mNextTimeout) {
705 mNextTimeout = when;
706 mEventHub->wake();
707 }
708}
709
710int32_t InputReader::bumpGenerationLocked() {
711 return ++mGeneration;
712}
713
714void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
715 AutoMutex _l(mLock);
716 getInputDevicesLocked(outInputDevices);
717}
718
719void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
720 outInputDevices.clear();
721
722 size_t numDevices = mDevices.size();
723 for (size_t i = 0; i < numDevices; i++) {
724 InputDevice* device = mDevices.valueAt(i);
725 if (!device->isIgnored()) {
726 outInputDevices.push();
727 device->getDeviceInfo(&outInputDevices.editTop());
728 }
729 }
730}
731
732int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
733 int32_t keyCode) {
734 AutoMutex _l(mLock);
735
736 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
737}
738
739int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
740 int32_t scanCode) {
741 AutoMutex _l(mLock);
742
743 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
744}
745
746int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
747 AutoMutex _l(mLock);
748
749 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
750}
751
752int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
753 GetStateFunc getStateFunc) {
754 int32_t result = AKEY_STATE_UNKNOWN;
755 if (deviceId >= 0) {
756 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
757 if (deviceIndex >= 0) {
758 InputDevice* device = mDevices.valueAt(deviceIndex);
759 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
760 result = (device->*getStateFunc)(sourceMask, code);
761 }
762 }
763 } else {
764 size_t numDevices = mDevices.size();
765 for (size_t i = 0; i < numDevices; i++) {
766 InputDevice* device = mDevices.valueAt(i);
767 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
768 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
769 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
770 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
771 if (currentResult >= AKEY_STATE_DOWN) {
772 return currentResult;
773 } else if (currentResult == AKEY_STATE_UP) {
774 result = currentResult;
775 }
776 }
777 }
778 }
779 return result;
780}
781
Andrii Kulian763a3a42016-03-08 10:46:16 -0800782void InputReader::toggleCapsLockState(int32_t deviceId) {
783 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
784 if (deviceIndex < 0) {
785 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
786 return;
787 }
788
789 InputDevice* device = mDevices.valueAt(deviceIndex);
790 if (device->isIgnored()) {
791 return;
792 }
793
794 device->updateMetaState(AKEYCODE_CAPS_LOCK);
795}
796
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
798 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
799 AutoMutex _l(mLock);
800
801 memset(outFlags, 0, numCodes);
802 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
803}
804
805bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
806 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
807 bool result = false;
808 if (deviceId >= 0) {
809 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
810 if (deviceIndex >= 0) {
811 InputDevice* device = mDevices.valueAt(deviceIndex);
812 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
813 result = device->markSupportedKeyCodes(sourceMask,
814 numCodes, keyCodes, outFlags);
815 }
816 }
817 } else {
818 size_t numDevices = mDevices.size();
819 for (size_t i = 0; i < numDevices; i++) {
820 InputDevice* device = mDevices.valueAt(i);
821 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
822 result |= device->markSupportedKeyCodes(sourceMask,
823 numCodes, keyCodes, outFlags);
824 }
825 }
826 }
827 return result;
828}
829
830void InputReader::requestRefreshConfiguration(uint32_t changes) {
831 AutoMutex _l(mLock);
832
833 if (changes) {
834 bool needWake = !mConfigurationChangesToRefresh;
835 mConfigurationChangesToRefresh |= changes;
836
837 if (needWake) {
838 mEventHub->wake();
839 }
840 }
841}
842
843void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
844 ssize_t repeat, int32_t token) {
845 AutoMutex _l(mLock);
846
847 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
848 if (deviceIndex >= 0) {
849 InputDevice* device = mDevices.valueAt(deviceIndex);
850 device->vibrate(pattern, patternSize, repeat, token);
851 }
852}
853
854void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
855 AutoMutex _l(mLock);
856
857 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
858 if (deviceIndex >= 0) {
859 InputDevice* device = mDevices.valueAt(deviceIndex);
860 device->cancelVibrate(token);
861 }
862}
863
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700864bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
865 AutoMutex _l(mLock);
866
867 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
868 if (deviceIndex >= 0) {
869 InputDevice* device = mDevices.valueAt(deviceIndex);
870 return device->isEnabled();
871 }
872 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
873 return false;
874}
875
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876void InputReader::dump(String8& dump) {
877 AutoMutex _l(mLock);
878
879 mEventHub->dump(dump);
880 dump.append("\n");
881
882 dump.append("Input Reader State:\n");
883
884 for (size_t i = 0; i < mDevices.size(); i++) {
885 mDevices.valueAt(i)->dump(dump);
886 }
887
888 dump.append(INDENT "Configuration:\n");
889 dump.append(INDENT2 "ExcludedDeviceNames: [");
890 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
891 if (i != 0) {
892 dump.append(", ");
893 }
894 dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
895 }
896 dump.append("]\n");
897 dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
898 mConfig.virtualKeyQuietTime * 0.000001f);
899
900 dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
901 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
902 mConfig.pointerVelocityControlParameters.scale,
903 mConfig.pointerVelocityControlParameters.lowThreshold,
904 mConfig.pointerVelocityControlParameters.highThreshold,
905 mConfig.pointerVelocityControlParameters.acceleration);
906
907 dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
908 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
909 mConfig.wheelVelocityControlParameters.scale,
910 mConfig.wheelVelocityControlParameters.lowThreshold,
911 mConfig.wheelVelocityControlParameters.highThreshold,
912 mConfig.wheelVelocityControlParameters.acceleration);
913
914 dump.appendFormat(INDENT2 "PointerGesture:\n");
915 dump.appendFormat(INDENT3 "Enabled: %s\n",
916 toString(mConfig.pointerGesturesEnabled));
917 dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
918 mConfig.pointerGestureQuietInterval * 0.000001f);
919 dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
920 mConfig.pointerGestureDragMinSwitchSpeed);
921 dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
922 mConfig.pointerGestureTapInterval * 0.000001f);
923 dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
924 mConfig.pointerGestureTapDragInterval * 0.000001f);
925 dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
926 mConfig.pointerGestureTapSlop);
927 dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
928 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
929 dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
930 mConfig.pointerGestureMultitouchMinDistance);
931 dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
932 mConfig.pointerGestureSwipeTransitionAngleCosine);
933 dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
934 mConfig.pointerGestureSwipeMaxWidthRatio);
935 dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
936 mConfig.pointerGestureMovementSpeedRatio);
937 dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
938 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700939
940 dump.append(INDENT3 "Viewports:\n");
941 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800942}
943
944void InputReader::monitor() {
945 // Acquire and release the lock to ensure that the reader has not deadlocked.
946 mLock.lock();
947 mEventHub->wake();
948 mReaderIsAliveCondition.wait(mLock);
949 mLock.unlock();
950
951 // Check the EventHub
952 mEventHub->monitor();
953}
954
955
956// --- InputReader::ContextImpl ---
957
958InputReader::ContextImpl::ContextImpl(InputReader* reader) :
959 mReader(reader) {
960}
961
962void InputReader::ContextImpl::updateGlobalMetaState() {
963 // lock is already held by the input loop
964 mReader->updateGlobalMetaStateLocked();
965}
966
967int32_t InputReader::ContextImpl::getGlobalMetaState() {
968 // lock is already held by the input loop
969 return mReader->getGlobalMetaStateLocked();
970}
971
972void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
973 // lock is already held by the input loop
974 mReader->disableVirtualKeysUntilLocked(time);
975}
976
977bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
978 InputDevice* device, int32_t keyCode, int32_t scanCode) {
979 // lock is already held by the input loop
980 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
981}
982
983void InputReader::ContextImpl::fadePointer() {
984 // lock is already held by the input loop
985 mReader->fadePointerLocked();
986}
987
988void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
989 // lock is already held by the input loop
990 mReader->requestTimeoutAtTimeLocked(when);
991}
992
993int32_t InputReader::ContextImpl::bumpGeneration() {
994 // lock is already held by the input loop
995 return mReader->bumpGenerationLocked();
996}
997
Michael Wright842500e2015-03-13 17:32:02 -0700998void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
999 // lock is already held by whatever called refreshConfigurationLocked
1000 mReader->getExternalStylusDevicesLocked(outDevices);
1001}
1002
1003void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
1004 mReader->dispatchExternalStylusState(state);
1005}
1006
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
1008 return mReader->mPolicy.get();
1009}
1010
1011InputListenerInterface* InputReader::ContextImpl::getListener() {
1012 return mReader->mQueuedListener.get();
1013}
1014
1015EventHubInterface* InputReader::ContextImpl::getEventHub() {
1016 return mReader->mEventHub.get();
1017}
1018
1019
1020// --- InputReaderThread ---
1021
1022InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
1023 Thread(/*canCallJava*/ true), mReader(reader) {
1024}
1025
1026InputReaderThread::~InputReaderThread() {
1027}
1028
1029bool InputReaderThread::threadLoop() {
1030 mReader->loopOnce();
1031 return true;
1032}
1033
1034
1035// --- InputDevice ---
1036
1037InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
1038 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
1039 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
1040 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -07001041 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042}
1043
1044InputDevice::~InputDevice() {
1045 size_t numMappers = mMappers.size();
1046 for (size_t i = 0; i < numMappers; i++) {
1047 delete mMappers[i];
1048 }
1049 mMappers.clear();
1050}
1051
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001052bool InputDevice::isEnabled() {
1053 return getEventHub()->isDeviceEnabled(mId);
1054}
1055
1056void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1057 if (isEnabled() == enabled) {
1058 return;
1059 }
1060
1061 if (enabled) {
1062 getEventHub()->enableDevice(mId);
1063 reset(when);
1064 } else {
1065 reset(when);
1066 getEventHub()->disableDevice(mId);
1067 }
1068 // Must change generation to flag this device as changed
1069 bumpGeneration();
1070}
1071
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072void InputDevice::dump(String8& dump) {
1073 InputDeviceInfo deviceInfo;
1074 getDeviceInfo(& deviceInfo);
1075
1076 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
1077 deviceInfo.getDisplayName().string());
1078 dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration);
1079 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Tim Kilbourn063ff532015-04-08 10:26:18 -07001080 dump.appendFormat(INDENT2 "HasMic: %s\n", toString(mHasMic));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001081 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1082 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
1083
1084 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1085 if (!ranges.isEmpty()) {
1086 dump.append(INDENT2 "Motion Ranges:\n");
1087 for (size_t i = 0; i < ranges.size(); i++) {
1088 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1089 const char* label = getAxisLabel(range.axis);
1090 char name[32];
1091 if (label) {
1092 strncpy(name, label, sizeof(name));
1093 name[sizeof(name) - 1] = '\0';
1094 } else {
1095 snprintf(name, sizeof(name), "%d", range.axis);
1096 }
1097 dump.appendFormat(INDENT3 "%s: source=0x%08x, "
1098 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1099 name, range.source, range.min, range.max, range.flat, range.fuzz,
1100 range.resolution);
1101 }
1102 }
1103
1104 size_t numMappers = mMappers.size();
1105 for (size_t i = 0; i < numMappers; i++) {
1106 InputMapper* mapper = mMappers[i];
1107 mapper->dump(dump);
1108 }
1109}
1110
1111void InputDevice::addMapper(InputMapper* mapper) {
1112 mMappers.add(mapper);
1113}
1114
1115void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1116 mSources = 0;
1117
1118 if (!isIgnored()) {
1119 if (!changes) { // first time only
1120 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1121 }
1122
1123 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1124 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1125 sp<KeyCharacterMap> keyboardLayout =
1126 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1127 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1128 bumpGeneration();
1129 }
1130 }
1131 }
1132
1133 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1134 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1135 String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
1136 if (mAlias != alias) {
1137 mAlias = alias;
1138 bumpGeneration();
1139 }
1140 }
1141 }
1142
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001143 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1144 ssize_t index = config->disabledDevices.indexOf(mId);
1145 bool enabled = index < 0;
1146 setEnabled(enabled, when);
1147 }
1148
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 size_t numMappers = mMappers.size();
1150 for (size_t i = 0; i < numMappers; i++) {
1151 InputMapper* mapper = mMappers[i];
1152 mapper->configure(when, config, changes);
1153 mSources |= mapper->getSources();
1154 }
1155 }
1156}
1157
1158void InputDevice::reset(nsecs_t when) {
1159 size_t numMappers = mMappers.size();
1160 for (size_t i = 0; i < numMappers; i++) {
1161 InputMapper* mapper = mMappers[i];
1162 mapper->reset(when);
1163 }
1164
1165 mContext->updateGlobalMetaState();
1166
1167 notifyReset(when);
1168}
1169
1170void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1171 // Process all of the events in order for each mapper.
1172 // We cannot simply ask each mapper to process them in bulk because mappers may
1173 // have side-effects that must be interleaved. For example, joystick movement events and
1174 // gamepad button presses are handled by different mappers but they should be dispatched
1175 // in the order received.
1176 size_t numMappers = mMappers.size();
1177 for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
1178#if DEBUG_RAW_EVENTS
1179 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",
1180 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1181 rawEvent->when);
1182#endif
1183
1184 if (mDropUntilNextSync) {
1185 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1186 mDropUntilNextSync = false;
1187#if DEBUG_RAW_EVENTS
1188 ALOGD("Recovered from input event buffer overrun.");
1189#endif
1190 } else {
1191#if DEBUG_RAW_EVENTS
1192 ALOGD("Dropped input event while waiting for next input sync.");
1193#endif
1194 }
1195 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
1196 ALOGI("Detected input event buffer overrun for device %s.", getName().string());
1197 mDropUntilNextSync = true;
1198 reset(rawEvent->when);
1199 } else {
1200 for (size_t i = 0; i < numMappers; i++) {
1201 InputMapper* mapper = mMappers[i];
1202 mapper->process(rawEvent);
1203 }
1204 }
1205 }
1206}
1207
1208void InputDevice::timeoutExpired(nsecs_t when) {
1209 size_t numMappers = mMappers.size();
1210 for (size_t i = 0; i < numMappers; i++) {
1211 InputMapper* mapper = mMappers[i];
1212 mapper->timeoutExpired(when);
1213 }
1214}
1215
Michael Wright842500e2015-03-13 17:32:02 -07001216void InputDevice::updateExternalStylusState(const StylusState& state) {
1217 size_t numMappers = mMappers.size();
1218 for (size_t i = 0; i < numMappers; i++) {
1219 InputMapper* mapper = mMappers[i];
1220 mapper->updateExternalStylusState(state);
1221 }
1222}
1223
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1225 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001226 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 size_t numMappers = mMappers.size();
1228 for (size_t i = 0; i < numMappers; i++) {
1229 InputMapper* mapper = mMappers[i];
1230 mapper->populateDeviceInfo(outDeviceInfo);
1231 }
1232}
1233
1234int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1235 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1236}
1237
1238int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1239 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1240}
1241
1242int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1243 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1244}
1245
1246int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1247 int32_t result = AKEY_STATE_UNKNOWN;
1248 size_t numMappers = mMappers.size();
1249 for (size_t i = 0; i < numMappers; i++) {
1250 InputMapper* mapper = mMappers[i];
1251 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1252 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1253 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1254 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1255 if (currentResult >= AKEY_STATE_DOWN) {
1256 return currentResult;
1257 } else if (currentResult == AKEY_STATE_UP) {
1258 result = currentResult;
1259 }
1260 }
1261 }
1262 return result;
1263}
1264
1265bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1266 const int32_t* keyCodes, uint8_t* outFlags) {
1267 bool result = false;
1268 size_t numMappers = mMappers.size();
1269 for (size_t i = 0; i < numMappers; i++) {
1270 InputMapper* mapper = mMappers[i];
1271 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1272 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1273 }
1274 }
1275 return result;
1276}
1277
1278void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1279 int32_t token) {
1280 size_t numMappers = mMappers.size();
1281 for (size_t i = 0; i < numMappers; i++) {
1282 InputMapper* mapper = mMappers[i];
1283 mapper->vibrate(pattern, patternSize, repeat, token);
1284 }
1285}
1286
1287void InputDevice::cancelVibrate(int32_t token) {
1288 size_t numMappers = mMappers.size();
1289 for (size_t i = 0; i < numMappers; i++) {
1290 InputMapper* mapper = mMappers[i];
1291 mapper->cancelVibrate(token);
1292 }
1293}
1294
Jeff Brownc9aa6282015-02-11 19:03:28 -08001295void InputDevice::cancelTouch(nsecs_t when) {
1296 size_t numMappers = mMappers.size();
1297 for (size_t i = 0; i < numMappers; i++) {
1298 InputMapper* mapper = mMappers[i];
1299 mapper->cancelTouch(when);
1300 }
1301}
1302
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303int32_t InputDevice::getMetaState() {
1304 int32_t result = 0;
1305 size_t numMappers = mMappers.size();
1306 for (size_t i = 0; i < numMappers; i++) {
1307 InputMapper* mapper = mMappers[i];
1308 result |= mapper->getMetaState();
1309 }
1310 return result;
1311}
1312
Andrii Kulian763a3a42016-03-08 10:46:16 -08001313void InputDevice::updateMetaState(int32_t keyCode) {
1314 size_t numMappers = mMappers.size();
1315 for (size_t i = 0; i < numMappers; i++) {
1316 mMappers[i]->updateMetaState(keyCode);
1317 }
1318}
1319
Michael Wrightd02c5b62014-02-10 15:10:22 -08001320void InputDevice::fadePointer() {
1321 size_t numMappers = mMappers.size();
1322 for (size_t i = 0; i < numMappers; i++) {
1323 InputMapper* mapper = mMappers[i];
1324 mapper->fadePointer();
1325 }
1326}
1327
1328void InputDevice::bumpGeneration() {
1329 mGeneration = mContext->bumpGeneration();
1330}
1331
1332void InputDevice::notifyReset(nsecs_t when) {
1333 NotifyDeviceResetArgs args(when, mId);
1334 mContext->getListener()->notifyDeviceReset(&args);
1335}
1336
1337
1338// --- CursorButtonAccumulator ---
1339
1340CursorButtonAccumulator::CursorButtonAccumulator() {
1341 clearButtons();
1342}
1343
1344void CursorButtonAccumulator::reset(InputDevice* device) {
1345 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1346 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1347 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1348 mBtnBack = device->isKeyPressed(BTN_BACK);
1349 mBtnSide = device->isKeyPressed(BTN_SIDE);
1350 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1351 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1352 mBtnTask = device->isKeyPressed(BTN_TASK);
1353}
1354
1355void CursorButtonAccumulator::clearButtons() {
1356 mBtnLeft = 0;
1357 mBtnRight = 0;
1358 mBtnMiddle = 0;
1359 mBtnBack = 0;
1360 mBtnSide = 0;
1361 mBtnForward = 0;
1362 mBtnExtra = 0;
1363 mBtnTask = 0;
1364}
1365
1366void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1367 if (rawEvent->type == EV_KEY) {
1368 switch (rawEvent->code) {
1369 case BTN_LEFT:
1370 mBtnLeft = rawEvent->value;
1371 break;
1372 case BTN_RIGHT:
1373 mBtnRight = rawEvent->value;
1374 break;
1375 case BTN_MIDDLE:
1376 mBtnMiddle = rawEvent->value;
1377 break;
1378 case BTN_BACK:
1379 mBtnBack = rawEvent->value;
1380 break;
1381 case BTN_SIDE:
1382 mBtnSide = rawEvent->value;
1383 break;
1384 case BTN_FORWARD:
1385 mBtnForward = rawEvent->value;
1386 break;
1387 case BTN_EXTRA:
1388 mBtnExtra = rawEvent->value;
1389 break;
1390 case BTN_TASK:
1391 mBtnTask = rawEvent->value;
1392 break;
1393 }
1394 }
1395}
1396
1397uint32_t CursorButtonAccumulator::getButtonState() const {
1398 uint32_t result = 0;
1399 if (mBtnLeft) {
1400 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1401 }
1402 if (mBtnRight) {
1403 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1404 }
1405 if (mBtnMiddle) {
1406 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1407 }
1408 if (mBtnBack || mBtnSide) {
1409 result |= AMOTION_EVENT_BUTTON_BACK;
1410 }
1411 if (mBtnForward || mBtnExtra) {
1412 result |= AMOTION_EVENT_BUTTON_FORWARD;
1413 }
1414 return result;
1415}
1416
1417
1418// --- CursorMotionAccumulator ---
1419
1420CursorMotionAccumulator::CursorMotionAccumulator() {
1421 clearRelativeAxes();
1422}
1423
1424void CursorMotionAccumulator::reset(InputDevice* device) {
1425 clearRelativeAxes();
1426}
1427
1428void CursorMotionAccumulator::clearRelativeAxes() {
1429 mRelX = 0;
1430 mRelY = 0;
1431}
1432
1433void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1434 if (rawEvent->type == EV_REL) {
1435 switch (rawEvent->code) {
1436 case REL_X:
1437 mRelX = rawEvent->value;
1438 break;
1439 case REL_Y:
1440 mRelY = rawEvent->value;
1441 break;
1442 }
1443 }
1444}
1445
1446void CursorMotionAccumulator::finishSync() {
1447 clearRelativeAxes();
1448}
1449
1450
1451// --- CursorScrollAccumulator ---
1452
1453CursorScrollAccumulator::CursorScrollAccumulator() :
1454 mHaveRelWheel(false), mHaveRelHWheel(false) {
1455 clearRelativeAxes();
1456}
1457
1458void CursorScrollAccumulator::configure(InputDevice* device) {
1459 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1460 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1461}
1462
1463void CursorScrollAccumulator::reset(InputDevice* device) {
1464 clearRelativeAxes();
1465}
1466
1467void CursorScrollAccumulator::clearRelativeAxes() {
1468 mRelWheel = 0;
1469 mRelHWheel = 0;
1470}
1471
1472void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1473 if (rawEvent->type == EV_REL) {
1474 switch (rawEvent->code) {
1475 case REL_WHEEL:
1476 mRelWheel = rawEvent->value;
1477 break;
1478 case REL_HWHEEL:
1479 mRelHWheel = rawEvent->value;
1480 break;
1481 }
1482 }
1483}
1484
1485void CursorScrollAccumulator::finishSync() {
1486 clearRelativeAxes();
1487}
1488
1489
1490// --- TouchButtonAccumulator ---
1491
1492TouchButtonAccumulator::TouchButtonAccumulator() :
1493 mHaveBtnTouch(false), mHaveStylus(false) {
1494 clearButtons();
1495}
1496
1497void TouchButtonAccumulator::configure(InputDevice* device) {
1498 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1499 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1500 || device->hasKey(BTN_TOOL_RUBBER)
1501 || device->hasKey(BTN_TOOL_BRUSH)
1502 || device->hasKey(BTN_TOOL_PENCIL)
1503 || device->hasKey(BTN_TOOL_AIRBRUSH);
1504}
1505
1506void TouchButtonAccumulator::reset(InputDevice* device) {
1507 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1508 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001509 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1510 mBtnStylus2 =
1511 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1513 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1514 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1515 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1516 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1517 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1518 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1519 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1520 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1521 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1522 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1523}
1524
1525void TouchButtonAccumulator::clearButtons() {
1526 mBtnTouch = 0;
1527 mBtnStylus = 0;
1528 mBtnStylus2 = 0;
1529 mBtnToolFinger = 0;
1530 mBtnToolPen = 0;
1531 mBtnToolRubber = 0;
1532 mBtnToolBrush = 0;
1533 mBtnToolPencil = 0;
1534 mBtnToolAirbrush = 0;
1535 mBtnToolMouse = 0;
1536 mBtnToolLens = 0;
1537 mBtnToolDoubleTap = 0;
1538 mBtnToolTripleTap = 0;
1539 mBtnToolQuadTap = 0;
1540}
1541
1542void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1543 if (rawEvent->type == EV_KEY) {
1544 switch (rawEvent->code) {
1545 case BTN_TOUCH:
1546 mBtnTouch = rawEvent->value;
1547 break;
1548 case BTN_STYLUS:
1549 mBtnStylus = rawEvent->value;
1550 break;
1551 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001552 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001553 mBtnStylus2 = rawEvent->value;
1554 break;
1555 case BTN_TOOL_FINGER:
1556 mBtnToolFinger = rawEvent->value;
1557 break;
1558 case BTN_TOOL_PEN:
1559 mBtnToolPen = rawEvent->value;
1560 break;
1561 case BTN_TOOL_RUBBER:
1562 mBtnToolRubber = rawEvent->value;
1563 break;
1564 case BTN_TOOL_BRUSH:
1565 mBtnToolBrush = rawEvent->value;
1566 break;
1567 case BTN_TOOL_PENCIL:
1568 mBtnToolPencil = rawEvent->value;
1569 break;
1570 case BTN_TOOL_AIRBRUSH:
1571 mBtnToolAirbrush = rawEvent->value;
1572 break;
1573 case BTN_TOOL_MOUSE:
1574 mBtnToolMouse = rawEvent->value;
1575 break;
1576 case BTN_TOOL_LENS:
1577 mBtnToolLens = rawEvent->value;
1578 break;
1579 case BTN_TOOL_DOUBLETAP:
1580 mBtnToolDoubleTap = rawEvent->value;
1581 break;
1582 case BTN_TOOL_TRIPLETAP:
1583 mBtnToolTripleTap = rawEvent->value;
1584 break;
1585 case BTN_TOOL_QUADTAP:
1586 mBtnToolQuadTap = rawEvent->value;
1587 break;
1588 }
1589 }
1590}
1591
1592uint32_t TouchButtonAccumulator::getButtonState() const {
1593 uint32_t result = 0;
1594 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001595 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 }
1597 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001598 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001599 }
1600 return result;
1601}
1602
1603int32_t TouchButtonAccumulator::getToolType() const {
1604 if (mBtnToolMouse || mBtnToolLens) {
1605 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1606 }
1607 if (mBtnToolRubber) {
1608 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1609 }
1610 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1611 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1612 }
1613 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1614 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1615 }
1616 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1617}
1618
1619bool TouchButtonAccumulator::isToolActive() const {
1620 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1621 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1622 || mBtnToolMouse || mBtnToolLens
1623 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1624}
1625
1626bool TouchButtonAccumulator::isHovering() const {
1627 return mHaveBtnTouch && !mBtnTouch;
1628}
1629
1630bool TouchButtonAccumulator::hasStylus() const {
1631 return mHaveStylus;
1632}
1633
1634
1635// --- RawPointerAxes ---
1636
1637RawPointerAxes::RawPointerAxes() {
1638 clear();
1639}
1640
1641void RawPointerAxes::clear() {
1642 x.clear();
1643 y.clear();
1644 pressure.clear();
1645 touchMajor.clear();
1646 touchMinor.clear();
1647 toolMajor.clear();
1648 toolMinor.clear();
1649 orientation.clear();
1650 distance.clear();
1651 tiltX.clear();
1652 tiltY.clear();
1653 trackingId.clear();
1654 slot.clear();
1655}
1656
1657
1658// --- RawPointerData ---
1659
1660RawPointerData::RawPointerData() {
1661 clear();
1662}
1663
1664void RawPointerData::clear() {
1665 pointerCount = 0;
1666 clearIdBits();
1667}
1668
1669void RawPointerData::copyFrom(const RawPointerData& other) {
1670 pointerCount = other.pointerCount;
1671 hoveringIdBits = other.hoveringIdBits;
1672 touchingIdBits = other.touchingIdBits;
1673
1674 for (uint32_t i = 0; i < pointerCount; i++) {
1675 pointers[i] = other.pointers[i];
1676
1677 int id = pointers[i].id;
1678 idToIndex[id] = other.idToIndex[id];
1679 }
1680}
1681
1682void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1683 float x = 0, y = 0;
1684 uint32_t count = touchingIdBits.count();
1685 if (count) {
1686 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1687 uint32_t id = idBits.clearFirstMarkedBit();
1688 const Pointer& pointer = pointerForId(id);
1689 x += pointer.x;
1690 y += pointer.y;
1691 }
1692 x /= count;
1693 y /= count;
1694 }
1695 *outX = x;
1696 *outY = y;
1697}
1698
1699
1700// --- CookedPointerData ---
1701
1702CookedPointerData::CookedPointerData() {
1703 clear();
1704}
1705
1706void CookedPointerData::clear() {
1707 pointerCount = 0;
1708 hoveringIdBits.clear();
1709 touchingIdBits.clear();
1710}
1711
1712void CookedPointerData::copyFrom(const CookedPointerData& other) {
1713 pointerCount = other.pointerCount;
1714 hoveringIdBits = other.hoveringIdBits;
1715 touchingIdBits = other.touchingIdBits;
1716
1717 for (uint32_t i = 0; i < pointerCount; i++) {
1718 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1719 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1720
1721 int id = pointerProperties[i].id;
1722 idToIndex[id] = other.idToIndex[id];
1723 }
1724}
1725
1726
1727// --- SingleTouchMotionAccumulator ---
1728
1729SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1730 clearAbsoluteAxes();
1731}
1732
1733void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1734 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1735 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1736 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1737 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1738 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1739 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1740 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1741}
1742
1743void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1744 mAbsX = 0;
1745 mAbsY = 0;
1746 mAbsPressure = 0;
1747 mAbsToolWidth = 0;
1748 mAbsDistance = 0;
1749 mAbsTiltX = 0;
1750 mAbsTiltY = 0;
1751}
1752
1753void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1754 if (rawEvent->type == EV_ABS) {
1755 switch (rawEvent->code) {
1756 case ABS_X:
1757 mAbsX = rawEvent->value;
1758 break;
1759 case ABS_Y:
1760 mAbsY = rawEvent->value;
1761 break;
1762 case ABS_PRESSURE:
1763 mAbsPressure = rawEvent->value;
1764 break;
1765 case ABS_TOOL_WIDTH:
1766 mAbsToolWidth = rawEvent->value;
1767 break;
1768 case ABS_DISTANCE:
1769 mAbsDistance = rawEvent->value;
1770 break;
1771 case ABS_TILT_X:
1772 mAbsTiltX = rawEvent->value;
1773 break;
1774 case ABS_TILT_Y:
1775 mAbsTiltY = rawEvent->value;
1776 break;
1777 }
1778 }
1779}
1780
1781
1782// --- MultiTouchMotionAccumulator ---
1783
1784MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1785 mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
1786 mHaveStylus(false) {
1787}
1788
1789MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1790 delete[] mSlots;
1791}
1792
1793void MultiTouchMotionAccumulator::configure(InputDevice* device,
1794 size_t slotCount, bool usingSlotsProtocol) {
1795 mSlotCount = slotCount;
1796 mUsingSlotsProtocol = usingSlotsProtocol;
1797 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1798
1799 delete[] mSlots;
1800 mSlots = new Slot[slotCount];
1801}
1802
1803void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1804 // Unfortunately there is no way to read the initial contents of the slots.
1805 // So when we reset the accumulator, we must assume they are all zeroes.
1806 if (mUsingSlotsProtocol) {
1807 // Query the driver for the current slot index and use it as the initial slot
1808 // before we start reading events from the device. It is possible that the
1809 // current slot index will not be the same as it was when the first event was
1810 // written into the evdev buffer, which means the input mapper could start
1811 // out of sync with the initial state of the events in the evdev buffer.
1812 // In the extremely unlikely case that this happens, the data from
1813 // two slots will be confused until the next ABS_MT_SLOT event is received.
1814 // This can cause the touch point to "jump", but at least there will be
1815 // no stuck touches.
1816 int32_t initialSlot;
1817 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1818 ABS_MT_SLOT, &initialSlot);
1819 if (status) {
1820 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1821 initialSlot = -1;
1822 }
1823 clearSlots(initialSlot);
1824 } else {
1825 clearSlots(-1);
1826 }
1827}
1828
1829void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1830 if (mSlots) {
1831 for (size_t i = 0; i < mSlotCount; i++) {
1832 mSlots[i].clear();
1833 }
1834 }
1835 mCurrentSlot = initialSlot;
1836}
1837
1838void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1839 if (rawEvent->type == EV_ABS) {
1840 bool newSlot = false;
1841 if (mUsingSlotsProtocol) {
1842 if (rawEvent->code == ABS_MT_SLOT) {
1843 mCurrentSlot = rawEvent->value;
1844 newSlot = true;
1845 }
1846 } else if (mCurrentSlot < 0) {
1847 mCurrentSlot = 0;
1848 }
1849
1850 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1851#if DEBUG_POINTERS
1852 if (newSlot) {
1853 ALOGW("MultiTouch device emitted invalid slot index %d but it "
1854 "should be between 0 and %d; ignoring this slot.",
1855 mCurrentSlot, mSlotCount - 1);
1856 }
1857#endif
1858 } else {
1859 Slot* slot = &mSlots[mCurrentSlot];
1860
1861 switch (rawEvent->code) {
1862 case ABS_MT_POSITION_X:
1863 slot->mInUse = true;
1864 slot->mAbsMTPositionX = rawEvent->value;
1865 break;
1866 case ABS_MT_POSITION_Y:
1867 slot->mInUse = true;
1868 slot->mAbsMTPositionY = rawEvent->value;
1869 break;
1870 case ABS_MT_TOUCH_MAJOR:
1871 slot->mInUse = true;
1872 slot->mAbsMTTouchMajor = rawEvent->value;
1873 break;
1874 case ABS_MT_TOUCH_MINOR:
1875 slot->mInUse = true;
1876 slot->mAbsMTTouchMinor = rawEvent->value;
1877 slot->mHaveAbsMTTouchMinor = true;
1878 break;
1879 case ABS_MT_WIDTH_MAJOR:
1880 slot->mInUse = true;
1881 slot->mAbsMTWidthMajor = rawEvent->value;
1882 break;
1883 case ABS_MT_WIDTH_MINOR:
1884 slot->mInUse = true;
1885 slot->mAbsMTWidthMinor = rawEvent->value;
1886 slot->mHaveAbsMTWidthMinor = true;
1887 break;
1888 case ABS_MT_ORIENTATION:
1889 slot->mInUse = true;
1890 slot->mAbsMTOrientation = rawEvent->value;
1891 break;
1892 case ABS_MT_TRACKING_ID:
1893 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1894 // The slot is no longer in use but it retains its previous contents,
1895 // which may be reused for subsequent touches.
1896 slot->mInUse = false;
1897 } else {
1898 slot->mInUse = true;
1899 slot->mAbsMTTrackingId = rawEvent->value;
1900 }
1901 break;
1902 case ABS_MT_PRESSURE:
1903 slot->mInUse = true;
1904 slot->mAbsMTPressure = rawEvent->value;
1905 break;
1906 case ABS_MT_DISTANCE:
1907 slot->mInUse = true;
1908 slot->mAbsMTDistance = rawEvent->value;
1909 break;
1910 case ABS_MT_TOOL_TYPE:
1911 slot->mInUse = true;
1912 slot->mAbsMTToolType = rawEvent->value;
1913 slot->mHaveAbsMTToolType = true;
1914 break;
1915 }
1916 }
1917 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1918 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1919 mCurrentSlot += 1;
1920 }
1921}
1922
1923void MultiTouchMotionAccumulator::finishSync() {
1924 if (!mUsingSlotsProtocol) {
1925 clearSlots(-1);
1926 }
1927}
1928
1929bool MultiTouchMotionAccumulator::hasStylus() const {
1930 return mHaveStylus;
1931}
1932
1933
1934// --- MultiTouchMotionAccumulator::Slot ---
1935
1936MultiTouchMotionAccumulator::Slot::Slot() {
1937 clear();
1938}
1939
1940void MultiTouchMotionAccumulator::Slot::clear() {
1941 mInUse = false;
1942 mHaveAbsMTTouchMinor = false;
1943 mHaveAbsMTWidthMinor = false;
1944 mHaveAbsMTToolType = false;
1945 mAbsMTPositionX = 0;
1946 mAbsMTPositionY = 0;
1947 mAbsMTTouchMajor = 0;
1948 mAbsMTTouchMinor = 0;
1949 mAbsMTWidthMajor = 0;
1950 mAbsMTWidthMinor = 0;
1951 mAbsMTOrientation = 0;
1952 mAbsMTTrackingId = -1;
1953 mAbsMTPressure = 0;
1954 mAbsMTDistance = 0;
1955 mAbsMTToolType = 0;
1956}
1957
1958int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1959 if (mHaveAbsMTToolType) {
1960 switch (mAbsMTToolType) {
1961 case MT_TOOL_FINGER:
1962 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1963 case MT_TOOL_PEN:
1964 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1965 }
1966 }
1967 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1968}
1969
1970
1971// --- InputMapper ---
1972
1973InputMapper::InputMapper(InputDevice* device) :
1974 mDevice(device), mContext(device->getContext()) {
1975}
1976
1977InputMapper::~InputMapper() {
1978}
1979
1980void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1981 info->addSource(getSources());
1982}
1983
1984void InputMapper::dump(String8& dump) {
1985}
1986
1987void InputMapper::configure(nsecs_t when,
1988 const InputReaderConfiguration* config, uint32_t changes) {
1989}
1990
1991void InputMapper::reset(nsecs_t when) {
1992}
1993
1994void InputMapper::timeoutExpired(nsecs_t when) {
1995}
1996
1997int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1998 return AKEY_STATE_UNKNOWN;
1999}
2000
2001int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2002 return AKEY_STATE_UNKNOWN;
2003}
2004
2005int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2006 return AKEY_STATE_UNKNOWN;
2007}
2008
2009bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2010 const int32_t* keyCodes, uint8_t* outFlags) {
2011 return false;
2012}
2013
2014void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2015 int32_t token) {
2016}
2017
2018void InputMapper::cancelVibrate(int32_t token) {
2019}
2020
Jeff Brownc9aa6282015-02-11 19:03:28 -08002021void InputMapper::cancelTouch(nsecs_t when) {
2022}
2023
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024int32_t InputMapper::getMetaState() {
2025 return 0;
2026}
2027
Andrii Kulian763a3a42016-03-08 10:46:16 -08002028void InputMapper::updateMetaState(int32_t keyCode) {
2029}
2030
Michael Wright842500e2015-03-13 17:32:02 -07002031void InputMapper::updateExternalStylusState(const StylusState& state) {
2032
2033}
2034
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035void InputMapper::fadePointer() {
2036}
2037
2038status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2039 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2040}
2041
2042void InputMapper::bumpGeneration() {
2043 mDevice->bumpGeneration();
2044}
2045
2046void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
2047 const RawAbsoluteAxisInfo& axis, const char* name) {
2048 if (axis.valid) {
2049 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
2050 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2051 } else {
2052 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
2053 }
2054}
2055
Michael Wright842500e2015-03-13 17:32:02 -07002056void InputMapper::dumpStylusState(String8& dump, const StylusState& state) {
2057 dump.appendFormat(INDENT4 "When: %" PRId64 "\n", state.when);
2058 dump.appendFormat(INDENT4 "Pressure: %f\n", state.pressure);
2059 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", state.buttons);
2060 dump.appendFormat(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
2061}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062
2063// --- SwitchInputMapper ---
2064
2065SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002066 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067}
2068
2069SwitchInputMapper::~SwitchInputMapper() {
2070}
2071
2072uint32_t SwitchInputMapper::getSources() {
2073 return AINPUT_SOURCE_SWITCH;
2074}
2075
2076void SwitchInputMapper::process(const RawEvent* rawEvent) {
2077 switch (rawEvent->type) {
2078 case EV_SW:
2079 processSwitch(rawEvent->code, rawEvent->value);
2080 break;
2081
2082 case EV_SYN:
2083 if (rawEvent->code == SYN_REPORT) {
2084 sync(rawEvent->when);
2085 }
2086 }
2087}
2088
2089void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2090 if (switchCode >= 0 && switchCode < 32) {
2091 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002092 mSwitchValues |= 1 << switchCode;
2093 } else {
2094 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095 }
2096 mUpdatedSwitchMask |= 1 << switchCode;
2097 }
2098}
2099
2100void SwitchInputMapper::sync(nsecs_t when) {
2101 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002102 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002103 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 getListener()->notifySwitch(&args);
2105
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 mUpdatedSwitchMask = 0;
2107 }
2108}
2109
2110int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2111 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2112}
2113
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002114void SwitchInputMapper::dump(String8& dump) {
2115 dump.append(INDENT2 "Switch Input Mapper:\n");
2116 dump.appendFormat(INDENT3 "SwitchValues: %x\n", mSwitchValues);
2117}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118
2119// --- VibratorInputMapper ---
2120
2121VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2122 InputMapper(device), mVibrating(false) {
2123}
2124
2125VibratorInputMapper::~VibratorInputMapper() {
2126}
2127
2128uint32_t VibratorInputMapper::getSources() {
2129 return 0;
2130}
2131
2132void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2133 InputMapper::populateDeviceInfo(info);
2134
2135 info->setVibrator(true);
2136}
2137
2138void VibratorInputMapper::process(const RawEvent* rawEvent) {
2139 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2140}
2141
2142void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2143 int32_t token) {
2144#if DEBUG_VIBRATOR
2145 String8 patternStr;
2146 for (size_t i = 0; i < patternSize; i++) {
2147 if (i != 0) {
2148 patternStr.append(", ");
2149 }
2150 patternStr.appendFormat("%lld", pattern[i]);
2151 }
2152 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d",
2153 getDeviceId(), patternStr.string(), repeat, token);
2154#endif
2155
2156 mVibrating = true;
2157 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2158 mPatternSize = patternSize;
2159 mRepeat = repeat;
2160 mToken = token;
2161 mIndex = -1;
2162
2163 nextStep();
2164}
2165
2166void VibratorInputMapper::cancelVibrate(int32_t token) {
2167#if DEBUG_VIBRATOR
2168 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2169#endif
2170
2171 if (mVibrating && mToken == token) {
2172 stopVibrating();
2173 }
2174}
2175
2176void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2177 if (mVibrating) {
2178 if (when >= mNextStepTime) {
2179 nextStep();
2180 } else {
2181 getContext()->requestTimeoutAtTime(mNextStepTime);
2182 }
2183 }
2184}
2185
2186void VibratorInputMapper::nextStep() {
2187 mIndex += 1;
2188 if (size_t(mIndex) >= mPatternSize) {
2189 if (mRepeat < 0) {
2190 // We are done.
2191 stopVibrating();
2192 return;
2193 }
2194 mIndex = mRepeat;
2195 }
2196
2197 bool vibratorOn = mIndex & 1;
2198 nsecs_t duration = mPattern[mIndex];
2199 if (vibratorOn) {
2200#if DEBUG_VIBRATOR
2201 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld",
2202 getDeviceId(), duration);
2203#endif
2204 getEventHub()->vibrate(getDeviceId(), duration);
2205 } else {
2206#if DEBUG_VIBRATOR
2207 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2208#endif
2209 getEventHub()->cancelVibrate(getDeviceId());
2210 }
2211 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2212 mNextStepTime = now + duration;
2213 getContext()->requestTimeoutAtTime(mNextStepTime);
2214#if DEBUG_VIBRATOR
2215 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2216#endif
2217}
2218
2219void VibratorInputMapper::stopVibrating() {
2220 mVibrating = false;
2221#if DEBUG_VIBRATOR
2222 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2223#endif
2224 getEventHub()->cancelVibrate(getDeviceId());
2225}
2226
2227void VibratorInputMapper::dump(String8& dump) {
2228 dump.append(INDENT2 "Vibrator Input Mapper:\n");
2229 dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
2230}
2231
2232
2233// --- KeyboardInputMapper ---
2234
2235KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2236 uint32_t source, int32_t keyboardType) :
2237 InputMapper(device), mSource(source),
2238 mKeyboardType(keyboardType) {
2239}
2240
2241KeyboardInputMapper::~KeyboardInputMapper() {
2242}
2243
2244uint32_t KeyboardInputMapper::getSources() {
2245 return mSource;
2246}
2247
2248void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2249 InputMapper::populateDeviceInfo(info);
2250
2251 info->setKeyboardType(mKeyboardType);
2252 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2253}
2254
2255void KeyboardInputMapper::dump(String8& dump) {
2256 dump.append(INDENT2 "Keyboard Input Mapper:\n");
2257 dumpParameters(dump);
2258 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2259 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002260 dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002262 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263}
2264
2265
2266void KeyboardInputMapper::configure(nsecs_t when,
2267 const InputReaderConfiguration* config, uint32_t changes) {
2268 InputMapper::configure(when, config, changes);
2269
2270 if (!changes) { // first time only
2271 // Configure basic parameters.
2272 configureParameters();
2273 }
2274
2275 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2276 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2277 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002278 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 mOrientation = v.orientation;
2280 } else {
2281 mOrientation = DISPLAY_ORIENTATION_0;
2282 }
2283 } else {
2284 mOrientation = DISPLAY_ORIENTATION_0;
2285 }
2286 }
2287}
2288
Ivan Podogovb9afef32017-02-13 15:34:32 +00002289static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2290 int32_t mapped = 0;
2291 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2292 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2293 if (stemKeyRotationMap[i][0] == keyCode) {
2294 stemKeyRotationMap[i][1] = mapped;
2295 return;
2296 }
2297 }
2298 }
2299}
2300
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301void KeyboardInputMapper::configureParameters() {
2302 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002303 const PropertyMap& config = getDevice()->getConfiguration();
2304 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 mParameters.orientationAware);
2306
2307 mParameters.hasAssociatedDisplay = false;
2308 if (mParameters.orientationAware) {
2309 mParameters.hasAssociatedDisplay = true;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002310
2311 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2312 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2313 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2314 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002316
2317 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002318 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002319 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320}
2321
2322void KeyboardInputMapper::dumpParameters(String8& dump) {
2323 dump.append(INDENT3 "Parameters:\n");
2324 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2325 toString(mParameters.hasAssociatedDisplay));
2326 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2327 toString(mParameters.orientationAware));
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002328 dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n",
2329 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330}
2331
2332void KeyboardInputMapper::reset(nsecs_t when) {
2333 mMetaState = AMETA_NONE;
2334 mDownTime = 0;
2335 mKeyDowns.clear();
2336 mCurrentHidUsage = 0;
2337
2338 resetLedState();
2339
2340 InputMapper::reset(when);
2341}
2342
2343void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2344 switch (rawEvent->type) {
2345 case EV_KEY: {
2346 int32_t scanCode = rawEvent->code;
2347 int32_t usageCode = mCurrentHidUsage;
2348 mCurrentHidUsage = 0;
2349
2350 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002351 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002352 }
2353 break;
2354 }
2355 case EV_MSC: {
2356 if (rawEvent->code == MSC_SCAN) {
2357 mCurrentHidUsage = rawEvent->value;
2358 }
2359 break;
2360 }
2361 case EV_SYN: {
2362 if (rawEvent->code == SYN_REPORT) {
2363 mCurrentHidUsage = 0;
2364 }
2365 }
2366 }
2367}
2368
2369bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2370 return scanCode < BTN_MOUSE
2371 || scanCode >= KEY_OK
2372 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2373 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2374}
2375
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002376void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2377 int32_t usageCode) {
2378 int32_t keyCode;
2379 int32_t keyMetaState;
2380 uint32_t policyFlags;
2381
2382 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2383 &keyCode, &keyMetaState, &policyFlags)) {
2384 keyCode = AKEYCODE_UNKNOWN;
2385 keyMetaState = mMetaState;
2386 policyFlags = 0;
2387 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002388
2389 if (down) {
2390 // Rotate key codes according to orientation if needed.
2391 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2392 keyCode = rotateKeyCode(keyCode, mOrientation);
2393 }
2394
2395 // Add key down.
2396 ssize_t keyDownIndex = findKeyDown(scanCode);
2397 if (keyDownIndex >= 0) {
2398 // key repeat, be sure to use same keycode as before in case of rotation
2399 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2400 } else {
2401 // key down
2402 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2403 && mContext->shouldDropVirtualKey(when,
2404 getDevice(), keyCode, scanCode)) {
2405 return;
2406 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002407 if (policyFlags & POLICY_FLAG_GESTURE) {
2408 mDevice->cancelTouch(when);
2409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410
2411 mKeyDowns.push();
2412 KeyDown& keyDown = mKeyDowns.editTop();
2413 keyDown.keyCode = keyCode;
2414 keyDown.scanCode = scanCode;
2415 }
2416
2417 mDownTime = when;
2418 } else {
2419 // Remove key down.
2420 ssize_t keyDownIndex = findKeyDown(scanCode);
2421 if (keyDownIndex >= 0) {
2422 // key up, be sure to use same keycode as before in case of rotation
2423 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2424 mKeyDowns.removeAt(size_t(keyDownIndex));
2425 } else {
2426 // key was not actually down
2427 ALOGI("Dropping key up from device %s because the key was not down. "
2428 "keyCode=%d, scanCode=%d",
2429 getDeviceName().string(), keyCode, scanCode);
2430 return;
2431 }
2432 }
2433
Andrii Kulian763a3a42016-03-08 10:46:16 -08002434 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002435 // If global meta state changed send it along with the key.
2436 // If it has not changed then we'll use what keymap gave us,
2437 // since key replacement logic might temporarily reset a few
2438 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002439 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440 }
2441
2442 nsecs_t downTime = mDownTime;
2443
2444 // Key down on external an keyboard should wake the device.
2445 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2446 // For internal keyboards, the key layout file should specify the policy flags for
2447 // each wake key individually.
2448 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright872db4f2014-04-22 15:03:51 -07002449 if (down && getDevice()->isExternal()) {
2450 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 }
2452
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002453 if (mParameters.handlesKeyRepeat) {
2454 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2455 }
2456
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2458 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002459 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 getListener()->notifyKey(&args);
2461}
2462
2463ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2464 size_t n = mKeyDowns.size();
2465 for (size_t i = 0; i < n; i++) {
2466 if (mKeyDowns[i].scanCode == scanCode) {
2467 return i;
2468 }
2469 }
2470 return -1;
2471}
2472
2473int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2474 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2475}
2476
2477int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2478 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2479}
2480
2481bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2482 const int32_t* keyCodes, uint8_t* outFlags) {
2483 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2484}
2485
2486int32_t KeyboardInputMapper::getMetaState() {
2487 return mMetaState;
2488}
2489
Andrii Kulian763a3a42016-03-08 10:46:16 -08002490void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2491 updateMetaStateIfNeeded(keyCode, false);
2492}
2493
2494bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2495 int32_t oldMetaState = mMetaState;
2496 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2497 bool metaStateChanged = oldMetaState != newMetaState;
2498 if (metaStateChanged) {
2499 mMetaState = newMetaState;
2500 updateLedState(false);
2501
2502 getContext()->updateGlobalMetaState();
2503 }
2504
2505 return metaStateChanged;
2506}
2507
Michael Wrightd02c5b62014-02-10 15:10:22 -08002508void KeyboardInputMapper::resetLedState() {
2509 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2510 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2511 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2512
2513 updateLedState(true);
2514}
2515
2516void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2517 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2518 ledState.on = false;
2519}
2520
2521void KeyboardInputMapper::updateLedState(bool reset) {
2522 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2523 AMETA_CAPS_LOCK_ON, reset);
2524 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2525 AMETA_NUM_LOCK_ON, reset);
2526 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2527 AMETA_SCROLL_LOCK_ON, reset);
2528}
2529
2530void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2531 int32_t led, int32_t modifier, bool reset) {
2532 if (ledState.avail) {
2533 bool desiredState = (mMetaState & modifier) != 0;
2534 if (reset || ledState.on != desiredState) {
2535 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2536 ledState.on = desiredState;
2537 }
2538 }
2539}
2540
2541
2542// --- CursorInputMapper ---
2543
2544CursorInputMapper::CursorInputMapper(InputDevice* device) :
2545 InputMapper(device) {
2546}
2547
2548CursorInputMapper::~CursorInputMapper() {
2549}
2550
2551uint32_t CursorInputMapper::getSources() {
2552 return mSource;
2553}
2554
2555void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2556 InputMapper::populateDeviceInfo(info);
2557
2558 if (mParameters.mode == Parameters::MODE_POINTER) {
2559 float minX, minY, maxX, maxY;
2560 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2561 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2562 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2563 }
2564 } else {
2565 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2566 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2567 }
2568 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2569
2570 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2571 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2572 }
2573 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2574 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2575 }
2576}
2577
2578void CursorInputMapper::dump(String8& dump) {
2579 dump.append(INDENT2 "Cursor Input Mapper:\n");
2580 dumpParameters(dump);
2581 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2582 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2583 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2584 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2585 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2586 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2587 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2588 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2589 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2590 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2591 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2592 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2593 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002594 dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595}
2596
2597void CursorInputMapper::configure(nsecs_t when,
2598 const InputReaderConfiguration* config, uint32_t changes) {
2599 InputMapper::configure(when, config, changes);
2600
2601 if (!changes) { // first time only
2602 mCursorScrollAccumulator.configure(getDevice());
2603
2604 // Configure basic parameters.
2605 configureParameters();
2606
2607 // Configure device mode.
2608 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002609 case Parameters::MODE_POINTER_RELATIVE:
2610 // Should not happen during first time configuration.
2611 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2612 mParameters.mode = Parameters::MODE_POINTER;
2613 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 case Parameters::MODE_POINTER:
2615 mSource = AINPUT_SOURCE_MOUSE;
2616 mXPrecision = 1.0f;
2617 mYPrecision = 1.0f;
2618 mXScale = 1.0f;
2619 mYScale = 1.0f;
2620 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2621 break;
2622 case Parameters::MODE_NAVIGATION:
2623 mSource = AINPUT_SOURCE_TRACKBALL;
2624 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2625 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2626 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2627 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2628 break;
2629 }
2630
2631 mVWheelScale = 1.0f;
2632 mHWheelScale = 1.0f;
2633 }
2634
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002635 if ((!changes && config->pointerCapture)
2636 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2637 if (config->pointerCapture) {
2638 if (mParameters.mode == Parameters::MODE_POINTER) {
2639 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2640 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2641 // Keep PointerController around in order to preserve the pointer position.
2642 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2643 } else {
2644 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2645 }
2646 } else {
2647 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2648 mParameters.mode = Parameters::MODE_POINTER;
2649 mSource = AINPUT_SOURCE_MOUSE;
2650 } else {
2651 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2652 }
2653 }
2654 bumpGeneration();
2655 if (changes) {
2656 getDevice()->notifyReset(when);
2657 }
2658 }
2659
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2661 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2662 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2663 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2664 }
2665
2666 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2667 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2668 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002669 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 mOrientation = v.orientation;
2671 } else {
2672 mOrientation = DISPLAY_ORIENTATION_0;
2673 }
2674 } else {
2675 mOrientation = DISPLAY_ORIENTATION_0;
2676 }
2677 bumpGeneration();
2678 }
2679}
2680
2681void CursorInputMapper::configureParameters() {
2682 mParameters.mode = Parameters::MODE_POINTER;
2683 String8 cursorModeString;
2684 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2685 if (cursorModeString == "navigation") {
2686 mParameters.mode = Parameters::MODE_NAVIGATION;
2687 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2688 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2689 }
2690 }
2691
2692 mParameters.orientationAware = false;
2693 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2694 mParameters.orientationAware);
2695
2696 mParameters.hasAssociatedDisplay = false;
2697 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2698 mParameters.hasAssociatedDisplay = true;
2699 }
2700}
2701
2702void CursorInputMapper::dumpParameters(String8& dump) {
2703 dump.append(INDENT3 "Parameters:\n");
2704 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2705 toString(mParameters.hasAssociatedDisplay));
2706
2707 switch (mParameters.mode) {
2708 case Parameters::MODE_POINTER:
2709 dump.append(INDENT4 "Mode: pointer\n");
2710 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002711 case Parameters::MODE_POINTER_RELATIVE:
2712 dump.append(INDENT4 "Mode: relative pointer\n");
2713 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 case Parameters::MODE_NAVIGATION:
2715 dump.append(INDENT4 "Mode: navigation\n");
2716 break;
2717 default:
2718 ALOG_ASSERT(false);
2719 }
2720
2721 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2722 toString(mParameters.orientationAware));
2723}
2724
2725void CursorInputMapper::reset(nsecs_t when) {
2726 mButtonState = 0;
2727 mDownTime = 0;
2728
2729 mPointerVelocityControl.reset();
2730 mWheelXVelocityControl.reset();
2731 mWheelYVelocityControl.reset();
2732
2733 mCursorButtonAccumulator.reset(getDevice());
2734 mCursorMotionAccumulator.reset(getDevice());
2735 mCursorScrollAccumulator.reset(getDevice());
2736
2737 InputMapper::reset(when);
2738}
2739
2740void CursorInputMapper::process(const RawEvent* rawEvent) {
2741 mCursorButtonAccumulator.process(rawEvent);
2742 mCursorMotionAccumulator.process(rawEvent);
2743 mCursorScrollAccumulator.process(rawEvent);
2744
2745 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2746 sync(rawEvent->when);
2747 }
2748}
2749
2750void CursorInputMapper::sync(nsecs_t when) {
2751 int32_t lastButtonState = mButtonState;
2752 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2753 mButtonState = currentButtonState;
2754
2755 bool wasDown = isPointerDown(lastButtonState);
2756 bool down = isPointerDown(currentButtonState);
2757 bool downChanged;
2758 if (!wasDown && down) {
2759 mDownTime = when;
2760 downChanged = true;
2761 } else if (wasDown && !down) {
2762 downChanged = true;
2763 } else {
2764 downChanged = false;
2765 }
2766 nsecs_t downTime = mDownTime;
2767 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002768 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2769 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770
2771 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2772 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2773 bool moved = deltaX != 0 || deltaY != 0;
2774
2775 // Rotate delta according to orientation if needed.
2776 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2777 && (deltaX != 0.0f || deltaY != 0.0f)) {
2778 rotateDelta(mOrientation, &deltaX, &deltaY);
2779 }
2780
2781 // Move the pointer.
2782 PointerProperties pointerProperties;
2783 pointerProperties.clear();
2784 pointerProperties.id = 0;
2785 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2786
2787 PointerCoords pointerCoords;
2788 pointerCoords.clear();
2789
2790 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2791 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2792 bool scrolled = vscroll != 0 || hscroll != 0;
2793
2794 mWheelYVelocityControl.move(when, NULL, &vscroll);
2795 mWheelXVelocityControl.move(when, &hscroll, NULL);
2796
2797 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2798
2799 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002800 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002801 if (moved || scrolled || buttonsChanged) {
2802 mPointerController->setPresentation(
2803 PointerControllerInterface::PRESENTATION_POINTER);
2804
2805 if (moved) {
2806 mPointerController->move(deltaX, deltaY);
2807 }
2808
2809 if (buttonsChanged) {
2810 mPointerController->setButtonState(currentButtonState);
2811 }
2812
2813 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2814 }
2815
2816 float x, y;
2817 mPointerController->getPosition(&x, &y);
2818 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2819 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002820 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2821 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 displayId = ADISPLAY_ID_DEFAULT;
2823 } else {
2824 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2825 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2826 displayId = ADISPLAY_ID_NONE;
2827 }
2828
2829 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2830
2831 // Moving an external trackball or mouse should wake the device.
2832 // We don't do this for internal cursor devices to prevent them from waking up
2833 // the device in your pocket.
2834 // TODO: Use the input device configuration to control this behavior more finely.
2835 uint32_t policyFlags = 0;
2836 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002837 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 }
2839
2840 // Synthesize key down from buttons if needed.
2841 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2842 policyFlags, lastButtonState, currentButtonState);
2843
2844 // Send motion event.
2845 if (downChanged || moved || scrolled || buttonsChanged) {
2846 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002847 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002848 int32_t motionEventAction;
2849 if (downChanged) {
2850 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002851 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2853 } else {
2854 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2855 }
2856
Michael Wright7b159c92015-05-14 14:48:03 +01002857 if (buttonsReleased) {
2858 BitSet32 released(buttonsReleased);
2859 while (!released.isEmpty()) {
2860 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2861 buttonState &= ~actionButton;
2862 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2863 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2864 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2865 displayId, 1, &pointerProperties, &pointerCoords,
2866 mXPrecision, mYPrecision, downTime);
2867 getListener()->notifyMotion(&releaseArgs);
2868 }
2869 }
2870
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002872 motionEventAction, 0, 0, metaState, currentButtonState,
2873 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002874 displayId, 1, &pointerProperties, &pointerCoords,
2875 mXPrecision, mYPrecision, downTime);
2876 getListener()->notifyMotion(&args);
2877
Michael Wright7b159c92015-05-14 14:48:03 +01002878 if (buttonsPressed) {
2879 BitSet32 pressed(buttonsPressed);
2880 while (!pressed.isEmpty()) {
2881 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2882 buttonState |= actionButton;
2883 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2884 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2885 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2886 displayId, 1, &pointerProperties, &pointerCoords,
2887 mXPrecision, mYPrecision, downTime);
2888 getListener()->notifyMotion(&pressArgs);
2889 }
2890 }
2891
2892 ALOG_ASSERT(buttonState == currentButtonState);
2893
Michael Wrightd02c5b62014-02-10 15:10:22 -08002894 // Send hover move after UP to tell the application that the mouse is hovering now.
2895 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002896 && (mSource == AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002898 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2900 displayId, 1, &pointerProperties, &pointerCoords,
2901 mXPrecision, mYPrecision, downTime);
2902 getListener()->notifyMotion(&hoverArgs);
2903 }
2904
2905 // Send scroll events.
2906 if (scrolled) {
2907 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2908 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2909
2910 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002911 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912 AMOTION_EVENT_EDGE_FLAG_NONE,
2913 displayId, 1, &pointerProperties, &pointerCoords,
2914 mXPrecision, mYPrecision, downTime);
2915 getListener()->notifyMotion(&scrollArgs);
2916 }
2917 }
2918
2919 // Synthesize key up from buttons if needed.
2920 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2921 policyFlags, lastButtonState, currentButtonState);
2922
2923 mCursorMotionAccumulator.finishSync();
2924 mCursorScrollAccumulator.finishSync();
2925}
2926
2927int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2928 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2929 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2930 } else {
2931 return AKEY_STATE_UNKNOWN;
2932 }
2933}
2934
2935void CursorInputMapper::fadePointer() {
2936 if (mPointerController != NULL) {
2937 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2938 }
2939}
2940
Prashant Malani1941ff52015-08-11 18:29:28 -07002941// --- RotaryEncoderInputMapper ---
2942
2943RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
2944 InputMapper(device) {
2945 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2946}
2947
2948RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2949}
2950
2951uint32_t RotaryEncoderInputMapper::getSources() {
2952 return mSource;
2953}
2954
2955void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2956 InputMapper::populateDeviceInfo(info);
2957
2958 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002959 float res = 0.0f;
2960 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2961 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2962 }
2963 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2964 mScalingFactor)) {
2965 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2966 "default to 1.0!\n");
2967 mScalingFactor = 1.0f;
2968 }
2969 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2970 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002971 }
2972}
2973
2974void RotaryEncoderInputMapper::dump(String8& dump) {
2975 dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
2976 dump.appendFormat(INDENT3 "HaveWheel: %s\n",
2977 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2978}
2979
2980void RotaryEncoderInputMapper::configure(nsecs_t when,
2981 const InputReaderConfiguration* config, uint32_t changes) {
2982 InputMapper::configure(when, config, changes);
2983 if (!changes) {
2984 mRotaryEncoderScrollAccumulator.configure(getDevice());
2985 }
2986}
2987
2988void RotaryEncoderInputMapper::reset(nsecs_t when) {
2989 mRotaryEncoderScrollAccumulator.reset(getDevice());
2990
2991 InputMapper::reset(when);
2992}
2993
2994void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2995 mRotaryEncoderScrollAccumulator.process(rawEvent);
2996
2997 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2998 sync(rawEvent->when);
2999 }
3000}
3001
3002void RotaryEncoderInputMapper::sync(nsecs_t when) {
3003 PointerCoords pointerCoords;
3004 pointerCoords.clear();
3005
3006 PointerProperties pointerProperties;
3007 pointerProperties.clear();
3008 pointerProperties.id = 0;
3009 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3010
3011 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3012 bool scrolled = scroll != 0;
3013
3014 // This is not a pointer, so it's not associated with a display.
3015 int32_t displayId = ADISPLAY_ID_NONE;
3016
3017 // Moving the rotary encoder should wake the device (if specified).
3018 uint32_t policyFlags = 0;
3019 if (scrolled && getDevice()->isExternal()) {
3020 policyFlags |= POLICY_FLAG_WAKE;
3021 }
3022
3023 // Send motion event.
3024 if (scrolled) {
3025 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003026 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003027
3028 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
3029 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3030 AMOTION_EVENT_EDGE_FLAG_NONE,
3031 displayId, 1, &pointerProperties, &pointerCoords,
3032 0, 0, 0);
3033 getListener()->notifyMotion(&scrollArgs);
3034 }
3035
3036 mRotaryEncoderScrollAccumulator.finishSync();
3037}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003038
3039// --- TouchInputMapper ---
3040
3041TouchInputMapper::TouchInputMapper(InputDevice* device) :
3042 InputMapper(device),
3043 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3044 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
3045 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3046}
3047
3048TouchInputMapper::~TouchInputMapper() {
3049}
3050
3051uint32_t TouchInputMapper::getSources() {
3052 return mSource;
3053}
3054
3055void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3056 InputMapper::populateDeviceInfo(info);
3057
3058 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3059 info->addMotionRange(mOrientedRanges.x);
3060 info->addMotionRange(mOrientedRanges.y);
3061 info->addMotionRange(mOrientedRanges.pressure);
3062
3063 if (mOrientedRanges.haveSize) {
3064 info->addMotionRange(mOrientedRanges.size);
3065 }
3066
3067 if (mOrientedRanges.haveTouchSize) {
3068 info->addMotionRange(mOrientedRanges.touchMajor);
3069 info->addMotionRange(mOrientedRanges.touchMinor);
3070 }
3071
3072 if (mOrientedRanges.haveToolSize) {
3073 info->addMotionRange(mOrientedRanges.toolMajor);
3074 info->addMotionRange(mOrientedRanges.toolMinor);
3075 }
3076
3077 if (mOrientedRanges.haveOrientation) {
3078 info->addMotionRange(mOrientedRanges.orientation);
3079 }
3080
3081 if (mOrientedRanges.haveDistance) {
3082 info->addMotionRange(mOrientedRanges.distance);
3083 }
3084
3085 if (mOrientedRanges.haveTilt) {
3086 info->addMotionRange(mOrientedRanges.tilt);
3087 }
3088
3089 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3090 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3091 0.0f);
3092 }
3093 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3094 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3095 0.0f);
3096 }
3097 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3098 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3099 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3100 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3101 x.fuzz, x.resolution);
3102 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3103 y.fuzz, y.resolution);
3104 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3105 x.fuzz, x.resolution);
3106 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3107 y.fuzz, y.resolution);
3108 }
3109 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3110 }
3111}
3112
3113void TouchInputMapper::dump(String8& dump) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003114 dump.appendFormat(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003115 dumpParameters(dump);
3116 dumpVirtualKeys(dump);
3117 dumpRawPointerAxes(dump);
3118 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003119 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003120 dumpSurface(dump);
3121
3122 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
3123 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3124 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3125 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
3126 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
3127 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3128 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3129 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3130 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3131 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3132 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3133 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3134 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3135 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3136 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3137 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3138 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
3139
Michael Wright7b159c92015-05-14 14:48:03 +01003140 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003141 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003142 mLastRawState.rawPointerData.pointerCount);
3143 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3144 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
3146 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3147 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3148 "toolType=%d, isHovering=%s\n", i,
3149 pointer.id, pointer.x, pointer.y, pointer.pressure,
3150 pointer.touchMajor, pointer.touchMinor,
3151 pointer.toolMajor, pointer.toolMinor,
3152 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3153 pointer.toolType, toString(pointer.isHovering));
3154 }
3155
Michael Wright7b159c92015-05-14 14:48:03 +01003156 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003158 mLastCookedState.cookedPointerData.pointerCount);
3159 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3160 const PointerProperties& pointerProperties =
3161 mLastCookedState.cookedPointerData.pointerProperties[i];
3162 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
3164 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3165 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3166 "toolType=%d, isHovering=%s\n", i,
3167 pointerProperties.id,
3168 pointerCoords.getX(),
3169 pointerCoords.getY(),
3170 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3171 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3172 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3173 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3174 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3175 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3176 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3177 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3178 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003179 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 }
3181
Michael Wright842500e2015-03-13 17:32:02 -07003182 dump.append(INDENT3 "Stylus Fusion:\n");
3183 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
3184 toString(mExternalStylusConnected));
3185 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3186 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003187 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07003188 dump.append(INDENT3 "External Stylus State:\n");
3189 dumpStylusState(dump, mExternalStylusState);
3190
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 if (mDeviceMode == DEVICE_MODE_POINTER) {
3192 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
3193 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
3194 mPointerXMovementScale);
3195 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
3196 mPointerYMovementScale);
3197 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
3198 mPointerXZoomScale);
3199 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
3200 mPointerYZoomScale);
3201 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
3202 mPointerGestureMaxSwipeWidth);
3203 }
3204}
3205
Santos Cordonfa5cf462017-04-05 10:37:00 -07003206const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3207 switch (deviceMode) {
3208 case DEVICE_MODE_DISABLED:
3209 return "disabled";
3210 case DEVICE_MODE_DIRECT:
3211 return "direct";
3212 case DEVICE_MODE_UNSCALED:
3213 return "unscaled";
3214 case DEVICE_MODE_NAVIGATION:
3215 return "navigation";
3216 case DEVICE_MODE_POINTER:
3217 return "pointer";
3218 }
3219 return "unknown";
3220}
3221
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222void TouchInputMapper::configure(nsecs_t when,
3223 const InputReaderConfiguration* config, uint32_t changes) {
3224 InputMapper::configure(when, config, changes);
3225
3226 mConfig = *config;
3227
3228 if (!changes) { // first time only
3229 // Configure basic parameters.
3230 configureParameters();
3231
3232 // Configure common accumulators.
3233 mCursorScrollAccumulator.configure(getDevice());
3234 mTouchButtonAccumulator.configure(getDevice());
3235
3236 // Configure absolute axis information.
3237 configureRawPointerAxes();
3238
3239 // Prepare input device calibration.
3240 parseCalibration();
3241 resolveCalibration();
3242 }
3243
Michael Wright842500e2015-03-13 17:32:02 -07003244 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003245 // Update location calibration to reflect current settings
3246 updateAffineTransformation();
3247 }
3248
Michael Wrightd02c5b62014-02-10 15:10:22 -08003249 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3250 // Update pointer speed.
3251 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3252 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3253 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3254 }
3255
3256 bool resetNeeded = false;
3257 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3258 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003259 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3260 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 // Configure device sources, surface dimensions, orientation and
3262 // scaling factors.
3263 configureSurface(when, &resetNeeded);
3264 }
3265
3266 if (changes && resetNeeded) {
3267 // Send reset, unless this is the first time the device has been configured,
3268 // in which case the reader will call reset itself after all mappers are ready.
3269 getDevice()->notifyReset(when);
3270 }
3271}
3272
Michael Wright842500e2015-03-13 17:32:02 -07003273void TouchInputMapper::resolveExternalStylusPresence() {
3274 Vector<InputDeviceInfo> devices;
3275 mContext->getExternalStylusDevices(devices);
3276 mExternalStylusConnected = !devices.isEmpty();
3277
3278 if (!mExternalStylusConnected) {
3279 resetExternalStylus();
3280 }
3281}
3282
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283void TouchInputMapper::configureParameters() {
3284 // Use the pointer presentation mode for devices that do not support distinct
3285 // multitouch. The spot-based presentation relies on being able to accurately
3286 // locate two or more fingers on the touch pad.
3287 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003288 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289
3290 String8 gestureModeString;
3291 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3292 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003293 if (gestureModeString == "single-touch") {
3294 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3295 } else if (gestureModeString == "multi-touch") {
3296 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 } else if (gestureModeString != "default") {
3298 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3299 }
3300 }
3301
3302 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3303 // The device is a touch screen.
3304 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3305 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3306 // The device is a pointing device like a track pad.
3307 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3308 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3309 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3310 // The device is a cursor device with a touch pad attached.
3311 // By default don't use the touch pad to move the pointer.
3312 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3313 } else {
3314 // The device is a touch pad of unknown purpose.
3315 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3316 }
3317
3318 mParameters.hasButtonUnderPad=
3319 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3320
3321 String8 deviceTypeString;
3322 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3323 deviceTypeString)) {
3324 if (deviceTypeString == "touchScreen") {
3325 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3326 } else if (deviceTypeString == "touchPad") {
3327 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3328 } else if (deviceTypeString == "touchNavigation") {
3329 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3330 } else if (deviceTypeString == "pointer") {
3331 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3332 } else if (deviceTypeString != "default") {
3333 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3334 }
3335 }
3336
3337 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3338 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3339 mParameters.orientationAware);
3340
3341 mParameters.hasAssociatedDisplay = false;
3342 mParameters.associatedDisplayIsExternal = false;
3343 if (mParameters.orientationAware
3344 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3345 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3346 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003347 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3348 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3349 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3350 mParameters.uniqueDisplayId);
3351 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003353
3354 // Initial downs on external touch devices should wake the device.
3355 // Normally we don't do this for internal touch screens to prevent them from waking
3356 // up in your pocket but you can enable it using the input device configuration.
3357 mParameters.wake = getDevice()->isExternal();
3358 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3359 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360}
3361
3362void TouchInputMapper::dumpParameters(String8& dump) {
3363 dump.append(INDENT3 "Parameters:\n");
3364
3365 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003366 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3367 dump.append(INDENT4 "GestureMode: single-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003369 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3370 dump.append(INDENT4 "GestureMode: multi-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 break;
3372 default:
3373 assert(false);
3374 }
3375
3376 switch (mParameters.deviceType) {
3377 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3378 dump.append(INDENT4 "DeviceType: touchScreen\n");
3379 break;
3380 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3381 dump.append(INDENT4 "DeviceType: touchPad\n");
3382 break;
3383 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3384 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3385 break;
3386 case Parameters::DEVICE_TYPE_POINTER:
3387 dump.append(INDENT4 "DeviceType: pointer\n");
3388 break;
3389 default:
3390 ALOG_ASSERT(false);
3391 }
3392
Santos Cordonfa5cf462017-04-05 10:37:00 -07003393 dump.appendFormat(
3394 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003395 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003396 toString(mParameters.associatedDisplayIsExternal),
3397 mParameters.uniqueDisplayId.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3399 toString(mParameters.orientationAware));
3400}
3401
3402void TouchInputMapper::configureRawPointerAxes() {
3403 mRawPointerAxes.clear();
3404}
3405
3406void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3407 dump.append(INDENT3 "Raw Touch Axes:\n");
3408 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3409 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3410 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3411 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3412 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3413 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3414 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3415 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3416 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3417 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3418 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3419 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3420 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3421}
3422
Michael Wright842500e2015-03-13 17:32:02 -07003423bool TouchInputMapper::hasExternalStylus() const {
3424 return mExternalStylusConnected;
3425}
3426
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3428 int32_t oldDeviceMode = mDeviceMode;
3429
Michael Wright842500e2015-03-13 17:32:02 -07003430 resolveExternalStylusPresence();
3431
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 // Determine device mode.
3433 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3434 && mConfig.pointerGesturesEnabled) {
3435 mSource = AINPUT_SOURCE_MOUSE;
3436 mDeviceMode = DEVICE_MODE_POINTER;
3437 if (hasStylus()) {
3438 mSource |= AINPUT_SOURCE_STYLUS;
3439 }
3440 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3441 && mParameters.hasAssociatedDisplay) {
3442 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3443 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003444 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 mSource |= AINPUT_SOURCE_STYLUS;
3446 }
Michael Wright2f78b682015-06-12 15:25:08 +01003447 if (hasExternalStylus()) {
3448 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3449 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3451 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3452 mDeviceMode = DEVICE_MODE_NAVIGATION;
3453 } else {
3454 mSource = AINPUT_SOURCE_TOUCHPAD;
3455 mDeviceMode = DEVICE_MODE_UNSCALED;
3456 }
3457
3458 // Ensure we have valid X and Y axes.
3459 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3460 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3461 "The device will be inoperable.", getDeviceName().string());
3462 mDeviceMode = DEVICE_MODE_DISABLED;
3463 return;
3464 }
3465
3466 // Raw width and height in the natural orientation.
3467 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3468 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3469
3470 // Get associated display dimensions.
3471 DisplayViewport newViewport;
3472 if (mParameters.hasAssociatedDisplay) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003473 const String8* uniqueDisplayId = NULL;
3474 ViewportType viewportTypeToUse;
3475
3476 if (mParameters.associatedDisplayIsExternal) {
3477 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3478 } else if (!mParameters.uniqueDisplayId.isEmpty()) {
3479 // If the IDC file specified a unique display Id, then it expects to be linked to a
3480 // virtual display with the same unique ID.
3481 uniqueDisplayId = &mParameters.uniqueDisplayId;
3482 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3483 } else {
3484 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3485 }
3486
3487 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3489 "display. The device will be inoperable until the display size "
3490 "becomes available.",
3491 getDeviceName().string());
3492 mDeviceMode = DEVICE_MODE_DISABLED;
3493 return;
3494 }
3495 } else {
3496 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3497 }
3498 bool viewportChanged = mViewport != newViewport;
3499 if (viewportChanged) {
3500 mViewport = newViewport;
3501
3502 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3503 // Convert rotated viewport to natural surface coordinates.
3504 int32_t naturalLogicalWidth, naturalLogicalHeight;
3505 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3506 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3507 int32_t naturalDeviceWidth, naturalDeviceHeight;
3508 switch (mViewport.orientation) {
3509 case DISPLAY_ORIENTATION_90:
3510 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3511 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3512 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3513 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3514 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3515 naturalPhysicalTop = mViewport.physicalLeft;
3516 naturalDeviceWidth = mViewport.deviceHeight;
3517 naturalDeviceHeight = mViewport.deviceWidth;
3518 break;
3519 case DISPLAY_ORIENTATION_180:
3520 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3521 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3522 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3523 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3524 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3525 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3526 naturalDeviceWidth = mViewport.deviceWidth;
3527 naturalDeviceHeight = mViewport.deviceHeight;
3528 break;
3529 case DISPLAY_ORIENTATION_270:
3530 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3531 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3532 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3533 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3534 naturalPhysicalLeft = mViewport.physicalTop;
3535 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3536 naturalDeviceWidth = mViewport.deviceHeight;
3537 naturalDeviceHeight = mViewport.deviceWidth;
3538 break;
3539 case DISPLAY_ORIENTATION_0:
3540 default:
3541 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3542 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3543 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3544 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3545 naturalPhysicalLeft = mViewport.physicalLeft;
3546 naturalPhysicalTop = mViewport.physicalTop;
3547 naturalDeviceWidth = mViewport.deviceWidth;
3548 naturalDeviceHeight = mViewport.deviceHeight;
3549 break;
3550 }
3551
3552 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3553 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3554 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3555 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3556
3557 mSurfaceOrientation = mParameters.orientationAware ?
3558 mViewport.orientation : DISPLAY_ORIENTATION_0;
3559 } else {
3560 mSurfaceWidth = rawWidth;
3561 mSurfaceHeight = rawHeight;
3562 mSurfaceLeft = 0;
3563 mSurfaceTop = 0;
3564 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3565 }
3566 }
3567
3568 // If moving between pointer modes, need to reset some state.
3569 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3570 if (deviceModeChanged) {
3571 mOrientedRanges.clear();
3572 }
3573
3574 // Create pointer controller if needed.
3575 if (mDeviceMode == DEVICE_MODE_POINTER ||
3576 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3577 if (mPointerController == NULL) {
3578 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3579 }
3580 } else {
3581 mPointerController.clear();
3582 }
3583
3584 if (viewportChanged || deviceModeChanged) {
3585 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3586 "display id %d",
3587 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3588 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3589
3590 // Configure X and Y factors.
3591 mXScale = float(mSurfaceWidth) / rawWidth;
3592 mYScale = float(mSurfaceHeight) / rawHeight;
3593 mXTranslate = -mSurfaceLeft;
3594 mYTranslate = -mSurfaceTop;
3595 mXPrecision = 1.0f / mXScale;
3596 mYPrecision = 1.0f / mYScale;
3597
3598 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3599 mOrientedRanges.x.source = mSource;
3600 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3601 mOrientedRanges.y.source = mSource;
3602
3603 configureVirtualKeys();
3604
3605 // Scale factor for terms that are not oriented in a particular axis.
3606 // If the pixels are square then xScale == yScale otherwise we fake it
3607 // by choosing an average.
3608 mGeometricScale = avg(mXScale, mYScale);
3609
3610 // Size of diagonal axis.
3611 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3612
3613 // Size factors.
3614 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3615 if (mRawPointerAxes.touchMajor.valid
3616 && mRawPointerAxes.touchMajor.maxValue != 0) {
3617 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3618 } else if (mRawPointerAxes.toolMajor.valid
3619 && mRawPointerAxes.toolMajor.maxValue != 0) {
3620 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3621 } else {
3622 mSizeScale = 0.0f;
3623 }
3624
3625 mOrientedRanges.haveTouchSize = true;
3626 mOrientedRanges.haveToolSize = true;
3627 mOrientedRanges.haveSize = true;
3628
3629 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3630 mOrientedRanges.touchMajor.source = mSource;
3631 mOrientedRanges.touchMajor.min = 0;
3632 mOrientedRanges.touchMajor.max = diagonalSize;
3633 mOrientedRanges.touchMajor.flat = 0;
3634 mOrientedRanges.touchMajor.fuzz = 0;
3635 mOrientedRanges.touchMajor.resolution = 0;
3636
3637 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3638 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3639
3640 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3641 mOrientedRanges.toolMajor.source = mSource;
3642 mOrientedRanges.toolMajor.min = 0;
3643 mOrientedRanges.toolMajor.max = diagonalSize;
3644 mOrientedRanges.toolMajor.flat = 0;
3645 mOrientedRanges.toolMajor.fuzz = 0;
3646 mOrientedRanges.toolMajor.resolution = 0;
3647
3648 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3649 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3650
3651 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3652 mOrientedRanges.size.source = mSource;
3653 mOrientedRanges.size.min = 0;
3654 mOrientedRanges.size.max = 1.0;
3655 mOrientedRanges.size.flat = 0;
3656 mOrientedRanges.size.fuzz = 0;
3657 mOrientedRanges.size.resolution = 0;
3658 } else {
3659 mSizeScale = 0.0f;
3660 }
3661
3662 // Pressure factors.
3663 mPressureScale = 0;
3664 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3665 || mCalibration.pressureCalibration
3666 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3667 if (mCalibration.havePressureScale) {
3668 mPressureScale = mCalibration.pressureScale;
3669 } else if (mRawPointerAxes.pressure.valid
3670 && mRawPointerAxes.pressure.maxValue != 0) {
3671 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3672 }
3673 }
3674
3675 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3676 mOrientedRanges.pressure.source = mSource;
3677 mOrientedRanges.pressure.min = 0;
3678 mOrientedRanges.pressure.max = 1.0;
3679 mOrientedRanges.pressure.flat = 0;
3680 mOrientedRanges.pressure.fuzz = 0;
3681 mOrientedRanges.pressure.resolution = 0;
3682
3683 // Tilt
3684 mTiltXCenter = 0;
3685 mTiltXScale = 0;
3686 mTiltYCenter = 0;
3687 mTiltYScale = 0;
3688 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3689 if (mHaveTilt) {
3690 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3691 mRawPointerAxes.tiltX.maxValue);
3692 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3693 mRawPointerAxes.tiltY.maxValue);
3694 mTiltXScale = M_PI / 180;
3695 mTiltYScale = M_PI / 180;
3696
3697 mOrientedRanges.haveTilt = true;
3698
3699 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3700 mOrientedRanges.tilt.source = mSource;
3701 mOrientedRanges.tilt.min = 0;
3702 mOrientedRanges.tilt.max = M_PI_2;
3703 mOrientedRanges.tilt.flat = 0;
3704 mOrientedRanges.tilt.fuzz = 0;
3705 mOrientedRanges.tilt.resolution = 0;
3706 }
3707
3708 // Orientation
3709 mOrientationScale = 0;
3710 if (mHaveTilt) {
3711 mOrientedRanges.haveOrientation = true;
3712
3713 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3714 mOrientedRanges.orientation.source = mSource;
3715 mOrientedRanges.orientation.min = -M_PI;
3716 mOrientedRanges.orientation.max = M_PI;
3717 mOrientedRanges.orientation.flat = 0;
3718 mOrientedRanges.orientation.fuzz = 0;
3719 mOrientedRanges.orientation.resolution = 0;
3720 } else if (mCalibration.orientationCalibration !=
3721 Calibration::ORIENTATION_CALIBRATION_NONE) {
3722 if (mCalibration.orientationCalibration
3723 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3724 if (mRawPointerAxes.orientation.valid) {
3725 if (mRawPointerAxes.orientation.maxValue > 0) {
3726 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3727 } else if (mRawPointerAxes.orientation.minValue < 0) {
3728 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3729 } else {
3730 mOrientationScale = 0;
3731 }
3732 }
3733 }
3734
3735 mOrientedRanges.haveOrientation = true;
3736
3737 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3738 mOrientedRanges.orientation.source = mSource;
3739 mOrientedRanges.orientation.min = -M_PI_2;
3740 mOrientedRanges.orientation.max = M_PI_2;
3741 mOrientedRanges.orientation.flat = 0;
3742 mOrientedRanges.orientation.fuzz = 0;
3743 mOrientedRanges.orientation.resolution = 0;
3744 }
3745
3746 // Distance
3747 mDistanceScale = 0;
3748 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3749 if (mCalibration.distanceCalibration
3750 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3751 if (mCalibration.haveDistanceScale) {
3752 mDistanceScale = mCalibration.distanceScale;
3753 } else {
3754 mDistanceScale = 1.0f;
3755 }
3756 }
3757
3758 mOrientedRanges.haveDistance = true;
3759
3760 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3761 mOrientedRanges.distance.source = mSource;
3762 mOrientedRanges.distance.min =
3763 mRawPointerAxes.distance.minValue * mDistanceScale;
3764 mOrientedRanges.distance.max =
3765 mRawPointerAxes.distance.maxValue * mDistanceScale;
3766 mOrientedRanges.distance.flat = 0;
3767 mOrientedRanges.distance.fuzz =
3768 mRawPointerAxes.distance.fuzz * mDistanceScale;
3769 mOrientedRanges.distance.resolution = 0;
3770 }
3771
3772 // Compute oriented precision, scales and ranges.
3773 // Note that the maximum value reported is an inclusive maximum value so it is one
3774 // unit less than the total width or height of surface.
3775 switch (mSurfaceOrientation) {
3776 case DISPLAY_ORIENTATION_90:
3777 case DISPLAY_ORIENTATION_270:
3778 mOrientedXPrecision = mYPrecision;
3779 mOrientedYPrecision = mXPrecision;
3780
3781 mOrientedRanges.x.min = mYTranslate;
3782 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3783 mOrientedRanges.x.flat = 0;
3784 mOrientedRanges.x.fuzz = 0;
3785 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3786
3787 mOrientedRanges.y.min = mXTranslate;
3788 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3789 mOrientedRanges.y.flat = 0;
3790 mOrientedRanges.y.fuzz = 0;
3791 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3792 break;
3793
3794 default:
3795 mOrientedXPrecision = mXPrecision;
3796 mOrientedYPrecision = mYPrecision;
3797
3798 mOrientedRanges.x.min = mXTranslate;
3799 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3800 mOrientedRanges.x.flat = 0;
3801 mOrientedRanges.x.fuzz = 0;
3802 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3803
3804 mOrientedRanges.y.min = mYTranslate;
3805 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3806 mOrientedRanges.y.flat = 0;
3807 mOrientedRanges.y.fuzz = 0;
3808 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3809 break;
3810 }
3811
Jason Gerecke71b16e82014-03-10 09:47:59 -07003812 // Location
3813 updateAffineTransformation();
3814
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 if (mDeviceMode == DEVICE_MODE_POINTER) {
3816 // Compute pointer gesture detection parameters.
3817 float rawDiagonal = hypotf(rawWidth, rawHeight);
3818 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3819
3820 // Scale movements such that one whole swipe of the touch pad covers a
3821 // given area relative to the diagonal size of the display when no acceleration
3822 // is applied.
3823 // Assume that the touch pad has a square aspect ratio such that movements in
3824 // X and Y of the same number of raw units cover the same physical distance.
3825 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3826 * displayDiagonal / rawDiagonal;
3827 mPointerYMovementScale = mPointerXMovementScale;
3828
3829 // Scale zooms to cover a smaller range of the display than movements do.
3830 // This value determines the area around the pointer that is affected by freeform
3831 // pointer gestures.
3832 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3833 * displayDiagonal / rawDiagonal;
3834 mPointerYZoomScale = mPointerXZoomScale;
3835
3836 // Max width between pointers to detect a swipe gesture is more than some fraction
3837 // of the diagonal axis of the touch pad. Touches that are wider than this are
3838 // translated into freeform gestures.
3839 mPointerGestureMaxSwipeWidth =
3840 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3841
3842 // Abort current pointer usages because the state has changed.
3843 abortPointerUsage(when, 0 /*policyFlags*/);
3844 }
3845
3846 // Inform the dispatcher about the changes.
3847 *outResetNeeded = true;
3848 bumpGeneration();
3849 }
3850}
3851
3852void TouchInputMapper::dumpSurface(String8& dump) {
3853 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3854 "logicalFrame=[%d, %d, %d, %d], "
3855 "physicalFrame=[%d, %d, %d, %d], "
3856 "deviceSize=[%d, %d]\n",
3857 mViewport.displayId, mViewport.orientation,
3858 mViewport.logicalLeft, mViewport.logicalTop,
3859 mViewport.logicalRight, mViewport.logicalBottom,
3860 mViewport.physicalLeft, mViewport.physicalTop,
3861 mViewport.physicalRight, mViewport.physicalBottom,
3862 mViewport.deviceWidth, mViewport.deviceHeight);
3863
3864 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3865 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3866 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3867 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3868 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3869}
3870
3871void TouchInputMapper::configureVirtualKeys() {
3872 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3873 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3874
3875 mVirtualKeys.clear();
3876
3877 if (virtualKeyDefinitions.size() == 0) {
3878 return;
3879 }
3880
3881 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3882
3883 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3884 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3885 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3886 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3887
3888 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3889 const VirtualKeyDefinition& virtualKeyDefinition =
3890 virtualKeyDefinitions[i];
3891
3892 mVirtualKeys.add();
3893 VirtualKey& virtualKey = mVirtualKeys.editTop();
3894
3895 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3896 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003897 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003899 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3900 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3902 virtualKey.scanCode);
3903 mVirtualKeys.pop(); // drop the key
3904 continue;
3905 }
3906
3907 virtualKey.keyCode = keyCode;
3908 virtualKey.flags = flags;
3909
3910 // convert the key definition's display coordinates into touch coordinates for a hit box
3911 int32_t halfWidth = virtualKeyDefinition.width / 2;
3912 int32_t halfHeight = virtualKeyDefinition.height / 2;
3913
3914 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3915 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3916 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3917 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3918 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3919 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3920 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3921 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3922 }
3923}
3924
3925void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3926 if (!mVirtualKeys.isEmpty()) {
3927 dump.append(INDENT3 "Virtual Keys:\n");
3928
3929 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3930 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003931 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3933 i, virtualKey.scanCode, virtualKey.keyCode,
3934 virtualKey.hitLeft, virtualKey.hitRight,
3935 virtualKey.hitTop, virtualKey.hitBottom);
3936 }
3937 }
3938}
3939
3940void TouchInputMapper::parseCalibration() {
3941 const PropertyMap& in = getDevice()->getConfiguration();
3942 Calibration& out = mCalibration;
3943
3944 // Size
3945 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3946 String8 sizeCalibrationString;
3947 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3948 if (sizeCalibrationString == "none") {
3949 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3950 } else if (sizeCalibrationString == "geometric") {
3951 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3952 } else if (sizeCalibrationString == "diameter") {
3953 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3954 } else if (sizeCalibrationString == "box") {
3955 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3956 } else if (sizeCalibrationString == "area") {
3957 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3958 } else if (sizeCalibrationString != "default") {
3959 ALOGW("Invalid value for touch.size.calibration: '%s'",
3960 sizeCalibrationString.string());
3961 }
3962 }
3963
3964 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3965 out.sizeScale);
3966 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3967 out.sizeBias);
3968 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3969 out.sizeIsSummed);
3970
3971 // Pressure
3972 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3973 String8 pressureCalibrationString;
3974 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3975 if (pressureCalibrationString == "none") {
3976 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3977 } else if (pressureCalibrationString == "physical") {
3978 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3979 } else if (pressureCalibrationString == "amplitude") {
3980 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3981 } else if (pressureCalibrationString != "default") {
3982 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3983 pressureCalibrationString.string());
3984 }
3985 }
3986
3987 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3988 out.pressureScale);
3989
3990 // Orientation
3991 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3992 String8 orientationCalibrationString;
3993 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3994 if (orientationCalibrationString == "none") {
3995 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3996 } else if (orientationCalibrationString == "interpolated") {
3997 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3998 } else if (orientationCalibrationString == "vector") {
3999 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4000 } else if (orientationCalibrationString != "default") {
4001 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4002 orientationCalibrationString.string());
4003 }
4004 }
4005
4006 // Distance
4007 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4008 String8 distanceCalibrationString;
4009 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4010 if (distanceCalibrationString == "none") {
4011 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4012 } else if (distanceCalibrationString == "scaled") {
4013 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4014 } else if (distanceCalibrationString != "default") {
4015 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4016 distanceCalibrationString.string());
4017 }
4018 }
4019
4020 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4021 out.distanceScale);
4022
4023 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4024 String8 coverageCalibrationString;
4025 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4026 if (coverageCalibrationString == "none") {
4027 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4028 } else if (coverageCalibrationString == "box") {
4029 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4030 } else if (coverageCalibrationString != "default") {
4031 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4032 coverageCalibrationString.string());
4033 }
4034 }
4035}
4036
4037void TouchInputMapper::resolveCalibration() {
4038 // Size
4039 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4040 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4041 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4042 }
4043 } else {
4044 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4045 }
4046
4047 // Pressure
4048 if (mRawPointerAxes.pressure.valid) {
4049 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4050 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4051 }
4052 } else {
4053 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4054 }
4055
4056 // Orientation
4057 if (mRawPointerAxes.orientation.valid) {
4058 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4059 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4060 }
4061 } else {
4062 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4063 }
4064
4065 // Distance
4066 if (mRawPointerAxes.distance.valid) {
4067 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4068 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4069 }
4070 } else {
4071 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4072 }
4073
4074 // Coverage
4075 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4076 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4077 }
4078}
4079
4080void TouchInputMapper::dumpCalibration(String8& dump) {
4081 dump.append(INDENT3 "Calibration:\n");
4082
4083 // Size
4084 switch (mCalibration.sizeCalibration) {
4085 case Calibration::SIZE_CALIBRATION_NONE:
4086 dump.append(INDENT4 "touch.size.calibration: none\n");
4087 break;
4088 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4089 dump.append(INDENT4 "touch.size.calibration: geometric\n");
4090 break;
4091 case Calibration::SIZE_CALIBRATION_DIAMETER:
4092 dump.append(INDENT4 "touch.size.calibration: diameter\n");
4093 break;
4094 case Calibration::SIZE_CALIBRATION_BOX:
4095 dump.append(INDENT4 "touch.size.calibration: box\n");
4096 break;
4097 case Calibration::SIZE_CALIBRATION_AREA:
4098 dump.append(INDENT4 "touch.size.calibration: area\n");
4099 break;
4100 default:
4101 ALOG_ASSERT(false);
4102 }
4103
4104 if (mCalibration.haveSizeScale) {
4105 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
4106 mCalibration.sizeScale);
4107 }
4108
4109 if (mCalibration.haveSizeBias) {
4110 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
4111 mCalibration.sizeBias);
4112 }
4113
4114 if (mCalibration.haveSizeIsSummed) {
4115 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
4116 toString(mCalibration.sizeIsSummed));
4117 }
4118
4119 // Pressure
4120 switch (mCalibration.pressureCalibration) {
4121 case Calibration::PRESSURE_CALIBRATION_NONE:
4122 dump.append(INDENT4 "touch.pressure.calibration: none\n");
4123 break;
4124 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4125 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
4126 break;
4127 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4128 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
4129 break;
4130 default:
4131 ALOG_ASSERT(false);
4132 }
4133
4134 if (mCalibration.havePressureScale) {
4135 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
4136 mCalibration.pressureScale);
4137 }
4138
4139 // Orientation
4140 switch (mCalibration.orientationCalibration) {
4141 case Calibration::ORIENTATION_CALIBRATION_NONE:
4142 dump.append(INDENT4 "touch.orientation.calibration: none\n");
4143 break;
4144 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4145 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
4146 break;
4147 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
4148 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
4149 break;
4150 default:
4151 ALOG_ASSERT(false);
4152 }
4153
4154 // Distance
4155 switch (mCalibration.distanceCalibration) {
4156 case Calibration::DISTANCE_CALIBRATION_NONE:
4157 dump.append(INDENT4 "touch.distance.calibration: none\n");
4158 break;
4159 case Calibration::DISTANCE_CALIBRATION_SCALED:
4160 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
4161 break;
4162 default:
4163 ALOG_ASSERT(false);
4164 }
4165
4166 if (mCalibration.haveDistanceScale) {
4167 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
4168 mCalibration.distanceScale);
4169 }
4170
4171 switch (mCalibration.coverageCalibration) {
4172 case Calibration::COVERAGE_CALIBRATION_NONE:
4173 dump.append(INDENT4 "touch.coverage.calibration: none\n");
4174 break;
4175 case Calibration::COVERAGE_CALIBRATION_BOX:
4176 dump.append(INDENT4 "touch.coverage.calibration: box\n");
4177 break;
4178 default:
4179 ALOG_ASSERT(false);
4180 }
4181}
4182
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004183void TouchInputMapper::dumpAffineTransformation(String8& dump) {
4184 dump.append(INDENT3 "Affine Transformation:\n");
4185
4186 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4187 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4188 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4189 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4190 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4191 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
4192}
4193
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004194void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004195 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4196 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004197}
4198
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199void TouchInputMapper::reset(nsecs_t when) {
4200 mCursorButtonAccumulator.reset(getDevice());
4201 mCursorScrollAccumulator.reset(getDevice());
4202 mTouchButtonAccumulator.reset(getDevice());
4203
4204 mPointerVelocityControl.reset();
4205 mWheelXVelocityControl.reset();
4206 mWheelYVelocityControl.reset();
4207
Michael Wright842500e2015-03-13 17:32:02 -07004208 mRawStatesPending.clear();
4209 mCurrentRawState.clear();
4210 mCurrentCookedState.clear();
4211 mLastRawState.clear();
4212 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 mPointerUsage = POINTER_USAGE_NONE;
4214 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004215 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004216 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 mDownTime = 0;
4218
4219 mCurrentVirtualKey.down = false;
4220
4221 mPointerGesture.reset();
4222 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004223 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224
4225 if (mPointerController != NULL) {
4226 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4227 mPointerController->clearSpots();
4228 }
4229
4230 InputMapper::reset(when);
4231}
4232
Michael Wright842500e2015-03-13 17:32:02 -07004233void TouchInputMapper::resetExternalStylus() {
4234 mExternalStylusState.clear();
4235 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004236 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004237 mExternalStylusDataPending = false;
4238}
4239
Michael Wright43fd19f2015-04-21 19:02:58 +01004240void TouchInputMapper::clearStylusDataPendingFlags() {
4241 mExternalStylusDataPending = false;
4242 mExternalStylusFusionTimeout = LLONG_MAX;
4243}
4244
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245void TouchInputMapper::process(const RawEvent* rawEvent) {
4246 mCursorButtonAccumulator.process(rawEvent);
4247 mCursorScrollAccumulator.process(rawEvent);
4248 mTouchButtonAccumulator.process(rawEvent);
4249
4250 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4251 sync(rawEvent->when);
4252 }
4253}
4254
4255void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004256 const RawState* last = mRawStatesPending.isEmpty() ?
4257 &mCurrentRawState : &mRawStatesPending.top();
4258
4259 // Push a new state.
4260 mRawStatesPending.push();
4261 RawState* next = &mRawStatesPending.editTop();
4262 next->clear();
4263 next->when = when;
4264
Michael Wrightd02c5b62014-02-10 15:10:22 -08004265 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004266 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 | mCursorButtonAccumulator.getButtonState();
4268
Michael Wright842500e2015-03-13 17:32:02 -07004269 // Sync scroll
4270 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4271 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 mCursorScrollAccumulator.finishSync();
4273
Michael Wright842500e2015-03-13 17:32:02 -07004274 // Sync touch
4275 syncTouch(when, next);
4276
4277 // Assign pointer ids.
4278 if (!mHavePointerIds) {
4279 assignPointerIds(last, next);
4280 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281
4282#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004283 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4284 "hovering ids 0x%08x -> 0x%08x",
4285 last->rawPointerData.pointerCount,
4286 next->rawPointerData.pointerCount,
4287 last->rawPointerData.touchingIdBits.value,
4288 next->rawPointerData.touchingIdBits.value,
4289 last->rawPointerData.hoveringIdBits.value,
4290 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291#endif
4292
Michael Wright842500e2015-03-13 17:32:02 -07004293 processRawTouches(false /*timeout*/);
4294}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295
Michael Wright842500e2015-03-13 17:32:02 -07004296void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4298 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004299 mCurrentRawState.clear();
4300 mRawStatesPending.clear();
4301 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 }
4303
Michael Wright842500e2015-03-13 17:32:02 -07004304 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4305 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4306 // touching the current state will only observe the events that have been dispatched to the
4307 // rest of the pipeline.
4308 const size_t N = mRawStatesPending.size();
4309 size_t count;
4310 for(count = 0; count < N; count++) {
4311 const RawState& next = mRawStatesPending[count];
4312
4313 // A failure to assign the stylus id means that we're waiting on stylus data
4314 // and so should defer the rest of the pipeline.
4315 if (assignExternalStylusId(next, timeout)) {
4316 break;
4317 }
4318
4319 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004320 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004321 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004322 if (mCurrentRawState.when < mLastRawState.when) {
4323 mCurrentRawState.when = mLastRawState.when;
4324 }
Michael Wright842500e2015-03-13 17:32:02 -07004325 cookAndDispatch(mCurrentRawState.when);
4326 }
4327 if (count != 0) {
4328 mRawStatesPending.removeItemsAt(0, count);
4329 }
4330
Michael Wright842500e2015-03-13 17:32:02 -07004331 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004332 if (timeout) {
4333 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4334 clearStylusDataPendingFlags();
4335 mCurrentRawState.copyFrom(mLastRawState);
4336#if DEBUG_STYLUS_FUSION
4337 ALOGD("Timeout expired, synthesizing event with new stylus data");
4338#endif
4339 cookAndDispatch(when);
4340 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4341 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4342 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4343 }
Michael Wright842500e2015-03-13 17:32:02 -07004344 }
4345}
4346
4347void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4348 // Always start with a clean state.
4349 mCurrentCookedState.clear();
4350
4351 // Apply stylus buttons to current raw state.
4352 applyExternalStylusButtonState(when);
4353
4354 // Handle policy on initial down or hover events.
4355 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4356 && mCurrentRawState.rawPointerData.pointerCount != 0;
4357
4358 uint32_t policyFlags = 0;
4359 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4360 if (initialDown || buttonsPressed) {
4361 // If this is a touch screen, hide the pointer on an initial down.
4362 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4363 getContext()->fadePointer();
4364 }
4365
4366 if (mParameters.wake) {
4367 policyFlags |= POLICY_FLAG_WAKE;
4368 }
4369 }
4370
4371 // Consume raw off-screen touches before cooking pointer data.
4372 // If touches are consumed, subsequent code will not receive any pointer data.
4373 if (consumeRawTouches(when, policyFlags)) {
4374 mCurrentRawState.rawPointerData.clear();
4375 }
4376
4377 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4378 // with cooked pointer data that has the same ids and indices as the raw data.
4379 // The following code can use either the raw or cooked data, as needed.
4380 cookPointerData();
4381
4382 // Apply stylus pressure to current cooked state.
4383 applyExternalStylusTouchState(when);
4384
4385 // Synthesize key down from raw buttons if needed.
4386 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004387 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004388
4389 // Dispatch the touches either directly or by translation through a pointer on screen.
4390 if (mDeviceMode == DEVICE_MODE_POINTER) {
4391 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4392 !idBits.isEmpty(); ) {
4393 uint32_t id = idBits.clearFirstMarkedBit();
4394 const RawPointerData::Pointer& pointer =
4395 mCurrentRawState.rawPointerData.pointerForId(id);
4396 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4397 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4398 mCurrentCookedState.stylusIdBits.markBit(id);
4399 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4400 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4401 mCurrentCookedState.fingerIdBits.markBit(id);
4402 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4403 mCurrentCookedState.mouseIdBits.markBit(id);
4404 }
4405 }
4406 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4407 !idBits.isEmpty(); ) {
4408 uint32_t id = idBits.clearFirstMarkedBit();
4409 const RawPointerData::Pointer& pointer =
4410 mCurrentRawState.rawPointerData.pointerForId(id);
4411 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4412 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4413 mCurrentCookedState.stylusIdBits.markBit(id);
4414 }
4415 }
4416
4417 // Stylus takes precedence over all tools, then mouse, then finger.
4418 PointerUsage pointerUsage = mPointerUsage;
4419 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4420 mCurrentCookedState.mouseIdBits.clear();
4421 mCurrentCookedState.fingerIdBits.clear();
4422 pointerUsage = POINTER_USAGE_STYLUS;
4423 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4424 mCurrentCookedState.fingerIdBits.clear();
4425 pointerUsage = POINTER_USAGE_MOUSE;
4426 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4427 isPointerDown(mCurrentRawState.buttonState)) {
4428 pointerUsage = POINTER_USAGE_GESTURES;
4429 }
4430
4431 dispatchPointerUsage(when, policyFlags, pointerUsage);
4432 } else {
4433 if (mDeviceMode == DEVICE_MODE_DIRECT
4434 && mConfig.showTouches && mPointerController != NULL) {
4435 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4436 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4437
4438 mPointerController->setButtonState(mCurrentRawState.buttonState);
4439 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4440 mCurrentCookedState.cookedPointerData.idToIndex,
4441 mCurrentCookedState.cookedPointerData.touchingIdBits);
4442 }
4443
Michael Wright8e812822015-06-22 16:18:21 +01004444 if (!mCurrentMotionAborted) {
4445 dispatchButtonRelease(when, policyFlags);
4446 dispatchHoverExit(when, policyFlags);
4447 dispatchTouches(when, policyFlags);
4448 dispatchHoverEnterAndMove(when, policyFlags);
4449 dispatchButtonPress(when, policyFlags);
4450 }
4451
4452 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4453 mCurrentMotionAborted = false;
4454 }
Michael Wright842500e2015-03-13 17:32:02 -07004455 }
4456
4457 // Synthesize key up from raw buttons if needed.
4458 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004459 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004460
4461 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004462 mCurrentRawState.rawVScroll = 0;
4463 mCurrentRawState.rawHScroll = 0;
4464
4465 // Copy current touch to last touch in preparation for the next cycle.
4466 mLastRawState.copyFrom(mCurrentRawState);
4467 mLastCookedState.copyFrom(mCurrentCookedState);
4468}
4469
4470void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004471 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004472 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4473 }
4474}
4475
4476void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004477 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4478 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004479
Michael Wright53dca3a2015-04-23 17:39:53 +01004480 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4481 float pressure = mExternalStylusState.pressure;
4482 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4483 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4484 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4485 }
4486 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4487 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4488
4489 PointerProperties& properties =
4490 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004491 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4492 properties.toolType = mExternalStylusState.toolType;
4493 }
4494 }
4495}
4496
4497bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4498 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4499 return false;
4500 }
4501
4502 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4503 && state.rawPointerData.pointerCount != 0;
4504 if (initialDown) {
4505 if (mExternalStylusState.pressure != 0.0f) {
4506#if DEBUG_STYLUS_FUSION
4507 ALOGD("Have both stylus and touch data, beginning fusion");
4508#endif
4509 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4510 } else if (timeout) {
4511#if DEBUG_STYLUS_FUSION
4512 ALOGD("Timeout expired, assuming touch is not a stylus.");
4513#endif
4514 resetExternalStylus();
4515 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004516 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4517 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004518 }
4519#if DEBUG_STYLUS_FUSION
4520 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004521 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004522#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004523 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004524 return true;
4525 }
4526 }
4527
4528 // Check if the stylus pointer has gone up.
4529 if (mExternalStylusId != -1 &&
4530 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4531#if DEBUG_STYLUS_FUSION
4532 ALOGD("Stylus pointer is going up");
4533#endif
4534 mExternalStylusId = -1;
4535 }
4536
4537 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004538}
4539
4540void TouchInputMapper::timeoutExpired(nsecs_t when) {
4541 if (mDeviceMode == DEVICE_MODE_POINTER) {
4542 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4543 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4544 }
Michael Wright842500e2015-03-13 17:32:02 -07004545 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004546 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004547 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004548 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4549 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004550 }
4551 }
4552}
4553
4554void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004555 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004556 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004557 // We're either in the middle of a fused stream of data or we're waiting on data before
4558 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4559 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004560 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004561 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004562 }
4563}
4564
4565bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4566 // Check for release of a virtual key.
4567 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004568 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004569 // Pointer went up while virtual key was down.
4570 mCurrentVirtualKey.down = false;
4571 if (!mCurrentVirtualKey.ignored) {
4572#if DEBUG_VIRTUAL_KEYS
4573 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4574 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4575#endif
4576 dispatchVirtualKey(when, policyFlags,
4577 AKEY_EVENT_ACTION_UP,
4578 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4579 }
4580 return true;
4581 }
4582
Michael Wright842500e2015-03-13 17:32:02 -07004583 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4584 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4585 const RawPointerData::Pointer& pointer =
4586 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004587 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4588 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4589 // Pointer is still within the space of the virtual key.
4590 return true;
4591 }
4592 }
4593
4594 // Pointer left virtual key area or another pointer also went down.
4595 // Send key cancellation but do not consume the touch yet.
4596 // This is useful when the user swipes through from the virtual key area
4597 // into the main display surface.
4598 mCurrentVirtualKey.down = false;
4599 if (!mCurrentVirtualKey.ignored) {
4600#if DEBUG_VIRTUAL_KEYS
4601 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4602 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4603#endif
4604 dispatchVirtualKey(when, policyFlags,
4605 AKEY_EVENT_ACTION_UP,
4606 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4607 | AKEY_EVENT_FLAG_CANCELED);
4608 }
4609 }
4610
Michael Wright842500e2015-03-13 17:32:02 -07004611 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4612 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004613 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004614 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4615 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4617 // If exactly one pointer went down, check for virtual key hit.
4618 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004619 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4621 if (virtualKey) {
4622 mCurrentVirtualKey.down = true;
4623 mCurrentVirtualKey.downTime = when;
4624 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4625 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4626 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4627 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4628
4629 if (!mCurrentVirtualKey.ignored) {
4630#if DEBUG_VIRTUAL_KEYS
4631 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4632 mCurrentVirtualKey.keyCode,
4633 mCurrentVirtualKey.scanCode);
4634#endif
4635 dispatchVirtualKey(when, policyFlags,
4636 AKEY_EVENT_ACTION_DOWN,
4637 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4638 }
4639 }
4640 }
4641 return true;
4642 }
4643 }
4644
4645 // Disable all virtual key touches that happen within a short time interval of the
4646 // most recent touch within the screen area. The idea is to filter out stray
4647 // virtual key presses when interacting with the touch screen.
4648 //
4649 // Problems we're trying to solve:
4650 //
4651 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4652 // virtual key area that is implemented by a separate touch panel and accidentally
4653 // triggers a virtual key.
4654 //
4655 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4656 // area and accidentally triggers a virtual key. This often happens when virtual keys
4657 // are layed out below the screen near to where the on screen keyboard's space bar
4658 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004659 if (mConfig.virtualKeyQuietTime > 0 &&
4660 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004661 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4662 }
4663 return false;
4664}
4665
4666void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4667 int32_t keyEventAction, int32_t keyEventFlags) {
4668 int32_t keyCode = mCurrentVirtualKey.keyCode;
4669 int32_t scanCode = mCurrentVirtualKey.scanCode;
4670 nsecs_t downTime = mCurrentVirtualKey.downTime;
4671 int32_t metaState = mContext->getGlobalMetaState();
4672 policyFlags |= POLICY_FLAG_VIRTUAL;
4673
4674 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4675 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4676 getListener()->notifyKey(&args);
4677}
4678
Michael Wright8e812822015-06-22 16:18:21 +01004679void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4680 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4681 if (!currentIdBits.isEmpty()) {
4682 int32_t metaState = getContext()->getGlobalMetaState();
4683 int32_t buttonState = mCurrentCookedState.buttonState;
4684 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4685 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4686 mCurrentCookedState.cookedPointerData.pointerProperties,
4687 mCurrentCookedState.cookedPointerData.pointerCoords,
4688 mCurrentCookedState.cookedPointerData.idToIndex,
4689 currentIdBits, -1,
4690 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4691 mCurrentMotionAborted = true;
4692 }
4693}
4694
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004696 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4697 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004699 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700
4701 if (currentIdBits == lastIdBits) {
4702 if (!currentIdBits.isEmpty()) {
4703 // No pointer id changes so this is a move event.
4704 // The listener takes care of batching moves so we don't have to deal with that here.
4705 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004706 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004708 mCurrentCookedState.cookedPointerData.pointerProperties,
4709 mCurrentCookedState.cookedPointerData.pointerCoords,
4710 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 currentIdBits, -1,
4712 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4713 }
4714 } else {
4715 // There may be pointers going up and pointers going down and pointers moving
4716 // all at the same time.
4717 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4718 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4719 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4720 BitSet32 dispatchedIdBits(lastIdBits.value);
4721
4722 // Update last coordinates of pointers that have moved so that we observe the new
4723 // pointer positions at the same time as other pointers that have just gone up.
4724 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004725 mCurrentCookedState.cookedPointerData.pointerProperties,
4726 mCurrentCookedState.cookedPointerData.pointerCoords,
4727 mCurrentCookedState.cookedPointerData.idToIndex,
4728 mLastCookedState.cookedPointerData.pointerProperties,
4729 mLastCookedState.cookedPointerData.pointerCoords,
4730 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004732 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 moveNeeded = true;
4734 }
4735
4736 // Dispatch pointer up events.
4737 while (!upIdBits.isEmpty()) {
4738 uint32_t upId = upIdBits.clearFirstMarkedBit();
4739
4740 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004741 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004742 mLastCookedState.cookedPointerData.pointerProperties,
4743 mLastCookedState.cookedPointerData.pointerCoords,
4744 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004745 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004746 dispatchedIdBits.clearBit(upId);
4747 }
4748
4749 // Dispatch move events if any of the remaining pointers moved from their old locations.
4750 // Although applications receive new locations as part of individual pointer up
4751 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004752 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4754 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004755 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004756 mCurrentCookedState.cookedPointerData.pointerProperties,
4757 mCurrentCookedState.cookedPointerData.pointerCoords,
4758 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004759 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 }
4761
4762 // Dispatch pointer down events using the new pointer locations.
4763 while (!downIdBits.isEmpty()) {
4764 uint32_t downId = downIdBits.clearFirstMarkedBit();
4765 dispatchedIdBits.markBit(downId);
4766
4767 if (dispatchedIdBits.count() == 1) {
4768 // First pointer is going down. Set down time.
4769 mDownTime = when;
4770 }
4771
4772 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004773 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004774 mCurrentCookedState.cookedPointerData.pointerProperties,
4775 mCurrentCookedState.cookedPointerData.pointerCoords,
4776 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004777 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004778 }
4779 }
4780}
4781
4782void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4783 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004784 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4785 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004786 int32_t metaState = getContext()->getGlobalMetaState();
4787 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004788 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004789 mLastCookedState.cookedPointerData.pointerProperties,
4790 mLastCookedState.cookedPointerData.pointerCoords,
4791 mLastCookedState.cookedPointerData.idToIndex,
4792 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4794 mSentHoverEnter = false;
4795 }
4796}
4797
4798void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004799 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4800 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 int32_t metaState = getContext()->getGlobalMetaState();
4802 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004803 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004804 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004805 mCurrentCookedState.cookedPointerData.pointerProperties,
4806 mCurrentCookedState.cookedPointerData.pointerCoords,
4807 mCurrentCookedState.cookedPointerData.idToIndex,
4808 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004809 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4810 mSentHoverEnter = true;
4811 }
4812
4813 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004814 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004815 mCurrentRawState.buttonState, 0,
4816 mCurrentCookedState.cookedPointerData.pointerProperties,
4817 mCurrentCookedState.cookedPointerData.pointerCoords,
4818 mCurrentCookedState.cookedPointerData.idToIndex,
4819 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4821 }
4822}
4823
Michael Wright7b159c92015-05-14 14:48:03 +01004824void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4825 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4826 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4827 const int32_t metaState = getContext()->getGlobalMetaState();
4828 int32_t buttonState = mLastCookedState.buttonState;
4829 while (!releasedButtons.isEmpty()) {
4830 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4831 buttonState &= ~actionButton;
4832 dispatchMotion(when, policyFlags, mSource,
4833 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4834 0, metaState, buttonState, 0,
4835 mCurrentCookedState.cookedPointerData.pointerProperties,
4836 mCurrentCookedState.cookedPointerData.pointerCoords,
4837 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4838 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4839 }
4840}
4841
4842void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4843 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4844 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4845 const int32_t metaState = getContext()->getGlobalMetaState();
4846 int32_t buttonState = mLastCookedState.buttonState;
4847 while (!pressedButtons.isEmpty()) {
4848 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4849 buttonState |= actionButton;
4850 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4851 0, metaState, buttonState, 0,
4852 mCurrentCookedState.cookedPointerData.pointerProperties,
4853 mCurrentCookedState.cookedPointerData.pointerCoords,
4854 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4855 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4856 }
4857}
4858
4859const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4860 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4861 return cookedPointerData.touchingIdBits;
4862 }
4863 return cookedPointerData.hoveringIdBits;
4864}
4865
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004867 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868
Michael Wright842500e2015-03-13 17:32:02 -07004869 mCurrentCookedState.cookedPointerData.clear();
4870 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4871 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4872 mCurrentRawState.rawPointerData.hoveringIdBits;
4873 mCurrentCookedState.cookedPointerData.touchingIdBits =
4874 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875
Michael Wright7b159c92015-05-14 14:48:03 +01004876 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4877 mCurrentCookedState.buttonState = 0;
4878 } else {
4879 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4880 }
4881
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 // Walk through the the active pointers and map device coordinates onto
4883 // surface coordinates and adjust for display orientation.
4884 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004885 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886
4887 // Size
4888 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4889 switch (mCalibration.sizeCalibration) {
4890 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4891 case Calibration::SIZE_CALIBRATION_DIAMETER:
4892 case Calibration::SIZE_CALIBRATION_BOX:
4893 case Calibration::SIZE_CALIBRATION_AREA:
4894 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4895 touchMajor = in.touchMajor;
4896 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4897 toolMajor = in.toolMajor;
4898 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4899 size = mRawPointerAxes.touchMinor.valid
4900 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4901 } else if (mRawPointerAxes.touchMajor.valid) {
4902 toolMajor = touchMajor = in.touchMajor;
4903 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4904 ? in.touchMinor : in.touchMajor;
4905 size = mRawPointerAxes.touchMinor.valid
4906 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4907 } else if (mRawPointerAxes.toolMajor.valid) {
4908 touchMajor = toolMajor = in.toolMajor;
4909 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4910 ? in.toolMinor : in.toolMajor;
4911 size = mRawPointerAxes.toolMinor.valid
4912 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4913 } else {
4914 ALOG_ASSERT(false, "No touch or tool axes. "
4915 "Size calibration should have been resolved to NONE.");
4916 touchMajor = 0;
4917 touchMinor = 0;
4918 toolMajor = 0;
4919 toolMinor = 0;
4920 size = 0;
4921 }
4922
4923 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004924 uint32_t touchingCount =
4925 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 if (touchingCount > 1) {
4927 touchMajor /= touchingCount;
4928 touchMinor /= touchingCount;
4929 toolMajor /= touchingCount;
4930 toolMinor /= touchingCount;
4931 size /= touchingCount;
4932 }
4933 }
4934
4935 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4936 touchMajor *= mGeometricScale;
4937 touchMinor *= mGeometricScale;
4938 toolMajor *= mGeometricScale;
4939 toolMinor *= mGeometricScale;
4940 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4941 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4942 touchMinor = touchMajor;
4943 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4944 toolMinor = toolMajor;
4945 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4946 touchMinor = touchMajor;
4947 toolMinor = toolMajor;
4948 }
4949
4950 mCalibration.applySizeScaleAndBias(&touchMajor);
4951 mCalibration.applySizeScaleAndBias(&touchMinor);
4952 mCalibration.applySizeScaleAndBias(&toolMajor);
4953 mCalibration.applySizeScaleAndBias(&toolMinor);
4954 size *= mSizeScale;
4955 break;
4956 default:
4957 touchMajor = 0;
4958 touchMinor = 0;
4959 toolMajor = 0;
4960 toolMinor = 0;
4961 size = 0;
4962 break;
4963 }
4964
4965 // Pressure
4966 float pressure;
4967 switch (mCalibration.pressureCalibration) {
4968 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4969 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4970 pressure = in.pressure * mPressureScale;
4971 break;
4972 default:
4973 pressure = in.isHovering ? 0 : 1;
4974 break;
4975 }
4976
4977 // Tilt and Orientation
4978 float tilt;
4979 float orientation;
4980 if (mHaveTilt) {
4981 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4982 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4983 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4984 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4985 } else {
4986 tilt = 0;
4987
4988 switch (mCalibration.orientationCalibration) {
4989 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4990 orientation = in.orientation * mOrientationScale;
4991 break;
4992 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4993 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4994 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4995 if (c1 != 0 || c2 != 0) {
4996 orientation = atan2f(c1, c2) * 0.5f;
4997 float confidence = hypotf(c1, c2);
4998 float scale = 1.0f + confidence / 16.0f;
4999 touchMajor *= scale;
5000 touchMinor /= scale;
5001 toolMajor *= scale;
5002 toolMinor /= scale;
5003 } else {
5004 orientation = 0;
5005 }
5006 break;
5007 }
5008 default:
5009 orientation = 0;
5010 }
5011 }
5012
5013 // Distance
5014 float distance;
5015 switch (mCalibration.distanceCalibration) {
5016 case Calibration::DISTANCE_CALIBRATION_SCALED:
5017 distance = in.distance * mDistanceScale;
5018 break;
5019 default:
5020 distance = 0;
5021 }
5022
5023 // Coverage
5024 int32_t rawLeft, rawTop, rawRight, rawBottom;
5025 switch (mCalibration.coverageCalibration) {
5026 case Calibration::COVERAGE_CALIBRATION_BOX:
5027 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5028 rawRight = in.toolMinor & 0x0000ffff;
5029 rawBottom = in.toolMajor & 0x0000ffff;
5030 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5031 break;
5032 default:
5033 rawLeft = rawTop = rawRight = rawBottom = 0;
5034 break;
5035 }
5036
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005037 // Adjust X,Y coords for device calibration
5038 // TODO: Adjust coverage coords?
5039 float xTransformed = in.x, yTransformed = in.y;
5040 mAffineTransform.applyTo(xTransformed, yTransformed);
5041
5042 // Adjust X, Y, and coverage coords for surface orientation.
5043 float x, y;
5044 float left, top, right, bottom;
5045
Michael Wrightd02c5b62014-02-10 15:10:22 -08005046 switch (mSurfaceOrientation) {
5047 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005048 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5049 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005050 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5051 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5052 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5053 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5054 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005055 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005056 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5057 }
5058 break;
5059 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005060 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5061 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005062 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5063 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5064 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5065 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5066 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005067 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005068 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5069 }
5070 break;
5071 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005072 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5073 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005074 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5075 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5076 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5077 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5078 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005079 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005080 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5081 }
5082 break;
5083 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005084 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5085 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5087 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5088 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5089 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5090 break;
5091 }
5092
5093 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005094 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095 out.clear();
5096 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5097 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5098 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5099 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5100 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5101 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5102 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5103 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5104 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5105 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5106 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5107 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5108 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5109 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5110 } else {
5111 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5112 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5113 }
5114
5115 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005116 PointerProperties& properties =
5117 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005118 uint32_t id = in.id;
5119 properties.clear();
5120 properties.id = id;
5121 properties.toolType = in.toolType;
5122
5123 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005124 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125 }
5126}
5127
5128void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5129 PointerUsage pointerUsage) {
5130 if (pointerUsage != mPointerUsage) {
5131 abortPointerUsage(when, policyFlags);
5132 mPointerUsage = pointerUsage;
5133 }
5134
5135 switch (mPointerUsage) {
5136 case POINTER_USAGE_GESTURES:
5137 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5138 break;
5139 case POINTER_USAGE_STYLUS:
5140 dispatchPointerStylus(when, policyFlags);
5141 break;
5142 case POINTER_USAGE_MOUSE:
5143 dispatchPointerMouse(when, policyFlags);
5144 break;
5145 default:
5146 break;
5147 }
5148}
5149
5150void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5151 switch (mPointerUsage) {
5152 case POINTER_USAGE_GESTURES:
5153 abortPointerGestures(when, policyFlags);
5154 break;
5155 case POINTER_USAGE_STYLUS:
5156 abortPointerStylus(when, policyFlags);
5157 break;
5158 case POINTER_USAGE_MOUSE:
5159 abortPointerMouse(when, policyFlags);
5160 break;
5161 default:
5162 break;
5163 }
5164
5165 mPointerUsage = POINTER_USAGE_NONE;
5166}
5167
5168void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5169 bool isTimeout) {
5170 // Update current gesture coordinates.
5171 bool cancelPreviousGesture, finishPreviousGesture;
5172 bool sendEvents = preparePointerGestures(when,
5173 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5174 if (!sendEvents) {
5175 return;
5176 }
5177 if (finishPreviousGesture) {
5178 cancelPreviousGesture = false;
5179 }
5180
5181 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005182 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5183 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184 if (finishPreviousGesture || cancelPreviousGesture) {
5185 mPointerController->clearSpots();
5186 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005187
5188 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5189 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5190 mPointerGesture.currentGestureIdToIndex,
5191 mPointerGesture.currentGestureIdBits);
5192 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 } else {
5194 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5195 }
5196
5197 // Show or hide the pointer if needed.
5198 switch (mPointerGesture.currentGestureMode) {
5199 case PointerGesture::NEUTRAL:
5200 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005201 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5202 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 // Remind the user of where the pointer is after finishing a gesture with spots.
5204 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5205 }
5206 break;
5207 case PointerGesture::TAP:
5208 case PointerGesture::TAP_DRAG:
5209 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5210 case PointerGesture::HOVER:
5211 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005212 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005213 // Unfade the pointer when the current gesture manipulates the
5214 // area directly under the pointer.
5215 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5216 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005217 case PointerGesture::FREEFORM:
5218 // Fade the pointer when the current gesture manipulates a different
5219 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005220 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5222 } else {
5223 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5224 }
5225 break;
5226 }
5227
5228 // Send events!
5229 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005230 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231
5232 // Update last coordinates of pointers that have moved so that we observe the new
5233 // pointer positions at the same time as other pointers that have just gone up.
5234 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5235 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5236 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5237 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5238 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5239 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5240 bool moveNeeded = false;
5241 if (down && !cancelPreviousGesture && !finishPreviousGesture
5242 && !mPointerGesture.lastGestureIdBits.isEmpty()
5243 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5244 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5245 & mPointerGesture.lastGestureIdBits.value);
5246 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5247 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5248 mPointerGesture.lastGestureProperties,
5249 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5250 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005251 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252 moveNeeded = true;
5253 }
5254 }
5255
5256 // Send motion events for all pointers that went up or were canceled.
5257 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5258 if (!dispatchedGestureIdBits.isEmpty()) {
5259 if (cancelPreviousGesture) {
5260 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005261 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 AMOTION_EVENT_EDGE_FLAG_NONE,
5263 mPointerGesture.lastGestureProperties,
5264 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005265 dispatchedGestureIdBits, -1, 0,
5266 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005267
5268 dispatchedGestureIdBits.clear();
5269 } else {
5270 BitSet32 upGestureIdBits;
5271 if (finishPreviousGesture) {
5272 upGestureIdBits = dispatchedGestureIdBits;
5273 } else {
5274 upGestureIdBits.value = dispatchedGestureIdBits.value
5275 & ~mPointerGesture.currentGestureIdBits.value;
5276 }
5277 while (!upGestureIdBits.isEmpty()) {
5278 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5279
5280 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005281 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5283 mPointerGesture.lastGestureProperties,
5284 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5285 dispatchedGestureIdBits, id,
5286 0, 0, mPointerGesture.downTime);
5287
5288 dispatchedGestureIdBits.clearBit(id);
5289 }
5290 }
5291 }
5292
5293 // Send motion events for all pointers that moved.
5294 if (moveNeeded) {
5295 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005296 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5297 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 mPointerGesture.currentGestureProperties,
5299 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5300 dispatchedGestureIdBits, -1,
5301 0, 0, mPointerGesture.downTime);
5302 }
5303
5304 // Send motion events for all pointers that went down.
5305 if (down) {
5306 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5307 & ~dispatchedGestureIdBits.value);
5308 while (!downGestureIdBits.isEmpty()) {
5309 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5310 dispatchedGestureIdBits.markBit(id);
5311
5312 if (dispatchedGestureIdBits.count() == 1) {
5313 mPointerGesture.downTime = when;
5314 }
5315
5316 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005317 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318 mPointerGesture.currentGestureProperties,
5319 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5320 dispatchedGestureIdBits, id,
5321 0, 0, mPointerGesture.downTime);
5322 }
5323 }
5324
5325 // Send motion events for hover.
5326 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5327 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005328 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5330 mPointerGesture.currentGestureProperties,
5331 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5332 mPointerGesture.currentGestureIdBits, -1,
5333 0, 0, mPointerGesture.downTime);
5334 } else if (dispatchedGestureIdBits.isEmpty()
5335 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5336 // Synthesize a hover move event after all pointers go up to indicate that
5337 // the pointer is hovering again even if the user is not currently touching
5338 // the touch pad. This ensures that a view will receive a fresh hover enter
5339 // event after a tap.
5340 float x, y;
5341 mPointerController->getPosition(&x, &y);
5342
5343 PointerProperties pointerProperties;
5344 pointerProperties.clear();
5345 pointerProperties.id = 0;
5346 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5347
5348 PointerCoords pointerCoords;
5349 pointerCoords.clear();
5350 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5351 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5352
5353 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005354 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005355 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5356 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5357 0, 0, mPointerGesture.downTime);
5358 getListener()->notifyMotion(&args);
5359 }
5360
5361 // Update state.
5362 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5363 if (!down) {
5364 mPointerGesture.lastGestureIdBits.clear();
5365 } else {
5366 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5367 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5368 uint32_t id = idBits.clearFirstMarkedBit();
5369 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5370 mPointerGesture.lastGestureProperties[index].copyFrom(
5371 mPointerGesture.currentGestureProperties[index]);
5372 mPointerGesture.lastGestureCoords[index].copyFrom(
5373 mPointerGesture.currentGestureCoords[index]);
5374 mPointerGesture.lastGestureIdToIndex[id] = index;
5375 }
5376 }
5377}
5378
5379void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5380 // Cancel previously dispatches pointers.
5381 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5382 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005383 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005385 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386 AMOTION_EVENT_EDGE_FLAG_NONE,
5387 mPointerGesture.lastGestureProperties,
5388 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5389 mPointerGesture.lastGestureIdBits, -1,
5390 0, 0, mPointerGesture.downTime);
5391 }
5392
5393 // Reset the current pointer gesture.
5394 mPointerGesture.reset();
5395 mPointerVelocityControl.reset();
5396
5397 // Remove any current spots.
5398 if (mPointerController != NULL) {
5399 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5400 mPointerController->clearSpots();
5401 }
5402}
5403
5404bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5405 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5406 *outCancelPreviousGesture = false;
5407 *outFinishPreviousGesture = false;
5408
5409 // Handle TAP timeout.
5410 if (isTimeout) {
5411#if DEBUG_GESTURES
5412 ALOGD("Gestures: Processing timeout");
5413#endif
5414
5415 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5416 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5417 // The tap/drag timeout has not yet expired.
5418 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5419 + mConfig.pointerGestureTapDragInterval);
5420 } else {
5421 // The tap is finished.
5422#if DEBUG_GESTURES
5423 ALOGD("Gestures: TAP finished");
5424#endif
5425 *outFinishPreviousGesture = true;
5426
5427 mPointerGesture.activeGestureId = -1;
5428 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5429 mPointerGesture.currentGestureIdBits.clear();
5430
5431 mPointerVelocityControl.reset();
5432 return true;
5433 }
5434 }
5435
5436 // We did not handle this timeout.
5437 return false;
5438 }
5439
Michael Wright842500e2015-03-13 17:32:02 -07005440 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5441 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442
5443 // Update the velocity tracker.
5444 {
5445 VelocityTracker::Position positions[MAX_POINTERS];
5446 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005447 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005449 const RawPointerData::Pointer& pointer =
5450 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451 positions[count].x = pointer.x * mPointerXMovementScale;
5452 positions[count].y = pointer.y * mPointerYMovementScale;
5453 }
5454 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005455 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005456 }
5457
5458 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5459 // to NEUTRAL, then we should not generate tap event.
5460 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5461 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5462 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5463 mPointerGesture.resetTap();
5464 }
5465
5466 // Pick a new active touch id if needed.
5467 // Choose an arbitrary pointer that just went down, if there is one.
5468 // Otherwise choose an arbitrary remaining pointer.
5469 // This guarantees we always have an active touch id when there is at least one pointer.
5470 // We keep the same active touch id for as long as possible.
5471 bool activeTouchChanged = false;
5472 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5473 int32_t activeTouchId = lastActiveTouchId;
5474 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005475 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 activeTouchChanged = true;
5477 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005478 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479 mPointerGesture.firstTouchTime = when;
5480 }
Michael Wright842500e2015-03-13 17:32:02 -07005481 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 activeTouchChanged = true;
Michael Wright842500e2015-03-13 17:32:02 -07005483 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005485 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005486 } else {
5487 activeTouchId = mPointerGesture.activeTouchId = -1;
5488 }
5489 }
5490
5491 // Determine whether we are in quiet time.
5492 bool isQuietTime = false;
5493 if (activeTouchId < 0) {
5494 mPointerGesture.resetQuietTime();
5495 } else {
5496 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5497 if (!isQuietTime) {
5498 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5499 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5500 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5501 && currentFingerCount < 2) {
5502 // Enter quiet time when exiting swipe or freeform state.
5503 // This is to prevent accidentally entering the hover state and flinging the
5504 // pointer when finishing a swipe and there is still one pointer left onscreen.
5505 isQuietTime = true;
5506 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5507 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005508 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005509 // Enter quiet time when releasing the button and there are still two or more
5510 // fingers down. This may indicate that one finger was used to press the button
5511 // but it has not gone up yet.
5512 isQuietTime = true;
5513 }
5514 if (isQuietTime) {
5515 mPointerGesture.quietTime = when;
5516 }
5517 }
5518 }
5519
5520 // Switch states based on button and pointer state.
5521 if (isQuietTime) {
5522 // Case 1: Quiet time. (QUIET)
5523#if DEBUG_GESTURES
5524 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5525 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5526#endif
5527 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5528 *outFinishPreviousGesture = true;
5529 }
5530
5531 mPointerGesture.activeGestureId = -1;
5532 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5533 mPointerGesture.currentGestureIdBits.clear();
5534
5535 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005536 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5538 // The pointer follows the active touch point.
5539 // Emit DOWN, MOVE, UP events at the pointer location.
5540 //
5541 // Only the active touch matters; other fingers are ignored. This policy helps
5542 // to handle the case where the user places a second finger on the touch pad
5543 // to apply the necessary force to depress an integrated button below the surface.
5544 // We don't want the second finger to be delivered to applications.
5545 //
5546 // For this to work well, we need to make sure to track the pointer that is really
5547 // active. If the user first puts one finger down to click then adds another
5548 // finger to drag then the active pointer should switch to the finger that is
5549 // being dragged.
5550#if DEBUG_GESTURES
5551 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5552 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5553#endif
5554 // Reset state when just starting.
5555 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5556 *outFinishPreviousGesture = true;
5557 mPointerGesture.activeGestureId = 0;
5558 }
5559
5560 // Switch pointers if needed.
5561 // Find the fastest pointer and follow it.
5562 if (activeTouchId >= 0 && currentFingerCount > 1) {
5563 int32_t bestId = -1;
5564 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005565 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566 uint32_t id = idBits.clearFirstMarkedBit();
5567 float vx, vy;
5568 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5569 float speed = hypotf(vx, vy);
5570 if (speed > bestSpeed) {
5571 bestId = id;
5572 bestSpeed = speed;
5573 }
5574 }
5575 }
5576 if (bestId >= 0 && bestId != activeTouchId) {
5577 mPointerGesture.activeTouchId = activeTouchId = bestId;
5578 activeTouchChanged = true;
5579#if DEBUG_GESTURES
5580 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5581 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5582#endif
5583 }
5584 }
5585
Jun Mukaifa1706a2015-12-03 01:14:46 -08005586 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005587 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005588 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005589 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005591 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005592 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5593 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005594
5595 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5596 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5597
5598 // Move the pointer using a relative motion.
5599 // When using spots, the click will occur at the position of the anchor
5600 // spot and all other spots will move there.
5601 mPointerController->move(deltaX, deltaY);
5602 } else {
5603 mPointerVelocityControl.reset();
5604 }
5605
5606 float x, y;
5607 mPointerController->getPosition(&x, &y);
5608
5609 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5610 mPointerGesture.currentGestureIdBits.clear();
5611 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5612 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5613 mPointerGesture.currentGestureProperties[0].clear();
5614 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5615 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5616 mPointerGesture.currentGestureCoords[0].clear();
5617 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5618 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5619 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5620 } else if (currentFingerCount == 0) {
5621 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5622 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5623 *outFinishPreviousGesture = true;
5624 }
5625
5626 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5627 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5628 bool tapped = false;
5629 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5630 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5631 && lastFingerCount == 1) {
5632 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5633 float x, y;
5634 mPointerController->getPosition(&x, &y);
5635 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5636 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5637#if DEBUG_GESTURES
5638 ALOGD("Gestures: TAP");
5639#endif
5640
5641 mPointerGesture.tapUpTime = when;
5642 getContext()->requestTimeoutAtTime(when
5643 + mConfig.pointerGestureTapDragInterval);
5644
5645 mPointerGesture.activeGestureId = 0;
5646 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5647 mPointerGesture.currentGestureIdBits.clear();
5648 mPointerGesture.currentGestureIdBits.markBit(
5649 mPointerGesture.activeGestureId);
5650 mPointerGesture.currentGestureIdToIndex[
5651 mPointerGesture.activeGestureId] = 0;
5652 mPointerGesture.currentGestureProperties[0].clear();
5653 mPointerGesture.currentGestureProperties[0].id =
5654 mPointerGesture.activeGestureId;
5655 mPointerGesture.currentGestureProperties[0].toolType =
5656 AMOTION_EVENT_TOOL_TYPE_FINGER;
5657 mPointerGesture.currentGestureCoords[0].clear();
5658 mPointerGesture.currentGestureCoords[0].setAxisValue(
5659 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5660 mPointerGesture.currentGestureCoords[0].setAxisValue(
5661 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5662 mPointerGesture.currentGestureCoords[0].setAxisValue(
5663 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5664
5665 tapped = true;
5666 } else {
5667#if DEBUG_GESTURES
5668 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5669 x - mPointerGesture.tapX,
5670 y - mPointerGesture.tapY);
5671#endif
5672 }
5673 } else {
5674#if DEBUG_GESTURES
5675 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5676 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5677 (when - mPointerGesture.tapDownTime) * 0.000001f);
5678 } else {
5679 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5680 }
5681#endif
5682 }
5683 }
5684
5685 mPointerVelocityControl.reset();
5686
5687 if (!tapped) {
5688#if DEBUG_GESTURES
5689 ALOGD("Gestures: NEUTRAL");
5690#endif
5691 mPointerGesture.activeGestureId = -1;
5692 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5693 mPointerGesture.currentGestureIdBits.clear();
5694 }
5695 } else if (currentFingerCount == 1) {
5696 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5697 // The pointer follows the active touch point.
5698 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5699 // When in TAP_DRAG, emit MOVE events at the pointer location.
5700 ALOG_ASSERT(activeTouchId >= 0);
5701
5702 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5703 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5704 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5705 float x, y;
5706 mPointerController->getPosition(&x, &y);
5707 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5708 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5709 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5710 } else {
5711#if DEBUG_GESTURES
5712 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5713 x - mPointerGesture.tapX,
5714 y - mPointerGesture.tapY);
5715#endif
5716 }
5717 } else {
5718#if DEBUG_GESTURES
5719 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5720 (when - mPointerGesture.tapUpTime) * 0.000001f);
5721#endif
5722 }
5723 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5724 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5725 }
5726
Jun Mukaifa1706a2015-12-03 01:14:46 -08005727 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005728 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005729 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005730 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005731 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005732 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005733 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5734 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005735
5736 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5737 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5738
5739 // Move the pointer using a relative motion.
5740 // When using spots, the hover or drag will occur at the position of the anchor spot.
5741 mPointerController->move(deltaX, deltaY);
5742 } else {
5743 mPointerVelocityControl.reset();
5744 }
5745
5746 bool down;
5747 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5748#if DEBUG_GESTURES
5749 ALOGD("Gestures: TAP_DRAG");
5750#endif
5751 down = true;
5752 } else {
5753#if DEBUG_GESTURES
5754 ALOGD("Gestures: HOVER");
5755#endif
5756 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5757 *outFinishPreviousGesture = true;
5758 }
5759 mPointerGesture.activeGestureId = 0;
5760 down = false;
5761 }
5762
5763 float x, y;
5764 mPointerController->getPosition(&x, &y);
5765
5766 mPointerGesture.currentGestureIdBits.clear();
5767 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5768 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5769 mPointerGesture.currentGestureProperties[0].clear();
5770 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5771 mPointerGesture.currentGestureProperties[0].toolType =
5772 AMOTION_EVENT_TOOL_TYPE_FINGER;
5773 mPointerGesture.currentGestureCoords[0].clear();
5774 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5775 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5776 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5777 down ? 1.0f : 0.0f);
5778
5779 if (lastFingerCount == 0 && currentFingerCount != 0) {
5780 mPointerGesture.resetTap();
5781 mPointerGesture.tapDownTime = when;
5782 mPointerGesture.tapX = x;
5783 mPointerGesture.tapY = y;
5784 }
5785 } else {
5786 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5787 // We need to provide feedback for each finger that goes down so we cannot wait
5788 // for the fingers to move before deciding what to do.
5789 //
5790 // The ambiguous case is deciding what to do when there are two fingers down but they
5791 // have not moved enough to determine whether they are part of a drag or part of a
5792 // freeform gesture, or just a press or long-press at the pointer location.
5793 //
5794 // When there are two fingers we start with the PRESS hypothesis and we generate a
5795 // down at the pointer location.
5796 //
5797 // When the two fingers move enough or when additional fingers are added, we make
5798 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5799 ALOG_ASSERT(activeTouchId >= 0);
5800
5801 bool settled = when >= mPointerGesture.firstTouchTime
5802 + mConfig.pointerGestureMultitouchSettleInterval;
5803 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5804 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5805 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5806 *outFinishPreviousGesture = true;
5807 } else if (!settled && currentFingerCount > lastFingerCount) {
5808 // Additional pointers have gone down but not yet settled.
5809 // Reset the gesture.
5810#if DEBUG_GESTURES
5811 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5812 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5813 + mConfig.pointerGestureMultitouchSettleInterval - when)
5814 * 0.000001f);
5815#endif
5816 *outCancelPreviousGesture = true;
5817 } else {
5818 // Continue previous gesture.
5819 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5820 }
5821
5822 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5823 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5824 mPointerGesture.activeGestureId = 0;
5825 mPointerGesture.referenceIdBits.clear();
5826 mPointerVelocityControl.reset();
5827
5828 // Use the centroid and pointer location as the reference points for the gesture.
5829#if DEBUG_GESTURES
5830 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5831 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5832 + mConfig.pointerGestureMultitouchSettleInterval - when)
5833 * 0.000001f);
5834#endif
Michael Wright842500e2015-03-13 17:32:02 -07005835 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005836 &mPointerGesture.referenceTouchX,
5837 &mPointerGesture.referenceTouchY);
5838 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5839 &mPointerGesture.referenceGestureY);
5840 }
5841
5842 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005843 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005844 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5845 uint32_t id = idBits.clearFirstMarkedBit();
5846 mPointerGesture.referenceDeltas[id].dx = 0;
5847 mPointerGesture.referenceDeltas[id].dy = 0;
5848 }
Michael Wright842500e2015-03-13 17:32:02 -07005849 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005850
5851 // Add delta for all fingers and calculate a common movement delta.
5852 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005853 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5854 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005855 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5856 bool first = (idBits == commonIdBits);
5857 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005858 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5859 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005860 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5861 delta.dx += cpd.x - lpd.x;
5862 delta.dy += cpd.y - lpd.y;
5863
5864 if (first) {
5865 commonDeltaX = delta.dx;
5866 commonDeltaY = delta.dy;
5867 } else {
5868 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5869 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5870 }
5871 }
5872
5873 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5874 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5875 float dist[MAX_POINTER_ID + 1];
5876 int32_t distOverThreshold = 0;
5877 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5878 uint32_t id = idBits.clearFirstMarkedBit();
5879 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5880 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5881 delta.dy * mPointerYZoomScale);
5882 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5883 distOverThreshold += 1;
5884 }
5885 }
5886
5887 // Only transition when at least two pointers have moved further than
5888 // the minimum distance threshold.
5889 if (distOverThreshold >= 2) {
5890 if (currentFingerCount > 2) {
5891 // There are more than two pointers, switch to FREEFORM.
5892#if DEBUG_GESTURES
5893 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5894 currentFingerCount);
5895#endif
5896 *outCancelPreviousGesture = true;
5897 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5898 } else {
5899 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005900 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901 uint32_t id1 = idBits.clearFirstMarkedBit();
5902 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005903 const RawPointerData::Pointer& p1 =
5904 mCurrentRawState.rawPointerData.pointerForId(id1);
5905 const RawPointerData::Pointer& p2 =
5906 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005907 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5908 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5909 // There are two pointers but they are too far apart for a SWIPE,
5910 // switch to FREEFORM.
5911#if DEBUG_GESTURES
5912 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5913 mutualDistance, mPointerGestureMaxSwipeWidth);
5914#endif
5915 *outCancelPreviousGesture = true;
5916 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5917 } else {
5918 // There are two pointers. Wait for both pointers to start moving
5919 // before deciding whether this is a SWIPE or FREEFORM gesture.
5920 float dist1 = dist[id1];
5921 float dist2 = dist[id2];
5922 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5923 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5924 // Calculate the dot product of the displacement vectors.
5925 // When the vectors are oriented in approximately the same direction,
5926 // the angle betweeen them is near zero and the cosine of the angle
5927 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5928 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5929 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5930 float dx1 = delta1.dx * mPointerXZoomScale;
5931 float dy1 = delta1.dy * mPointerYZoomScale;
5932 float dx2 = delta2.dx * mPointerXZoomScale;
5933 float dy2 = delta2.dy * mPointerYZoomScale;
5934 float dot = dx1 * dx2 + dy1 * dy2;
5935 float cosine = dot / (dist1 * dist2); // denominator always > 0
5936 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5937 // Pointers are moving in the same direction. Switch to SWIPE.
5938#if DEBUG_GESTURES
5939 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5940 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5941 "cosine %0.3f >= %0.3f",
5942 dist1, mConfig.pointerGestureMultitouchMinDistance,
5943 dist2, mConfig.pointerGestureMultitouchMinDistance,
5944 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5945#endif
5946 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5947 } else {
5948 // Pointers are moving in different directions. Switch to FREEFORM.
5949#if DEBUG_GESTURES
5950 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5951 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5952 "cosine %0.3f < %0.3f",
5953 dist1, mConfig.pointerGestureMultitouchMinDistance,
5954 dist2, mConfig.pointerGestureMultitouchMinDistance,
5955 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5956#endif
5957 *outCancelPreviousGesture = true;
5958 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5959 }
5960 }
5961 }
5962 }
5963 }
5964 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5965 // Switch from SWIPE to FREEFORM if additional pointers go down.
5966 // Cancel previous gesture.
5967 if (currentFingerCount > 2) {
5968#if DEBUG_GESTURES
5969 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5970 currentFingerCount);
5971#endif
5972 *outCancelPreviousGesture = true;
5973 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5974 }
5975 }
5976
5977 // Move the reference points based on the overall group motion of the fingers
5978 // except in PRESS mode while waiting for a transition to occur.
5979 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5980 && (commonDeltaX || commonDeltaY)) {
5981 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5982 uint32_t id = idBits.clearFirstMarkedBit();
5983 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5984 delta.dx = 0;
5985 delta.dy = 0;
5986 }
5987
5988 mPointerGesture.referenceTouchX += commonDeltaX;
5989 mPointerGesture.referenceTouchY += commonDeltaY;
5990
5991 commonDeltaX *= mPointerXMovementScale;
5992 commonDeltaY *= mPointerYMovementScale;
5993
5994 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5995 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5996
5997 mPointerGesture.referenceGestureX += commonDeltaX;
5998 mPointerGesture.referenceGestureY += commonDeltaY;
5999 }
6000
6001 // Report gestures.
6002 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6003 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6004 // PRESS or SWIPE mode.
6005#if DEBUG_GESTURES
6006 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6007 "activeGestureId=%d, currentTouchPointerCount=%d",
6008 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6009#endif
6010 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6011
6012 mPointerGesture.currentGestureIdBits.clear();
6013 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6014 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6015 mPointerGesture.currentGestureProperties[0].clear();
6016 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6017 mPointerGesture.currentGestureProperties[0].toolType =
6018 AMOTION_EVENT_TOOL_TYPE_FINGER;
6019 mPointerGesture.currentGestureCoords[0].clear();
6020 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6021 mPointerGesture.referenceGestureX);
6022 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6023 mPointerGesture.referenceGestureY);
6024 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6025 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6026 // FREEFORM mode.
6027#if DEBUG_GESTURES
6028 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6029 "activeGestureId=%d, currentTouchPointerCount=%d",
6030 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6031#endif
6032 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6033
6034 mPointerGesture.currentGestureIdBits.clear();
6035
6036 BitSet32 mappedTouchIdBits;
6037 BitSet32 usedGestureIdBits;
6038 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6039 // Initially, assign the active gesture id to the active touch point
6040 // if there is one. No other touch id bits are mapped yet.
6041 if (!*outCancelPreviousGesture) {
6042 mappedTouchIdBits.markBit(activeTouchId);
6043 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6044 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6045 mPointerGesture.activeGestureId;
6046 } else {
6047 mPointerGesture.activeGestureId = -1;
6048 }
6049 } else {
6050 // Otherwise, assume we mapped all touches from the previous frame.
6051 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006052 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6053 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006054 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6055
6056 // Check whether we need to choose a new active gesture id because the
6057 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006058 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6059 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006060 !upTouchIdBits.isEmpty(); ) {
6061 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6062 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6063 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6064 mPointerGesture.activeGestureId = -1;
6065 break;
6066 }
6067 }
6068 }
6069
6070#if DEBUG_GESTURES
6071 ALOGD("Gestures: FREEFORM follow up "
6072 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6073 "activeGestureId=%d",
6074 mappedTouchIdBits.value, usedGestureIdBits.value,
6075 mPointerGesture.activeGestureId);
6076#endif
6077
Michael Wright842500e2015-03-13 17:32:02 -07006078 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006079 for (uint32_t i = 0; i < currentFingerCount; i++) {
6080 uint32_t touchId = idBits.clearFirstMarkedBit();
6081 uint32_t gestureId;
6082 if (!mappedTouchIdBits.hasBit(touchId)) {
6083 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6084 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6085#if DEBUG_GESTURES
6086 ALOGD("Gestures: FREEFORM "
6087 "new mapping for touch id %d -> gesture id %d",
6088 touchId, gestureId);
6089#endif
6090 } else {
6091 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6092#if DEBUG_GESTURES
6093 ALOGD("Gestures: FREEFORM "
6094 "existing mapping for touch id %d -> gesture id %d",
6095 touchId, gestureId);
6096#endif
6097 }
6098 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6099 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6100
6101 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006102 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006103 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6104 * mPointerXZoomScale;
6105 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6106 * mPointerYZoomScale;
6107 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6108
6109 mPointerGesture.currentGestureProperties[i].clear();
6110 mPointerGesture.currentGestureProperties[i].id = gestureId;
6111 mPointerGesture.currentGestureProperties[i].toolType =
6112 AMOTION_EVENT_TOOL_TYPE_FINGER;
6113 mPointerGesture.currentGestureCoords[i].clear();
6114 mPointerGesture.currentGestureCoords[i].setAxisValue(
6115 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6116 mPointerGesture.currentGestureCoords[i].setAxisValue(
6117 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6118 mPointerGesture.currentGestureCoords[i].setAxisValue(
6119 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6120 }
6121
6122 if (mPointerGesture.activeGestureId < 0) {
6123 mPointerGesture.activeGestureId =
6124 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6125#if DEBUG_GESTURES
6126 ALOGD("Gestures: FREEFORM new "
6127 "activeGestureId=%d", mPointerGesture.activeGestureId);
6128#endif
6129 }
6130 }
6131 }
6132
Michael Wright842500e2015-03-13 17:32:02 -07006133 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006134
6135#if DEBUG_GESTURES
6136 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6137 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6138 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6139 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6140 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6141 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6142 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6143 uint32_t id = idBits.clearFirstMarkedBit();
6144 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6145 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6146 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6147 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6148 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6149 id, index, properties.toolType,
6150 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6151 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6152 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6153 }
6154 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6155 uint32_t id = idBits.clearFirstMarkedBit();
6156 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6157 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6158 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6159 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6160 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6161 id, index, properties.toolType,
6162 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6163 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6164 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6165 }
6166#endif
6167 return true;
6168}
6169
6170void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6171 mPointerSimple.currentCoords.clear();
6172 mPointerSimple.currentProperties.clear();
6173
6174 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006175 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6176 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6177 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6178 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6179 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180 mPointerController->setPosition(x, y);
6181
Michael Wright842500e2015-03-13 17:32:02 -07006182 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006183 down = !hovering;
6184
6185 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006186 mPointerSimple.currentCoords.copyFrom(
6187 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006188 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6189 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6190 mPointerSimple.currentProperties.id = 0;
6191 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006192 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006193 } else {
6194 down = false;
6195 hovering = false;
6196 }
6197
6198 dispatchPointerSimple(when, policyFlags, down, hovering);
6199}
6200
6201void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6202 abortPointerSimple(when, policyFlags);
6203}
6204
6205void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6206 mPointerSimple.currentCoords.clear();
6207 mPointerSimple.currentProperties.clear();
6208
6209 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006210 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6211 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6212 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006213 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006214 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6215 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006216 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006217 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006219 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006220 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006221 * mPointerYMovementScale;
6222
6223 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6224 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6225
6226 mPointerController->move(deltaX, deltaY);
6227 } else {
6228 mPointerVelocityControl.reset();
6229 }
6230
Michael Wright842500e2015-03-13 17:32:02 -07006231 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006232 hovering = !down;
6233
6234 float x, y;
6235 mPointerController->getPosition(&x, &y);
6236 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006237 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006238 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6239 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6240 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6241 hovering ? 0.0f : 1.0f);
6242 mPointerSimple.currentProperties.id = 0;
6243 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006244 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006245 } else {
6246 mPointerVelocityControl.reset();
6247
6248 down = false;
6249 hovering = false;
6250 }
6251
6252 dispatchPointerSimple(when, policyFlags, down, hovering);
6253}
6254
6255void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6256 abortPointerSimple(when, policyFlags);
6257
6258 mPointerVelocityControl.reset();
6259}
6260
6261void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6262 bool down, bool hovering) {
6263 int32_t metaState = getContext()->getGlobalMetaState();
6264
6265 if (mPointerController != NULL) {
6266 if (down || hovering) {
6267 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6268 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006269 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006270 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6271 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6272 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6273 }
6274 }
6275
6276 if (mPointerSimple.down && !down) {
6277 mPointerSimple.down = false;
6278
6279 // Send up.
6280 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006281 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006282 mViewport.displayId,
6283 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6284 mOrientedXPrecision, mOrientedYPrecision,
6285 mPointerSimple.downTime);
6286 getListener()->notifyMotion(&args);
6287 }
6288
6289 if (mPointerSimple.hovering && !hovering) {
6290 mPointerSimple.hovering = false;
6291
6292 // Send hover exit.
6293 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006294 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006295 mViewport.displayId,
6296 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6297 mOrientedXPrecision, mOrientedYPrecision,
6298 mPointerSimple.downTime);
6299 getListener()->notifyMotion(&args);
6300 }
6301
6302 if (down) {
6303 if (!mPointerSimple.down) {
6304 mPointerSimple.down = true;
6305 mPointerSimple.downTime = when;
6306
6307 // Send down.
6308 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006309 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006310 mViewport.displayId,
6311 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6312 mOrientedXPrecision, mOrientedYPrecision,
6313 mPointerSimple.downTime);
6314 getListener()->notifyMotion(&args);
6315 }
6316
6317 // Send move.
6318 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006319 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006320 mViewport.displayId,
6321 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6322 mOrientedXPrecision, mOrientedYPrecision,
6323 mPointerSimple.downTime);
6324 getListener()->notifyMotion(&args);
6325 }
6326
6327 if (hovering) {
6328 if (!mPointerSimple.hovering) {
6329 mPointerSimple.hovering = true;
6330
6331 // Send hover enter.
6332 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006333 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006334 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006335 mViewport.displayId,
6336 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6337 mOrientedXPrecision, mOrientedYPrecision,
6338 mPointerSimple.downTime);
6339 getListener()->notifyMotion(&args);
6340 }
6341
6342 // Send hover move.
6343 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006344 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006345 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006346 mViewport.displayId,
6347 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6348 mOrientedXPrecision, mOrientedYPrecision,
6349 mPointerSimple.downTime);
6350 getListener()->notifyMotion(&args);
6351 }
6352
Michael Wright842500e2015-03-13 17:32:02 -07006353 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6354 float vscroll = mCurrentRawState.rawVScroll;
6355 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006356 mWheelYVelocityControl.move(when, NULL, &vscroll);
6357 mWheelXVelocityControl.move(when, &hscroll, NULL);
6358
6359 // Send scroll.
6360 PointerCoords pointerCoords;
6361 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6362 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6363 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6364
6365 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006366 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006367 mViewport.displayId,
6368 1, &mPointerSimple.currentProperties, &pointerCoords,
6369 mOrientedXPrecision, mOrientedYPrecision,
6370 mPointerSimple.downTime);
6371 getListener()->notifyMotion(&args);
6372 }
6373
6374 // Save state.
6375 if (down || hovering) {
6376 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6377 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6378 } else {
6379 mPointerSimple.reset();
6380 }
6381}
6382
6383void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6384 mPointerSimple.currentCoords.clear();
6385 mPointerSimple.currentProperties.clear();
6386
6387 dispatchPointerSimple(when, policyFlags, false, false);
6388}
6389
6390void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006391 int32_t action, int32_t actionButton, int32_t flags,
6392 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006393 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006394 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6395 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006396 PointerCoords pointerCoords[MAX_POINTERS];
6397 PointerProperties pointerProperties[MAX_POINTERS];
6398 uint32_t pointerCount = 0;
6399 while (!idBits.isEmpty()) {
6400 uint32_t id = idBits.clearFirstMarkedBit();
6401 uint32_t index = idToIndex[id];
6402 pointerProperties[pointerCount].copyFrom(properties[index]);
6403 pointerCoords[pointerCount].copyFrom(coords[index]);
6404
6405 if (changedId >= 0 && id == uint32_t(changedId)) {
6406 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6407 }
6408
6409 pointerCount += 1;
6410 }
6411
6412 ALOG_ASSERT(pointerCount != 0);
6413
6414 if (changedId >= 0 && pointerCount == 1) {
6415 // Replace initial down and final up action.
6416 // We can compare the action without masking off the changed pointer index
6417 // because we know the index is 0.
6418 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6419 action = AMOTION_EVENT_ACTION_DOWN;
6420 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6421 action = AMOTION_EVENT_ACTION_UP;
6422 } else {
6423 // Can't happen.
6424 ALOG_ASSERT(false);
6425 }
6426 }
6427
6428 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006429 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006430 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6431 xPrecision, yPrecision, downTime);
6432 getListener()->notifyMotion(&args);
6433}
6434
6435bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6436 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6437 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6438 BitSet32 idBits) const {
6439 bool changed = false;
6440 while (!idBits.isEmpty()) {
6441 uint32_t id = idBits.clearFirstMarkedBit();
6442 uint32_t inIndex = inIdToIndex[id];
6443 uint32_t outIndex = outIdToIndex[id];
6444
6445 const PointerProperties& curInProperties = inProperties[inIndex];
6446 const PointerCoords& curInCoords = inCoords[inIndex];
6447 PointerProperties& curOutProperties = outProperties[outIndex];
6448 PointerCoords& curOutCoords = outCoords[outIndex];
6449
6450 if (curInProperties != curOutProperties) {
6451 curOutProperties.copyFrom(curInProperties);
6452 changed = true;
6453 }
6454
6455 if (curInCoords != curOutCoords) {
6456 curOutCoords.copyFrom(curInCoords);
6457 changed = true;
6458 }
6459 }
6460 return changed;
6461}
6462
6463void TouchInputMapper::fadePointer() {
6464 if (mPointerController != NULL) {
6465 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6466 }
6467}
6468
Jeff Brownc9aa6282015-02-11 19:03:28 -08006469void TouchInputMapper::cancelTouch(nsecs_t when) {
6470 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006471 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006472}
6473
Michael Wrightd02c5b62014-02-10 15:10:22 -08006474bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6475 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6476 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6477}
6478
6479const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6480 int32_t x, int32_t y) {
6481 size_t numVirtualKeys = mVirtualKeys.size();
6482 for (size_t i = 0; i < numVirtualKeys; i++) {
6483 const VirtualKey& virtualKey = mVirtualKeys[i];
6484
6485#if DEBUG_VIRTUAL_KEYS
6486 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6487 "left=%d, top=%d, right=%d, bottom=%d",
6488 x, y,
6489 virtualKey.keyCode, virtualKey.scanCode,
6490 virtualKey.hitLeft, virtualKey.hitTop,
6491 virtualKey.hitRight, virtualKey.hitBottom);
6492#endif
6493
6494 if (virtualKey.isHit(x, y)) {
6495 return & virtualKey;
6496 }
6497 }
6498
6499 return NULL;
6500}
6501
Michael Wright842500e2015-03-13 17:32:02 -07006502void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6503 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6504 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006505
Michael Wright842500e2015-03-13 17:32:02 -07006506 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006507
6508 if (currentPointerCount == 0) {
6509 // No pointers to assign.
6510 return;
6511 }
6512
6513 if (lastPointerCount == 0) {
6514 // All pointers are new.
6515 for (uint32_t i = 0; i < currentPointerCount; i++) {
6516 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006517 current->rawPointerData.pointers[i].id = id;
6518 current->rawPointerData.idToIndex[id] = i;
6519 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006520 }
6521 return;
6522 }
6523
6524 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006525 && current->rawPointerData.pointers[0].toolType
6526 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006527 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006528 uint32_t id = last->rawPointerData.pointers[0].id;
6529 current->rawPointerData.pointers[0].id = id;
6530 current->rawPointerData.idToIndex[id] = 0;
6531 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006532 return;
6533 }
6534
6535 // General case.
6536 // We build a heap of squared euclidean distances between current and last pointers
6537 // associated with the current and last pointer indices. Then, we find the best
6538 // match (by distance) for each current pointer.
6539 // The pointers must have the same tool type but it is possible for them to
6540 // transition from hovering to touching or vice-versa while retaining the same id.
6541 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6542
6543 uint32_t heapSize = 0;
6544 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6545 currentPointerIndex++) {
6546 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6547 lastPointerIndex++) {
6548 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006549 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006550 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006551 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552 if (currentPointer.toolType == lastPointer.toolType) {
6553 int64_t deltaX = currentPointer.x - lastPointer.x;
6554 int64_t deltaY = currentPointer.y - lastPointer.y;
6555
6556 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6557
6558 // Insert new element into the heap (sift up).
6559 heap[heapSize].currentPointerIndex = currentPointerIndex;
6560 heap[heapSize].lastPointerIndex = lastPointerIndex;
6561 heap[heapSize].distance = distance;
6562 heapSize += 1;
6563 }
6564 }
6565 }
6566
6567 // Heapify
6568 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6569 startIndex -= 1;
6570 for (uint32_t parentIndex = startIndex; ;) {
6571 uint32_t childIndex = parentIndex * 2 + 1;
6572 if (childIndex >= heapSize) {
6573 break;
6574 }
6575
6576 if (childIndex + 1 < heapSize
6577 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6578 childIndex += 1;
6579 }
6580
6581 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6582 break;
6583 }
6584
6585 swap(heap[parentIndex], heap[childIndex]);
6586 parentIndex = childIndex;
6587 }
6588 }
6589
6590#if DEBUG_POINTER_ASSIGNMENT
6591 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6592 for (size_t i = 0; i < heapSize; i++) {
6593 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6594 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6595 heap[i].distance);
6596 }
6597#endif
6598
6599 // Pull matches out by increasing order of distance.
6600 // To avoid reassigning pointers that have already been matched, the loop keeps track
6601 // of which last and current pointers have been matched using the matchedXXXBits variables.
6602 // It also tracks the used pointer id bits.
6603 BitSet32 matchedLastBits(0);
6604 BitSet32 matchedCurrentBits(0);
6605 BitSet32 usedIdBits(0);
6606 bool first = true;
6607 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6608 while (heapSize > 0) {
6609 if (first) {
6610 // The first time through the loop, we just consume the root element of
6611 // the heap (the one with smallest distance).
6612 first = false;
6613 } else {
6614 // Previous iterations consumed the root element of the heap.
6615 // Pop root element off of the heap (sift down).
6616 heap[0] = heap[heapSize];
6617 for (uint32_t parentIndex = 0; ;) {
6618 uint32_t childIndex = parentIndex * 2 + 1;
6619 if (childIndex >= heapSize) {
6620 break;
6621 }
6622
6623 if (childIndex + 1 < heapSize
6624 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6625 childIndex += 1;
6626 }
6627
6628 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6629 break;
6630 }
6631
6632 swap(heap[parentIndex], heap[childIndex]);
6633 parentIndex = childIndex;
6634 }
6635
6636#if DEBUG_POINTER_ASSIGNMENT
6637 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6638 for (size_t i = 0; i < heapSize; i++) {
6639 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6640 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6641 heap[i].distance);
6642 }
6643#endif
6644 }
6645
6646 heapSize -= 1;
6647
6648 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6649 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6650
6651 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6652 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6653
6654 matchedCurrentBits.markBit(currentPointerIndex);
6655 matchedLastBits.markBit(lastPointerIndex);
6656
Michael Wright842500e2015-03-13 17:32:02 -07006657 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6658 current->rawPointerData.pointers[currentPointerIndex].id = id;
6659 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6660 current->rawPointerData.markIdBit(id,
6661 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006662 usedIdBits.markBit(id);
6663
6664#if DEBUG_POINTER_ASSIGNMENT
6665 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
6666 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6667#endif
6668 break;
6669 }
6670 }
6671
6672 // Assign fresh ids to pointers that were not matched in the process.
6673 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6674 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6675 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6676
Michael Wright842500e2015-03-13 17:32:02 -07006677 current->rawPointerData.pointers[currentPointerIndex].id = id;
6678 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6679 current->rawPointerData.markIdBit(id,
6680 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006681
6682#if DEBUG_POINTER_ASSIGNMENT
6683 ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
6684 currentPointerIndex, id);
6685#endif
6686 }
6687}
6688
6689int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6690 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6691 return AKEY_STATE_VIRTUAL;
6692 }
6693
6694 size_t numVirtualKeys = mVirtualKeys.size();
6695 for (size_t i = 0; i < numVirtualKeys; i++) {
6696 const VirtualKey& virtualKey = mVirtualKeys[i];
6697 if (virtualKey.keyCode == keyCode) {
6698 return AKEY_STATE_UP;
6699 }
6700 }
6701
6702 return AKEY_STATE_UNKNOWN;
6703}
6704
6705int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6706 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6707 return AKEY_STATE_VIRTUAL;
6708 }
6709
6710 size_t numVirtualKeys = mVirtualKeys.size();
6711 for (size_t i = 0; i < numVirtualKeys; i++) {
6712 const VirtualKey& virtualKey = mVirtualKeys[i];
6713 if (virtualKey.scanCode == scanCode) {
6714 return AKEY_STATE_UP;
6715 }
6716 }
6717
6718 return AKEY_STATE_UNKNOWN;
6719}
6720
6721bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6722 const int32_t* keyCodes, uint8_t* outFlags) {
6723 size_t numVirtualKeys = mVirtualKeys.size();
6724 for (size_t i = 0; i < numVirtualKeys; i++) {
6725 const VirtualKey& virtualKey = mVirtualKeys[i];
6726
6727 for (size_t i = 0; i < numCodes; i++) {
6728 if (virtualKey.keyCode == keyCodes[i]) {
6729 outFlags[i] = 1;
6730 }
6731 }
6732 }
6733
6734 return true;
6735}
6736
6737
6738// --- SingleTouchInputMapper ---
6739
6740SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6741 TouchInputMapper(device) {
6742}
6743
6744SingleTouchInputMapper::~SingleTouchInputMapper() {
6745}
6746
6747void SingleTouchInputMapper::reset(nsecs_t when) {
6748 mSingleTouchMotionAccumulator.reset(getDevice());
6749
6750 TouchInputMapper::reset(when);
6751}
6752
6753void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6754 TouchInputMapper::process(rawEvent);
6755
6756 mSingleTouchMotionAccumulator.process(rawEvent);
6757}
6758
Michael Wright842500e2015-03-13 17:32:02 -07006759void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006760 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006761 outState->rawPointerData.pointerCount = 1;
6762 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006763
6764 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6765 && (mTouchButtonAccumulator.isHovering()
6766 || (mRawPointerAxes.pressure.valid
6767 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006768 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006769
Michael Wright842500e2015-03-13 17:32:02 -07006770 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006771 outPointer.id = 0;
6772 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6773 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6774 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6775 outPointer.touchMajor = 0;
6776 outPointer.touchMinor = 0;
6777 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6778 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6779 outPointer.orientation = 0;
6780 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6781 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6782 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6783 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6784 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6785 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6786 }
6787 outPointer.isHovering = isHovering;
6788 }
6789}
6790
6791void SingleTouchInputMapper::configureRawPointerAxes() {
6792 TouchInputMapper::configureRawPointerAxes();
6793
6794 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6795 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6796 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6797 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6798 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6799 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6800 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6801}
6802
6803bool SingleTouchInputMapper::hasStylus() const {
6804 return mTouchButtonAccumulator.hasStylus();
6805}
6806
6807
6808// --- MultiTouchInputMapper ---
6809
6810MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6811 TouchInputMapper(device) {
6812}
6813
6814MultiTouchInputMapper::~MultiTouchInputMapper() {
6815}
6816
6817void MultiTouchInputMapper::reset(nsecs_t when) {
6818 mMultiTouchMotionAccumulator.reset(getDevice());
6819
6820 mPointerIdBits.clear();
6821
6822 TouchInputMapper::reset(when);
6823}
6824
6825void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6826 TouchInputMapper::process(rawEvent);
6827
6828 mMultiTouchMotionAccumulator.process(rawEvent);
6829}
6830
Michael Wright842500e2015-03-13 17:32:02 -07006831void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006832 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6833 size_t outCount = 0;
6834 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006835 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006836
6837 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6838 const MultiTouchMotionAccumulator::Slot* inSlot =
6839 mMultiTouchMotionAccumulator.getSlot(inIndex);
6840 if (!inSlot->isInUse()) {
6841 continue;
6842 }
6843
6844 if (outCount >= MAX_POINTERS) {
6845#if DEBUG_POINTERS
6846 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6847 "ignoring the rest.",
6848 getDeviceName().string(), MAX_POINTERS);
6849#endif
6850 break; // too many fingers!
6851 }
6852
Michael Wright842500e2015-03-13 17:32:02 -07006853 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006854 outPointer.x = inSlot->getX();
6855 outPointer.y = inSlot->getY();
6856 outPointer.pressure = inSlot->getPressure();
6857 outPointer.touchMajor = inSlot->getTouchMajor();
6858 outPointer.touchMinor = inSlot->getTouchMinor();
6859 outPointer.toolMajor = inSlot->getToolMajor();
6860 outPointer.toolMinor = inSlot->getToolMinor();
6861 outPointer.orientation = inSlot->getOrientation();
6862 outPointer.distance = inSlot->getDistance();
6863 outPointer.tiltX = 0;
6864 outPointer.tiltY = 0;
6865
6866 outPointer.toolType = inSlot->getToolType();
6867 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6868 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6869 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6870 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6871 }
6872 }
6873
6874 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6875 && (mTouchButtonAccumulator.isHovering()
6876 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6877 outPointer.isHovering = isHovering;
6878
6879 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006880 if (mHavePointerIds) {
6881 int32_t trackingId = inSlot->getTrackingId();
6882 int32_t id = -1;
6883 if (trackingId >= 0) {
6884 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6885 uint32_t n = idBits.clearFirstMarkedBit();
6886 if (mPointerTrackingIdMap[n] == trackingId) {
6887 id = n;
6888 }
6889 }
6890
6891 if (id < 0 && !mPointerIdBits.isFull()) {
6892 id = mPointerIdBits.markFirstUnmarkedBit();
6893 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006894 }
Michael Wright842500e2015-03-13 17:32:02 -07006895 }
gaoshang1a632de2016-08-24 10:23:50 +08006896 if (id < 0) {
6897 mHavePointerIds = false;
6898 outState->rawPointerData.clearIdBits();
6899 newPointerIdBits.clear();
6900 } else {
6901 outPointer.id = id;
6902 outState->rawPointerData.idToIndex[id] = outCount;
6903 outState->rawPointerData.markIdBit(id, isHovering);
6904 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006905 }
Michael Wright842500e2015-03-13 17:32:02 -07006906 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006907 outCount += 1;
6908 }
6909
Michael Wright842500e2015-03-13 17:32:02 -07006910 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006911 mPointerIdBits = newPointerIdBits;
6912
6913 mMultiTouchMotionAccumulator.finishSync();
6914}
6915
6916void MultiTouchInputMapper::configureRawPointerAxes() {
6917 TouchInputMapper::configureRawPointerAxes();
6918
6919 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6920 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6921 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6922 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6923 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6924 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6925 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6926 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6927 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6928 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6929 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6930
6931 if (mRawPointerAxes.trackingId.valid
6932 && mRawPointerAxes.slot.valid
6933 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6934 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6935 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006936 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6937 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006938 getDeviceName().string(), slotCount, MAX_SLOTS);
6939 slotCount = MAX_SLOTS;
6940 }
6941 mMultiTouchMotionAccumulator.configure(getDevice(),
6942 slotCount, true /*usingSlotsProtocol*/);
6943 } else {
6944 mMultiTouchMotionAccumulator.configure(getDevice(),
6945 MAX_POINTERS, false /*usingSlotsProtocol*/);
6946 }
6947}
6948
6949bool MultiTouchInputMapper::hasStylus() const {
6950 return mMultiTouchMotionAccumulator.hasStylus()
6951 || mTouchButtonAccumulator.hasStylus();
6952}
6953
Michael Wright842500e2015-03-13 17:32:02 -07006954// --- ExternalStylusInputMapper
6955
6956ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6957 InputMapper(device) {
6958
6959}
6960
6961uint32_t ExternalStylusInputMapper::getSources() {
6962 return AINPUT_SOURCE_STYLUS;
6963}
6964
6965void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6966 InputMapper::populateDeviceInfo(info);
6967 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
6968 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
6969}
6970
6971void ExternalStylusInputMapper::dump(String8& dump) {
6972 dump.append(INDENT2 "External Stylus Input Mapper:\n");
6973 dump.append(INDENT3 "Raw Stylus Axes:\n");
6974 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
6975 dump.append(INDENT3 "Stylus State:\n");
6976 dumpStylusState(dump, mStylusState);
6977}
6978
6979void ExternalStylusInputMapper::configure(nsecs_t when,
6980 const InputReaderConfiguration* config, uint32_t changes) {
6981 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6982 mTouchButtonAccumulator.configure(getDevice());
6983}
6984
6985void ExternalStylusInputMapper::reset(nsecs_t when) {
6986 InputDevice* device = getDevice();
6987 mSingleTouchMotionAccumulator.reset(device);
6988 mTouchButtonAccumulator.reset(device);
6989 InputMapper::reset(when);
6990}
6991
6992void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
6993 mSingleTouchMotionAccumulator.process(rawEvent);
6994 mTouchButtonAccumulator.process(rawEvent);
6995
6996 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
6997 sync(rawEvent->when);
6998 }
6999}
7000
7001void ExternalStylusInputMapper::sync(nsecs_t when) {
7002 mStylusState.clear();
7003
7004 mStylusState.when = when;
7005
Michael Wright45ccacf2015-04-21 19:01:58 +01007006 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7007 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7008 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7009 }
7010
Michael Wright842500e2015-03-13 17:32:02 -07007011 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7012 if (mRawPressureAxis.valid) {
7013 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7014 } else if (mTouchButtonAccumulator.isToolActive()) {
7015 mStylusState.pressure = 1.0f;
7016 } else {
7017 mStylusState.pressure = 0.0f;
7018 }
7019
7020 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007021
7022 mContext->dispatchExternalStylusState(mStylusState);
7023}
7024
Michael Wrightd02c5b62014-02-10 15:10:22 -08007025
7026// --- JoystickInputMapper ---
7027
7028JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7029 InputMapper(device) {
7030}
7031
7032JoystickInputMapper::~JoystickInputMapper() {
7033}
7034
7035uint32_t JoystickInputMapper::getSources() {
7036 return AINPUT_SOURCE_JOYSTICK;
7037}
7038
7039void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7040 InputMapper::populateDeviceInfo(info);
7041
7042 for (size_t i = 0; i < mAxes.size(); i++) {
7043 const Axis& axis = mAxes.valueAt(i);
7044 addMotionRange(axis.axisInfo.axis, axis, info);
7045
7046 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7047 addMotionRange(axis.axisInfo.highAxis, axis, info);
7048
7049 }
7050 }
7051}
7052
7053void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7054 InputDeviceInfo* info) {
7055 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7056 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7057 /* In order to ease the transition for developers from using the old axes
7058 * to the newer, more semantically correct axes, we'll continue to register
7059 * the old axes as duplicates of their corresponding new ones. */
7060 int32_t compatAxis = getCompatAxis(axisId);
7061 if (compatAxis >= 0) {
7062 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7063 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7064 }
7065}
7066
7067/* A mapping from axes the joystick actually has to the axes that should be
7068 * artificially created for compatibility purposes.
7069 * Returns -1 if no compatibility axis is needed. */
7070int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7071 switch(axis) {
7072 case AMOTION_EVENT_AXIS_LTRIGGER:
7073 return AMOTION_EVENT_AXIS_BRAKE;
7074 case AMOTION_EVENT_AXIS_RTRIGGER:
7075 return AMOTION_EVENT_AXIS_GAS;
7076 }
7077 return -1;
7078}
7079
7080void JoystickInputMapper::dump(String8& dump) {
7081 dump.append(INDENT2 "Joystick Input Mapper:\n");
7082
7083 dump.append(INDENT3 "Axes:\n");
7084 size_t numAxes = mAxes.size();
7085 for (size_t i = 0; i < numAxes; i++) {
7086 const Axis& axis = mAxes.valueAt(i);
7087 const char* label = getAxisLabel(axis.axisInfo.axis);
7088 if (label) {
7089 dump.appendFormat(INDENT4 "%s", label);
7090 } else {
7091 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
7092 }
7093 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7094 label = getAxisLabel(axis.axisInfo.highAxis);
7095 if (label) {
7096 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
7097 } else {
7098 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
7099 axis.axisInfo.splitValue);
7100 }
7101 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
7102 dump.append(" (invert)");
7103 }
7104
7105 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
7106 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7107 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
7108 "highScale=%0.5f, highOffset=%0.5f\n",
7109 axis.scale, axis.offset, axis.highScale, axis.highOffset);
7110 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
7111 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7112 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7113 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7114 }
7115}
7116
7117void JoystickInputMapper::configure(nsecs_t when,
7118 const InputReaderConfiguration* config, uint32_t changes) {
7119 InputMapper::configure(when, config, changes);
7120
7121 if (!changes) { // first time only
7122 // Collect all axes.
7123 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7124 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7125 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7126 continue; // axis must be claimed by a different device
7127 }
7128
7129 RawAbsoluteAxisInfo rawAxisInfo;
7130 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7131 if (rawAxisInfo.valid) {
7132 // Map axis.
7133 AxisInfo axisInfo;
7134 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7135 if (!explicitlyMapped) {
7136 // Axis is not explicitly mapped, will choose a generic axis later.
7137 axisInfo.mode = AxisInfo::MODE_NORMAL;
7138 axisInfo.axis = -1;
7139 }
7140
7141 // Apply flat override.
7142 int32_t rawFlat = axisInfo.flatOverride < 0
7143 ? rawAxisInfo.flat : axisInfo.flatOverride;
7144
7145 // Calculate scaling factors and limits.
7146 Axis axis;
7147 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7148 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7149 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7150 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7151 scale, 0.0f, highScale, 0.0f,
7152 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7153 rawAxisInfo.resolution * scale);
7154 } else if (isCenteredAxis(axisInfo.axis)) {
7155 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7156 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7157 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7158 scale, offset, scale, offset,
7159 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7160 rawAxisInfo.resolution * scale);
7161 } else {
7162 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7163 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7164 scale, 0.0f, scale, 0.0f,
7165 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7166 rawAxisInfo.resolution * scale);
7167 }
7168
7169 // To eliminate noise while the joystick is at rest, filter out small variations
7170 // in axis values up front.
7171 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7172
7173 mAxes.add(abs, axis);
7174 }
7175 }
7176
7177 // If there are too many axes, start dropping them.
7178 // Prefer to keep explicitly mapped axes.
7179 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007180 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007181 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7182 pruneAxes(true);
7183 pruneAxes(false);
7184 }
7185
7186 // Assign generic axis ids to remaining axes.
7187 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7188 size_t numAxes = mAxes.size();
7189 for (size_t i = 0; i < numAxes; i++) {
7190 Axis& axis = mAxes.editValueAt(i);
7191 if (axis.axisInfo.axis < 0) {
7192 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7193 && haveAxis(nextGenericAxisId)) {
7194 nextGenericAxisId += 1;
7195 }
7196
7197 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7198 axis.axisInfo.axis = nextGenericAxisId;
7199 nextGenericAxisId += 1;
7200 } else {
7201 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7202 "have already been assigned to other axes.",
7203 getDeviceName().string(), mAxes.keyAt(i));
7204 mAxes.removeItemsAt(i--);
7205 numAxes -= 1;
7206 }
7207 }
7208 }
7209 }
7210}
7211
7212bool JoystickInputMapper::haveAxis(int32_t axisId) {
7213 size_t numAxes = mAxes.size();
7214 for (size_t i = 0; i < numAxes; i++) {
7215 const Axis& axis = mAxes.valueAt(i);
7216 if (axis.axisInfo.axis == axisId
7217 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7218 && axis.axisInfo.highAxis == axisId)) {
7219 return true;
7220 }
7221 }
7222 return false;
7223}
7224
7225void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7226 size_t i = mAxes.size();
7227 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7228 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7229 continue;
7230 }
7231 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7232 getDeviceName().string(), mAxes.keyAt(i));
7233 mAxes.removeItemsAt(i);
7234 }
7235}
7236
7237bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7238 switch (axis) {
7239 case AMOTION_EVENT_AXIS_X:
7240 case AMOTION_EVENT_AXIS_Y:
7241 case AMOTION_EVENT_AXIS_Z:
7242 case AMOTION_EVENT_AXIS_RX:
7243 case AMOTION_EVENT_AXIS_RY:
7244 case AMOTION_EVENT_AXIS_RZ:
7245 case AMOTION_EVENT_AXIS_HAT_X:
7246 case AMOTION_EVENT_AXIS_HAT_Y:
7247 case AMOTION_EVENT_AXIS_ORIENTATION:
7248 case AMOTION_EVENT_AXIS_RUDDER:
7249 case AMOTION_EVENT_AXIS_WHEEL:
7250 return true;
7251 default:
7252 return false;
7253 }
7254}
7255
7256void JoystickInputMapper::reset(nsecs_t when) {
7257 // Recenter all axes.
7258 size_t numAxes = mAxes.size();
7259 for (size_t i = 0; i < numAxes; i++) {
7260 Axis& axis = mAxes.editValueAt(i);
7261 axis.resetValue();
7262 }
7263
7264 InputMapper::reset(when);
7265}
7266
7267void JoystickInputMapper::process(const RawEvent* rawEvent) {
7268 switch (rawEvent->type) {
7269 case EV_ABS: {
7270 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7271 if (index >= 0) {
7272 Axis& axis = mAxes.editValueAt(index);
7273 float newValue, highNewValue;
7274 switch (axis.axisInfo.mode) {
7275 case AxisInfo::MODE_INVERT:
7276 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7277 * axis.scale + axis.offset;
7278 highNewValue = 0.0f;
7279 break;
7280 case AxisInfo::MODE_SPLIT:
7281 if (rawEvent->value < axis.axisInfo.splitValue) {
7282 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7283 * axis.scale + axis.offset;
7284 highNewValue = 0.0f;
7285 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7286 newValue = 0.0f;
7287 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7288 * axis.highScale + axis.highOffset;
7289 } else {
7290 newValue = 0.0f;
7291 highNewValue = 0.0f;
7292 }
7293 break;
7294 default:
7295 newValue = rawEvent->value * axis.scale + axis.offset;
7296 highNewValue = 0.0f;
7297 break;
7298 }
7299 axis.newValue = newValue;
7300 axis.highNewValue = highNewValue;
7301 }
7302 break;
7303 }
7304
7305 case EV_SYN:
7306 switch (rawEvent->code) {
7307 case SYN_REPORT:
7308 sync(rawEvent->when, false /*force*/);
7309 break;
7310 }
7311 break;
7312 }
7313}
7314
7315void JoystickInputMapper::sync(nsecs_t when, bool force) {
7316 if (!filterAxes(force)) {
7317 return;
7318 }
7319
7320 int32_t metaState = mContext->getGlobalMetaState();
7321 int32_t buttonState = 0;
7322
7323 PointerProperties pointerProperties;
7324 pointerProperties.clear();
7325 pointerProperties.id = 0;
7326 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7327
7328 PointerCoords pointerCoords;
7329 pointerCoords.clear();
7330
7331 size_t numAxes = mAxes.size();
7332 for (size_t i = 0; i < numAxes; i++) {
7333 const Axis& axis = mAxes.valueAt(i);
7334 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7335 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7336 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7337 axis.highCurrentValue);
7338 }
7339 }
7340
7341 // Moving a joystick axis should not wake the device because joysticks can
7342 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7343 // button will likely wake the device.
7344 // TODO: Use the input device configuration to control this behavior more finely.
7345 uint32_t policyFlags = 0;
7346
7347 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007348 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007349 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7350 getListener()->notifyMotion(&args);
7351}
7352
7353void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7354 int32_t axis, float value) {
7355 pointerCoords->setAxisValue(axis, value);
7356 /* In order to ease the transition for developers from using the old axes
7357 * to the newer, more semantically correct axes, we'll continue to produce
7358 * values for the old axes as mirrors of the value of their corresponding
7359 * new axes. */
7360 int32_t compatAxis = getCompatAxis(axis);
7361 if (compatAxis >= 0) {
7362 pointerCoords->setAxisValue(compatAxis, value);
7363 }
7364}
7365
7366bool JoystickInputMapper::filterAxes(bool force) {
7367 bool atLeastOneSignificantChange = force;
7368 size_t numAxes = mAxes.size();
7369 for (size_t i = 0; i < numAxes; i++) {
7370 Axis& axis = mAxes.editValueAt(i);
7371 if (force || hasValueChangedSignificantly(axis.filter,
7372 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7373 axis.currentValue = axis.newValue;
7374 atLeastOneSignificantChange = true;
7375 }
7376 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7377 if (force || hasValueChangedSignificantly(axis.filter,
7378 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7379 axis.highCurrentValue = axis.highNewValue;
7380 atLeastOneSignificantChange = true;
7381 }
7382 }
7383 }
7384 return atLeastOneSignificantChange;
7385}
7386
7387bool JoystickInputMapper::hasValueChangedSignificantly(
7388 float filter, float newValue, float currentValue, float min, float max) {
7389 if (newValue != currentValue) {
7390 // Filter out small changes in value unless the value is converging on the axis
7391 // bounds or center point. This is intended to reduce the amount of information
7392 // sent to applications by particularly noisy joysticks (such as PS3).
7393 if (fabs(newValue - currentValue) > filter
7394 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7395 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7396 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7397 return true;
7398 }
7399 }
7400 return false;
7401}
7402
7403bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7404 float filter, float newValue, float currentValue, float thresholdValue) {
7405 float newDistance = fabs(newValue - thresholdValue);
7406 if (newDistance < filter) {
7407 float oldDistance = fabs(currentValue - thresholdValue);
7408 if (newDistance < oldDistance) {
7409 return true;
7410 }
7411 }
7412 return false;
7413}
7414
7415} // namespace android