blob: 9aef5b84913d1befcc29496e4985789c0a8f2d70 [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) {
Michael Spangaf8a5882017-09-05 20:17:16 -0400260 for (const DisplayViewport& currentViewport : mVirtualDisplays) {
Santos Cordonfa5cf462017-04-05 10:37:00 -0700261 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();
Ivan Lozano623c43a2017-11-09 14:45:38 -08001177 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178#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 }
Ivan Lozano623c43a2017-11-09 14:45:38 -08001205 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
1207}
1208
1209void InputDevice::timeoutExpired(nsecs_t when) {
1210 size_t numMappers = mMappers.size();
1211 for (size_t i = 0; i < numMappers; i++) {
1212 InputMapper* mapper = mMappers[i];
1213 mapper->timeoutExpired(when);
1214 }
1215}
1216
Michael Wright842500e2015-03-13 17:32:02 -07001217void InputDevice::updateExternalStylusState(const StylusState& state) {
1218 size_t numMappers = mMappers.size();
1219 for (size_t i = 0; i < numMappers; i++) {
1220 InputMapper* mapper = mMappers[i];
1221 mapper->updateExternalStylusState(state);
1222 }
1223}
1224
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1226 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001227 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 size_t numMappers = mMappers.size();
1229 for (size_t i = 0; i < numMappers; i++) {
1230 InputMapper* mapper = mMappers[i];
1231 mapper->populateDeviceInfo(outDeviceInfo);
1232 }
1233}
1234
1235int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1236 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1237}
1238
1239int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1240 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1241}
1242
1243int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1244 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1245}
1246
1247int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1248 int32_t result = AKEY_STATE_UNKNOWN;
1249 size_t numMappers = mMappers.size();
1250 for (size_t i = 0; i < numMappers; i++) {
1251 InputMapper* mapper = mMappers[i];
1252 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1253 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1254 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1255 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1256 if (currentResult >= AKEY_STATE_DOWN) {
1257 return currentResult;
1258 } else if (currentResult == AKEY_STATE_UP) {
1259 result = currentResult;
1260 }
1261 }
1262 }
1263 return result;
1264}
1265
1266bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1267 const int32_t* keyCodes, uint8_t* outFlags) {
1268 bool result = false;
1269 size_t numMappers = mMappers.size();
1270 for (size_t i = 0; i < numMappers; i++) {
1271 InputMapper* mapper = mMappers[i];
1272 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1273 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1274 }
1275 }
1276 return result;
1277}
1278
1279void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1280 int32_t token) {
1281 size_t numMappers = mMappers.size();
1282 for (size_t i = 0; i < numMappers; i++) {
1283 InputMapper* mapper = mMappers[i];
1284 mapper->vibrate(pattern, patternSize, repeat, token);
1285 }
1286}
1287
1288void InputDevice::cancelVibrate(int32_t token) {
1289 size_t numMappers = mMappers.size();
1290 for (size_t i = 0; i < numMappers; i++) {
1291 InputMapper* mapper = mMappers[i];
1292 mapper->cancelVibrate(token);
1293 }
1294}
1295
Jeff Brownc9aa6282015-02-11 19:03:28 -08001296void InputDevice::cancelTouch(nsecs_t when) {
1297 size_t numMappers = mMappers.size();
1298 for (size_t i = 0; i < numMappers; i++) {
1299 InputMapper* mapper = mMappers[i];
1300 mapper->cancelTouch(when);
1301 }
1302}
1303
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304int32_t InputDevice::getMetaState() {
1305 int32_t result = 0;
1306 size_t numMappers = mMappers.size();
1307 for (size_t i = 0; i < numMappers; i++) {
1308 InputMapper* mapper = mMappers[i];
1309 result |= mapper->getMetaState();
1310 }
1311 return result;
1312}
1313
Andrii Kulian763a3a42016-03-08 10:46:16 -08001314void InputDevice::updateMetaState(int32_t keyCode) {
1315 size_t numMappers = mMappers.size();
1316 for (size_t i = 0; i < numMappers; i++) {
1317 mMappers[i]->updateMetaState(keyCode);
1318 }
1319}
1320
Michael Wrightd02c5b62014-02-10 15:10:22 -08001321void InputDevice::fadePointer() {
1322 size_t numMappers = mMappers.size();
1323 for (size_t i = 0; i < numMappers; i++) {
1324 InputMapper* mapper = mMappers[i];
1325 mapper->fadePointer();
1326 }
1327}
1328
1329void InputDevice::bumpGeneration() {
1330 mGeneration = mContext->bumpGeneration();
1331}
1332
1333void InputDevice::notifyReset(nsecs_t when) {
1334 NotifyDeviceResetArgs args(when, mId);
1335 mContext->getListener()->notifyDeviceReset(&args);
1336}
1337
1338
1339// --- CursorButtonAccumulator ---
1340
1341CursorButtonAccumulator::CursorButtonAccumulator() {
1342 clearButtons();
1343}
1344
1345void CursorButtonAccumulator::reset(InputDevice* device) {
1346 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1347 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1348 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1349 mBtnBack = device->isKeyPressed(BTN_BACK);
1350 mBtnSide = device->isKeyPressed(BTN_SIDE);
1351 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1352 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1353 mBtnTask = device->isKeyPressed(BTN_TASK);
1354}
1355
1356void CursorButtonAccumulator::clearButtons() {
1357 mBtnLeft = 0;
1358 mBtnRight = 0;
1359 mBtnMiddle = 0;
1360 mBtnBack = 0;
1361 mBtnSide = 0;
1362 mBtnForward = 0;
1363 mBtnExtra = 0;
1364 mBtnTask = 0;
1365}
1366
1367void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1368 if (rawEvent->type == EV_KEY) {
1369 switch (rawEvent->code) {
1370 case BTN_LEFT:
1371 mBtnLeft = rawEvent->value;
1372 break;
1373 case BTN_RIGHT:
1374 mBtnRight = rawEvent->value;
1375 break;
1376 case BTN_MIDDLE:
1377 mBtnMiddle = rawEvent->value;
1378 break;
1379 case BTN_BACK:
1380 mBtnBack = rawEvent->value;
1381 break;
1382 case BTN_SIDE:
1383 mBtnSide = rawEvent->value;
1384 break;
1385 case BTN_FORWARD:
1386 mBtnForward = rawEvent->value;
1387 break;
1388 case BTN_EXTRA:
1389 mBtnExtra = rawEvent->value;
1390 break;
1391 case BTN_TASK:
1392 mBtnTask = rawEvent->value;
1393 break;
1394 }
1395 }
1396}
1397
1398uint32_t CursorButtonAccumulator::getButtonState() const {
1399 uint32_t result = 0;
1400 if (mBtnLeft) {
1401 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1402 }
1403 if (mBtnRight) {
1404 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1405 }
1406 if (mBtnMiddle) {
1407 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1408 }
1409 if (mBtnBack || mBtnSide) {
1410 result |= AMOTION_EVENT_BUTTON_BACK;
1411 }
1412 if (mBtnForward || mBtnExtra) {
1413 result |= AMOTION_EVENT_BUTTON_FORWARD;
1414 }
1415 return result;
1416}
1417
1418
1419// --- CursorMotionAccumulator ---
1420
1421CursorMotionAccumulator::CursorMotionAccumulator() {
1422 clearRelativeAxes();
1423}
1424
1425void CursorMotionAccumulator::reset(InputDevice* device) {
1426 clearRelativeAxes();
1427}
1428
1429void CursorMotionAccumulator::clearRelativeAxes() {
1430 mRelX = 0;
1431 mRelY = 0;
1432}
1433
1434void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1435 if (rawEvent->type == EV_REL) {
1436 switch (rawEvent->code) {
1437 case REL_X:
1438 mRelX = rawEvent->value;
1439 break;
1440 case REL_Y:
1441 mRelY = rawEvent->value;
1442 break;
1443 }
1444 }
1445}
1446
1447void CursorMotionAccumulator::finishSync() {
1448 clearRelativeAxes();
1449}
1450
1451
1452// --- CursorScrollAccumulator ---
1453
1454CursorScrollAccumulator::CursorScrollAccumulator() :
1455 mHaveRelWheel(false), mHaveRelHWheel(false) {
1456 clearRelativeAxes();
1457}
1458
1459void CursorScrollAccumulator::configure(InputDevice* device) {
1460 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1461 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1462}
1463
1464void CursorScrollAccumulator::reset(InputDevice* device) {
1465 clearRelativeAxes();
1466}
1467
1468void CursorScrollAccumulator::clearRelativeAxes() {
1469 mRelWheel = 0;
1470 mRelHWheel = 0;
1471}
1472
1473void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1474 if (rawEvent->type == EV_REL) {
1475 switch (rawEvent->code) {
1476 case REL_WHEEL:
1477 mRelWheel = rawEvent->value;
1478 break;
1479 case REL_HWHEEL:
1480 mRelHWheel = rawEvent->value;
1481 break;
1482 }
1483 }
1484}
1485
1486void CursorScrollAccumulator::finishSync() {
1487 clearRelativeAxes();
1488}
1489
1490
1491// --- TouchButtonAccumulator ---
1492
1493TouchButtonAccumulator::TouchButtonAccumulator() :
1494 mHaveBtnTouch(false), mHaveStylus(false) {
1495 clearButtons();
1496}
1497
1498void TouchButtonAccumulator::configure(InputDevice* device) {
1499 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1500 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1501 || device->hasKey(BTN_TOOL_RUBBER)
1502 || device->hasKey(BTN_TOOL_BRUSH)
1503 || device->hasKey(BTN_TOOL_PENCIL)
1504 || device->hasKey(BTN_TOOL_AIRBRUSH);
1505}
1506
1507void TouchButtonAccumulator::reset(InputDevice* device) {
1508 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1509 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001510 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1511 mBtnStylus2 =
1512 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1514 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1515 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1516 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1517 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1518 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1519 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1520 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1521 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1522 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1523 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1524}
1525
1526void TouchButtonAccumulator::clearButtons() {
1527 mBtnTouch = 0;
1528 mBtnStylus = 0;
1529 mBtnStylus2 = 0;
1530 mBtnToolFinger = 0;
1531 mBtnToolPen = 0;
1532 mBtnToolRubber = 0;
1533 mBtnToolBrush = 0;
1534 mBtnToolPencil = 0;
1535 mBtnToolAirbrush = 0;
1536 mBtnToolMouse = 0;
1537 mBtnToolLens = 0;
1538 mBtnToolDoubleTap = 0;
1539 mBtnToolTripleTap = 0;
1540 mBtnToolQuadTap = 0;
1541}
1542
1543void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1544 if (rawEvent->type == EV_KEY) {
1545 switch (rawEvent->code) {
1546 case BTN_TOUCH:
1547 mBtnTouch = rawEvent->value;
1548 break;
1549 case BTN_STYLUS:
1550 mBtnStylus = rawEvent->value;
1551 break;
1552 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001553 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554 mBtnStylus2 = rawEvent->value;
1555 break;
1556 case BTN_TOOL_FINGER:
1557 mBtnToolFinger = rawEvent->value;
1558 break;
1559 case BTN_TOOL_PEN:
1560 mBtnToolPen = rawEvent->value;
1561 break;
1562 case BTN_TOOL_RUBBER:
1563 mBtnToolRubber = rawEvent->value;
1564 break;
1565 case BTN_TOOL_BRUSH:
1566 mBtnToolBrush = rawEvent->value;
1567 break;
1568 case BTN_TOOL_PENCIL:
1569 mBtnToolPencil = rawEvent->value;
1570 break;
1571 case BTN_TOOL_AIRBRUSH:
1572 mBtnToolAirbrush = rawEvent->value;
1573 break;
1574 case BTN_TOOL_MOUSE:
1575 mBtnToolMouse = rawEvent->value;
1576 break;
1577 case BTN_TOOL_LENS:
1578 mBtnToolLens = rawEvent->value;
1579 break;
1580 case BTN_TOOL_DOUBLETAP:
1581 mBtnToolDoubleTap = rawEvent->value;
1582 break;
1583 case BTN_TOOL_TRIPLETAP:
1584 mBtnToolTripleTap = rawEvent->value;
1585 break;
1586 case BTN_TOOL_QUADTAP:
1587 mBtnToolQuadTap = rawEvent->value;
1588 break;
1589 }
1590 }
1591}
1592
1593uint32_t TouchButtonAccumulator::getButtonState() const {
1594 uint32_t result = 0;
1595 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001596 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 }
1598 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001599 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 }
1601 return result;
1602}
1603
1604int32_t TouchButtonAccumulator::getToolType() const {
1605 if (mBtnToolMouse || mBtnToolLens) {
1606 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1607 }
1608 if (mBtnToolRubber) {
1609 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1610 }
1611 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1612 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1613 }
1614 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1615 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1616 }
1617 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1618}
1619
1620bool TouchButtonAccumulator::isToolActive() const {
1621 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1622 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1623 || mBtnToolMouse || mBtnToolLens
1624 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1625}
1626
1627bool TouchButtonAccumulator::isHovering() const {
1628 return mHaveBtnTouch && !mBtnTouch;
1629}
1630
1631bool TouchButtonAccumulator::hasStylus() const {
1632 return mHaveStylus;
1633}
1634
1635
1636// --- RawPointerAxes ---
1637
1638RawPointerAxes::RawPointerAxes() {
1639 clear();
1640}
1641
1642void RawPointerAxes::clear() {
1643 x.clear();
1644 y.clear();
1645 pressure.clear();
1646 touchMajor.clear();
1647 touchMinor.clear();
1648 toolMajor.clear();
1649 toolMinor.clear();
1650 orientation.clear();
1651 distance.clear();
1652 tiltX.clear();
1653 tiltY.clear();
1654 trackingId.clear();
1655 slot.clear();
1656}
1657
1658
1659// --- RawPointerData ---
1660
1661RawPointerData::RawPointerData() {
1662 clear();
1663}
1664
1665void RawPointerData::clear() {
1666 pointerCount = 0;
1667 clearIdBits();
1668}
1669
1670void RawPointerData::copyFrom(const RawPointerData& other) {
1671 pointerCount = other.pointerCount;
1672 hoveringIdBits = other.hoveringIdBits;
1673 touchingIdBits = other.touchingIdBits;
1674
1675 for (uint32_t i = 0; i < pointerCount; i++) {
1676 pointers[i] = other.pointers[i];
1677
1678 int id = pointers[i].id;
1679 idToIndex[id] = other.idToIndex[id];
1680 }
1681}
1682
1683void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1684 float x = 0, y = 0;
1685 uint32_t count = touchingIdBits.count();
1686 if (count) {
1687 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1688 uint32_t id = idBits.clearFirstMarkedBit();
1689 const Pointer& pointer = pointerForId(id);
1690 x += pointer.x;
1691 y += pointer.y;
1692 }
1693 x /= count;
1694 y /= count;
1695 }
1696 *outX = x;
1697 *outY = y;
1698}
1699
1700
1701// --- CookedPointerData ---
1702
1703CookedPointerData::CookedPointerData() {
1704 clear();
1705}
1706
1707void CookedPointerData::clear() {
1708 pointerCount = 0;
1709 hoveringIdBits.clear();
1710 touchingIdBits.clear();
1711}
1712
1713void CookedPointerData::copyFrom(const CookedPointerData& other) {
1714 pointerCount = other.pointerCount;
1715 hoveringIdBits = other.hoveringIdBits;
1716 touchingIdBits = other.touchingIdBits;
1717
1718 for (uint32_t i = 0; i < pointerCount; i++) {
1719 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1720 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1721
1722 int id = pointerProperties[i].id;
1723 idToIndex[id] = other.idToIndex[id];
1724 }
1725}
1726
1727
1728// --- SingleTouchMotionAccumulator ---
1729
1730SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1731 clearAbsoluteAxes();
1732}
1733
1734void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1735 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1736 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1737 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1738 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1739 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1740 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1741 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1742}
1743
1744void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1745 mAbsX = 0;
1746 mAbsY = 0;
1747 mAbsPressure = 0;
1748 mAbsToolWidth = 0;
1749 mAbsDistance = 0;
1750 mAbsTiltX = 0;
1751 mAbsTiltY = 0;
1752}
1753
1754void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1755 if (rawEvent->type == EV_ABS) {
1756 switch (rawEvent->code) {
1757 case ABS_X:
1758 mAbsX = rawEvent->value;
1759 break;
1760 case ABS_Y:
1761 mAbsY = rawEvent->value;
1762 break;
1763 case ABS_PRESSURE:
1764 mAbsPressure = rawEvent->value;
1765 break;
1766 case ABS_TOOL_WIDTH:
1767 mAbsToolWidth = rawEvent->value;
1768 break;
1769 case ABS_DISTANCE:
1770 mAbsDistance = rawEvent->value;
1771 break;
1772 case ABS_TILT_X:
1773 mAbsTiltX = rawEvent->value;
1774 break;
1775 case ABS_TILT_Y:
1776 mAbsTiltY = rawEvent->value;
1777 break;
1778 }
1779 }
1780}
1781
1782
1783// --- MultiTouchMotionAccumulator ---
1784
1785MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
1786 mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false),
1787 mHaveStylus(false) {
1788}
1789
1790MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1791 delete[] mSlots;
1792}
1793
1794void MultiTouchMotionAccumulator::configure(InputDevice* device,
1795 size_t slotCount, bool usingSlotsProtocol) {
1796 mSlotCount = slotCount;
1797 mUsingSlotsProtocol = usingSlotsProtocol;
1798 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1799
1800 delete[] mSlots;
1801 mSlots = new Slot[slotCount];
1802}
1803
1804void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1805 // Unfortunately there is no way to read the initial contents of the slots.
1806 // So when we reset the accumulator, we must assume they are all zeroes.
1807 if (mUsingSlotsProtocol) {
1808 // Query the driver for the current slot index and use it as the initial slot
1809 // before we start reading events from the device. It is possible that the
1810 // current slot index will not be the same as it was when the first event was
1811 // written into the evdev buffer, which means the input mapper could start
1812 // out of sync with the initial state of the events in the evdev buffer.
1813 // In the extremely unlikely case that this happens, the data from
1814 // two slots will be confused until the next ABS_MT_SLOT event is received.
1815 // This can cause the touch point to "jump", but at least there will be
1816 // no stuck touches.
1817 int32_t initialSlot;
1818 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1819 ABS_MT_SLOT, &initialSlot);
1820 if (status) {
1821 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1822 initialSlot = -1;
1823 }
1824 clearSlots(initialSlot);
1825 } else {
1826 clearSlots(-1);
1827 }
1828}
1829
1830void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1831 if (mSlots) {
1832 for (size_t i = 0; i < mSlotCount; i++) {
1833 mSlots[i].clear();
1834 }
1835 }
1836 mCurrentSlot = initialSlot;
1837}
1838
1839void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1840 if (rawEvent->type == EV_ABS) {
1841 bool newSlot = false;
1842 if (mUsingSlotsProtocol) {
1843 if (rawEvent->code == ABS_MT_SLOT) {
1844 mCurrentSlot = rawEvent->value;
1845 newSlot = true;
1846 }
1847 } else if (mCurrentSlot < 0) {
1848 mCurrentSlot = 0;
1849 }
1850
1851 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1852#if DEBUG_POINTERS
1853 if (newSlot) {
1854 ALOGW("MultiTouch device emitted invalid slot index %d but it "
1855 "should be between 0 and %d; ignoring this slot.",
1856 mCurrentSlot, mSlotCount - 1);
1857 }
1858#endif
1859 } else {
1860 Slot* slot = &mSlots[mCurrentSlot];
1861
1862 switch (rawEvent->code) {
1863 case ABS_MT_POSITION_X:
1864 slot->mInUse = true;
1865 slot->mAbsMTPositionX = rawEvent->value;
1866 break;
1867 case ABS_MT_POSITION_Y:
1868 slot->mInUse = true;
1869 slot->mAbsMTPositionY = rawEvent->value;
1870 break;
1871 case ABS_MT_TOUCH_MAJOR:
1872 slot->mInUse = true;
1873 slot->mAbsMTTouchMajor = rawEvent->value;
1874 break;
1875 case ABS_MT_TOUCH_MINOR:
1876 slot->mInUse = true;
1877 slot->mAbsMTTouchMinor = rawEvent->value;
1878 slot->mHaveAbsMTTouchMinor = true;
1879 break;
1880 case ABS_MT_WIDTH_MAJOR:
1881 slot->mInUse = true;
1882 slot->mAbsMTWidthMajor = rawEvent->value;
1883 break;
1884 case ABS_MT_WIDTH_MINOR:
1885 slot->mInUse = true;
1886 slot->mAbsMTWidthMinor = rawEvent->value;
1887 slot->mHaveAbsMTWidthMinor = true;
1888 break;
1889 case ABS_MT_ORIENTATION:
1890 slot->mInUse = true;
1891 slot->mAbsMTOrientation = rawEvent->value;
1892 break;
1893 case ABS_MT_TRACKING_ID:
1894 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1895 // The slot is no longer in use but it retains its previous contents,
1896 // which may be reused for subsequent touches.
1897 slot->mInUse = false;
1898 } else {
1899 slot->mInUse = true;
1900 slot->mAbsMTTrackingId = rawEvent->value;
1901 }
1902 break;
1903 case ABS_MT_PRESSURE:
1904 slot->mInUse = true;
1905 slot->mAbsMTPressure = rawEvent->value;
1906 break;
1907 case ABS_MT_DISTANCE:
1908 slot->mInUse = true;
1909 slot->mAbsMTDistance = rawEvent->value;
1910 break;
1911 case ABS_MT_TOOL_TYPE:
1912 slot->mInUse = true;
1913 slot->mAbsMTToolType = rawEvent->value;
1914 slot->mHaveAbsMTToolType = true;
1915 break;
1916 }
1917 }
1918 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1919 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1920 mCurrentSlot += 1;
1921 }
1922}
1923
1924void MultiTouchMotionAccumulator::finishSync() {
1925 if (!mUsingSlotsProtocol) {
1926 clearSlots(-1);
1927 }
1928}
1929
1930bool MultiTouchMotionAccumulator::hasStylus() const {
1931 return mHaveStylus;
1932}
1933
1934
1935// --- MultiTouchMotionAccumulator::Slot ---
1936
1937MultiTouchMotionAccumulator::Slot::Slot() {
1938 clear();
1939}
1940
1941void MultiTouchMotionAccumulator::Slot::clear() {
1942 mInUse = false;
1943 mHaveAbsMTTouchMinor = false;
1944 mHaveAbsMTWidthMinor = false;
1945 mHaveAbsMTToolType = false;
1946 mAbsMTPositionX = 0;
1947 mAbsMTPositionY = 0;
1948 mAbsMTTouchMajor = 0;
1949 mAbsMTTouchMinor = 0;
1950 mAbsMTWidthMajor = 0;
1951 mAbsMTWidthMinor = 0;
1952 mAbsMTOrientation = 0;
1953 mAbsMTTrackingId = -1;
1954 mAbsMTPressure = 0;
1955 mAbsMTDistance = 0;
1956 mAbsMTToolType = 0;
1957}
1958
1959int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1960 if (mHaveAbsMTToolType) {
1961 switch (mAbsMTToolType) {
1962 case MT_TOOL_FINGER:
1963 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1964 case MT_TOOL_PEN:
1965 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1966 }
1967 }
1968 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1969}
1970
1971
1972// --- InputMapper ---
1973
1974InputMapper::InputMapper(InputDevice* device) :
1975 mDevice(device), mContext(device->getContext()) {
1976}
1977
1978InputMapper::~InputMapper() {
1979}
1980
1981void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1982 info->addSource(getSources());
1983}
1984
1985void InputMapper::dump(String8& dump) {
1986}
1987
1988void InputMapper::configure(nsecs_t when,
1989 const InputReaderConfiguration* config, uint32_t changes) {
1990}
1991
1992void InputMapper::reset(nsecs_t when) {
1993}
1994
1995void InputMapper::timeoutExpired(nsecs_t when) {
1996}
1997
1998int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1999 return AKEY_STATE_UNKNOWN;
2000}
2001
2002int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2003 return AKEY_STATE_UNKNOWN;
2004}
2005
2006int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2007 return AKEY_STATE_UNKNOWN;
2008}
2009
2010bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2011 const int32_t* keyCodes, uint8_t* outFlags) {
2012 return false;
2013}
2014
2015void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2016 int32_t token) {
2017}
2018
2019void InputMapper::cancelVibrate(int32_t token) {
2020}
2021
Jeff Brownc9aa6282015-02-11 19:03:28 -08002022void InputMapper::cancelTouch(nsecs_t when) {
2023}
2024
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025int32_t InputMapper::getMetaState() {
2026 return 0;
2027}
2028
Andrii Kulian763a3a42016-03-08 10:46:16 -08002029void InputMapper::updateMetaState(int32_t keyCode) {
2030}
2031
Michael Wright842500e2015-03-13 17:32:02 -07002032void InputMapper::updateExternalStylusState(const StylusState& state) {
2033
2034}
2035
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036void InputMapper::fadePointer() {
2037}
2038
2039status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2040 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2041}
2042
2043void InputMapper::bumpGeneration() {
2044 mDevice->bumpGeneration();
2045}
2046
2047void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
2048 const RawAbsoluteAxisInfo& axis, const char* name) {
2049 if (axis.valid) {
2050 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
2051 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2052 } else {
2053 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
2054 }
2055}
2056
Michael Wright842500e2015-03-13 17:32:02 -07002057void InputMapper::dumpStylusState(String8& dump, const StylusState& state) {
2058 dump.appendFormat(INDENT4 "When: %" PRId64 "\n", state.when);
2059 dump.appendFormat(INDENT4 "Pressure: %f\n", state.pressure);
2060 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", state.buttons);
2061 dump.appendFormat(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
2062}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063
2064// --- SwitchInputMapper ---
2065
2066SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002067 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068}
2069
2070SwitchInputMapper::~SwitchInputMapper() {
2071}
2072
2073uint32_t SwitchInputMapper::getSources() {
2074 return AINPUT_SOURCE_SWITCH;
2075}
2076
2077void SwitchInputMapper::process(const RawEvent* rawEvent) {
2078 switch (rawEvent->type) {
2079 case EV_SW:
2080 processSwitch(rawEvent->code, rawEvent->value);
2081 break;
2082
2083 case EV_SYN:
2084 if (rawEvent->code == SYN_REPORT) {
2085 sync(rawEvent->when);
2086 }
2087 }
2088}
2089
2090void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2091 if (switchCode >= 0 && switchCode < 32) {
2092 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002093 mSwitchValues |= 1 << switchCode;
2094 } else {
2095 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 }
2097 mUpdatedSwitchMask |= 1 << switchCode;
2098 }
2099}
2100
2101void SwitchInputMapper::sync(nsecs_t when) {
2102 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002103 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002104 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 getListener()->notifySwitch(&args);
2106
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107 mUpdatedSwitchMask = 0;
2108 }
2109}
2110
2111int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2112 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2113}
2114
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002115void SwitchInputMapper::dump(String8& dump) {
2116 dump.append(INDENT2 "Switch Input Mapper:\n");
2117 dump.appendFormat(INDENT3 "SwitchValues: %x\n", mSwitchValues);
2118}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002119
2120// --- VibratorInputMapper ---
2121
2122VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2123 InputMapper(device), mVibrating(false) {
2124}
2125
2126VibratorInputMapper::~VibratorInputMapper() {
2127}
2128
2129uint32_t VibratorInputMapper::getSources() {
2130 return 0;
2131}
2132
2133void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2134 InputMapper::populateDeviceInfo(info);
2135
2136 info->setVibrator(true);
2137}
2138
2139void VibratorInputMapper::process(const RawEvent* rawEvent) {
2140 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2141}
2142
2143void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2144 int32_t token) {
2145#if DEBUG_VIBRATOR
2146 String8 patternStr;
2147 for (size_t i = 0; i < patternSize; i++) {
2148 if (i != 0) {
2149 patternStr.append(", ");
2150 }
2151 patternStr.appendFormat("%lld", pattern[i]);
2152 }
2153 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d",
2154 getDeviceId(), patternStr.string(), repeat, token);
2155#endif
2156
2157 mVibrating = true;
2158 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2159 mPatternSize = patternSize;
2160 mRepeat = repeat;
2161 mToken = token;
2162 mIndex = -1;
2163
2164 nextStep();
2165}
2166
2167void VibratorInputMapper::cancelVibrate(int32_t token) {
2168#if DEBUG_VIBRATOR
2169 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2170#endif
2171
2172 if (mVibrating && mToken == token) {
2173 stopVibrating();
2174 }
2175}
2176
2177void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2178 if (mVibrating) {
2179 if (when >= mNextStepTime) {
2180 nextStep();
2181 } else {
2182 getContext()->requestTimeoutAtTime(mNextStepTime);
2183 }
2184 }
2185}
2186
2187void VibratorInputMapper::nextStep() {
2188 mIndex += 1;
2189 if (size_t(mIndex) >= mPatternSize) {
2190 if (mRepeat < 0) {
2191 // We are done.
2192 stopVibrating();
2193 return;
2194 }
2195 mIndex = mRepeat;
2196 }
2197
2198 bool vibratorOn = mIndex & 1;
2199 nsecs_t duration = mPattern[mIndex];
2200 if (vibratorOn) {
2201#if DEBUG_VIBRATOR
2202 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld",
2203 getDeviceId(), duration);
2204#endif
2205 getEventHub()->vibrate(getDeviceId(), duration);
2206 } else {
2207#if DEBUG_VIBRATOR
2208 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2209#endif
2210 getEventHub()->cancelVibrate(getDeviceId());
2211 }
2212 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2213 mNextStepTime = now + duration;
2214 getContext()->requestTimeoutAtTime(mNextStepTime);
2215#if DEBUG_VIBRATOR
2216 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2217#endif
2218}
2219
2220void VibratorInputMapper::stopVibrating() {
2221 mVibrating = false;
2222#if DEBUG_VIBRATOR
2223 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2224#endif
2225 getEventHub()->cancelVibrate(getDeviceId());
2226}
2227
2228void VibratorInputMapper::dump(String8& dump) {
2229 dump.append(INDENT2 "Vibrator Input Mapper:\n");
2230 dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating));
2231}
2232
2233
2234// --- KeyboardInputMapper ---
2235
2236KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2237 uint32_t source, int32_t keyboardType) :
2238 InputMapper(device), mSource(source),
2239 mKeyboardType(keyboardType) {
2240}
2241
2242KeyboardInputMapper::~KeyboardInputMapper() {
2243}
2244
2245uint32_t KeyboardInputMapper::getSources() {
2246 return mSource;
2247}
2248
2249void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2250 InputMapper::populateDeviceInfo(info);
2251
2252 info->setKeyboardType(mKeyboardType);
2253 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2254}
2255
2256void KeyboardInputMapper::dump(String8& dump) {
2257 dump.append(INDENT2 "Keyboard Input Mapper:\n");
2258 dumpParameters(dump);
2259 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
2260 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07002261 dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState);
Siarhei Vishniakoud65d1f72017-11-01 16:32:14 -07002263 dump.appendFormat(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264}
2265
2266
2267void KeyboardInputMapper::configure(nsecs_t when,
2268 const InputReaderConfiguration* config, uint32_t changes) {
2269 InputMapper::configure(when, config, changes);
2270
2271 if (!changes) { // first time only
2272 // Configure basic parameters.
2273 configureParameters();
2274 }
2275
2276 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2277 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2278 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002279 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 mOrientation = v.orientation;
2281 } else {
2282 mOrientation = DISPLAY_ORIENTATION_0;
2283 }
2284 } else {
2285 mOrientation = DISPLAY_ORIENTATION_0;
2286 }
2287 }
2288}
2289
Ivan Podogovb9afef32017-02-13 15:34:32 +00002290static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2291 int32_t mapped = 0;
2292 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2293 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2294 if (stemKeyRotationMap[i][0] == keyCode) {
2295 stemKeyRotationMap[i][1] = mapped;
2296 return;
2297 }
2298 }
2299 }
2300}
2301
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302void KeyboardInputMapper::configureParameters() {
2303 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002304 const PropertyMap& config = getDevice()->getConfiguration();
2305 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 mParameters.orientationAware);
2307
2308 mParameters.hasAssociatedDisplay = false;
2309 if (mParameters.orientationAware) {
2310 mParameters.hasAssociatedDisplay = true;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002311
2312 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2313 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2314 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2315 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002317
2318 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002319 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002320 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321}
2322
2323void KeyboardInputMapper::dumpParameters(String8& dump) {
2324 dump.append(INDENT3 "Parameters:\n");
2325 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2326 toString(mParameters.hasAssociatedDisplay));
2327 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2328 toString(mParameters.orientationAware));
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002329 dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n",
2330 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331}
2332
2333void KeyboardInputMapper::reset(nsecs_t when) {
2334 mMetaState = AMETA_NONE;
2335 mDownTime = 0;
2336 mKeyDowns.clear();
2337 mCurrentHidUsage = 0;
2338
2339 resetLedState();
2340
2341 InputMapper::reset(when);
2342}
2343
2344void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2345 switch (rawEvent->type) {
2346 case EV_KEY: {
2347 int32_t scanCode = rawEvent->code;
2348 int32_t usageCode = mCurrentHidUsage;
2349 mCurrentHidUsage = 0;
2350
2351 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002352 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002353 }
2354 break;
2355 }
2356 case EV_MSC: {
2357 if (rawEvent->code == MSC_SCAN) {
2358 mCurrentHidUsage = rawEvent->value;
2359 }
2360 break;
2361 }
2362 case EV_SYN: {
2363 if (rawEvent->code == SYN_REPORT) {
2364 mCurrentHidUsage = 0;
2365 }
2366 }
2367 }
2368}
2369
2370bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2371 return scanCode < BTN_MOUSE
2372 || scanCode >= KEY_OK
2373 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2374 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2375}
2376
Michael Wright58ba9882017-07-26 16:19:11 +01002377bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2378 switch (keyCode) {
2379 case AKEYCODE_MEDIA_PLAY:
2380 case AKEYCODE_MEDIA_PAUSE:
2381 case AKEYCODE_MEDIA_PLAY_PAUSE:
2382 case AKEYCODE_MUTE:
2383 case AKEYCODE_HEADSETHOOK:
2384 case AKEYCODE_MEDIA_STOP:
2385 case AKEYCODE_MEDIA_NEXT:
2386 case AKEYCODE_MEDIA_PREVIOUS:
2387 case AKEYCODE_MEDIA_REWIND:
2388 case AKEYCODE_MEDIA_RECORD:
2389 case AKEYCODE_MEDIA_FAST_FORWARD:
2390 case AKEYCODE_MEDIA_SKIP_FORWARD:
2391 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2392 case AKEYCODE_MEDIA_STEP_FORWARD:
2393 case AKEYCODE_MEDIA_STEP_BACKWARD:
2394 case AKEYCODE_MEDIA_AUDIO_TRACK:
2395 case AKEYCODE_VOLUME_UP:
2396 case AKEYCODE_VOLUME_DOWN:
2397 case AKEYCODE_VOLUME_MUTE:
2398 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2399 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2400 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2401 return true;
2402 }
2403 return false;
2404}
2405
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002406void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2407 int32_t usageCode) {
2408 int32_t keyCode;
2409 int32_t keyMetaState;
2410 uint32_t policyFlags;
2411
2412 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2413 &keyCode, &keyMetaState, &policyFlags)) {
2414 keyCode = AKEYCODE_UNKNOWN;
2415 keyMetaState = mMetaState;
2416 policyFlags = 0;
2417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002418
2419 if (down) {
2420 // Rotate key codes according to orientation if needed.
2421 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2422 keyCode = rotateKeyCode(keyCode, mOrientation);
2423 }
2424
2425 // Add key down.
2426 ssize_t keyDownIndex = findKeyDown(scanCode);
2427 if (keyDownIndex >= 0) {
2428 // key repeat, be sure to use same keycode as before in case of rotation
2429 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2430 } else {
2431 // key down
2432 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2433 && mContext->shouldDropVirtualKey(when,
2434 getDevice(), keyCode, scanCode)) {
2435 return;
2436 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002437 if (policyFlags & POLICY_FLAG_GESTURE) {
2438 mDevice->cancelTouch(when);
2439 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440
2441 mKeyDowns.push();
2442 KeyDown& keyDown = mKeyDowns.editTop();
2443 keyDown.keyCode = keyCode;
2444 keyDown.scanCode = scanCode;
2445 }
2446
2447 mDownTime = when;
2448 } else {
2449 // Remove key down.
2450 ssize_t keyDownIndex = findKeyDown(scanCode);
2451 if (keyDownIndex >= 0) {
2452 // key up, be sure to use same keycode as before in case of rotation
2453 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2454 mKeyDowns.removeAt(size_t(keyDownIndex));
2455 } else {
2456 // key was not actually down
2457 ALOGI("Dropping key up from device %s because the key was not down. "
2458 "keyCode=%d, scanCode=%d",
2459 getDeviceName().string(), keyCode, scanCode);
2460 return;
2461 }
2462 }
2463
Andrii Kulian763a3a42016-03-08 10:46:16 -08002464 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002465 // If global meta state changed send it along with the key.
2466 // If it has not changed then we'll use what keymap gave us,
2467 // since key replacement logic might temporarily reset a few
2468 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002469 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 }
2471
2472 nsecs_t downTime = mDownTime;
2473
2474 // Key down on external an keyboard should wake the device.
2475 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2476 // For internal keyboards, the key layout file should specify the policy flags for
2477 // each wake key individually.
2478 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002479 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002480 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481 }
2482
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002483 if (mParameters.handlesKeyRepeat) {
2484 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2485 }
2486
Michael Wrightd02c5b62014-02-10 15:10:22 -08002487 NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,
2488 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002489 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490 getListener()->notifyKey(&args);
2491}
2492
2493ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2494 size_t n = mKeyDowns.size();
2495 for (size_t i = 0; i < n; i++) {
2496 if (mKeyDowns[i].scanCode == scanCode) {
2497 return i;
2498 }
2499 }
2500 return -1;
2501}
2502
2503int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2504 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2505}
2506
2507int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2508 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2509}
2510
2511bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2512 const int32_t* keyCodes, uint8_t* outFlags) {
2513 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2514}
2515
2516int32_t KeyboardInputMapper::getMetaState() {
2517 return mMetaState;
2518}
2519
Andrii Kulian763a3a42016-03-08 10:46:16 -08002520void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2521 updateMetaStateIfNeeded(keyCode, false);
2522}
2523
2524bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2525 int32_t oldMetaState = mMetaState;
2526 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2527 bool metaStateChanged = oldMetaState != newMetaState;
2528 if (metaStateChanged) {
2529 mMetaState = newMetaState;
2530 updateLedState(false);
2531
2532 getContext()->updateGlobalMetaState();
2533 }
2534
2535 return metaStateChanged;
2536}
2537
Michael Wrightd02c5b62014-02-10 15:10:22 -08002538void KeyboardInputMapper::resetLedState() {
2539 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2540 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2541 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2542
2543 updateLedState(true);
2544}
2545
2546void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2547 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2548 ledState.on = false;
2549}
2550
2551void KeyboardInputMapper::updateLedState(bool reset) {
2552 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2553 AMETA_CAPS_LOCK_ON, reset);
2554 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2555 AMETA_NUM_LOCK_ON, reset);
2556 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2557 AMETA_SCROLL_LOCK_ON, reset);
2558}
2559
2560void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2561 int32_t led, int32_t modifier, bool reset) {
2562 if (ledState.avail) {
2563 bool desiredState = (mMetaState & modifier) != 0;
2564 if (reset || ledState.on != desiredState) {
2565 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2566 ledState.on = desiredState;
2567 }
2568 }
2569}
2570
2571
2572// --- CursorInputMapper ---
2573
2574CursorInputMapper::CursorInputMapper(InputDevice* device) :
2575 InputMapper(device) {
2576}
2577
2578CursorInputMapper::~CursorInputMapper() {
2579}
2580
2581uint32_t CursorInputMapper::getSources() {
2582 return mSource;
2583}
2584
2585void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2586 InputMapper::populateDeviceInfo(info);
2587
2588 if (mParameters.mode == Parameters::MODE_POINTER) {
2589 float minX, minY, maxX, maxY;
2590 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2591 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2592 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2593 }
2594 } else {
2595 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2596 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2597 }
2598 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2599
2600 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2601 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2602 }
2603 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2604 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2605 }
2606}
2607
2608void CursorInputMapper::dump(String8& dump) {
2609 dump.append(INDENT2 "Cursor Input Mapper:\n");
2610 dumpParameters(dump);
2611 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
2612 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
2613 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2614 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2615 dump.appendFormat(INDENT3 "HaveVWheel: %s\n",
2616 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
2617 dump.appendFormat(INDENT3 "HaveHWheel: %s\n",
2618 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
2619 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2620 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2621 dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation);
2622 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2623 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
Siarhei Vishniakoud65d1f72017-11-01 16:32:14 -07002624 dump.appendFormat(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625}
2626
2627void CursorInputMapper::configure(nsecs_t when,
2628 const InputReaderConfiguration* config, uint32_t changes) {
2629 InputMapper::configure(when, config, changes);
2630
2631 if (!changes) { // first time only
2632 mCursorScrollAccumulator.configure(getDevice());
2633
2634 // Configure basic parameters.
2635 configureParameters();
2636
2637 // Configure device mode.
2638 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002639 case Parameters::MODE_POINTER_RELATIVE:
2640 // Should not happen during first time configuration.
2641 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2642 mParameters.mode = Parameters::MODE_POINTER;
2643 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002644 case Parameters::MODE_POINTER:
2645 mSource = AINPUT_SOURCE_MOUSE;
2646 mXPrecision = 1.0f;
2647 mYPrecision = 1.0f;
2648 mXScale = 1.0f;
2649 mYScale = 1.0f;
2650 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2651 break;
2652 case Parameters::MODE_NAVIGATION:
2653 mSource = AINPUT_SOURCE_TRACKBALL;
2654 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2655 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2656 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2657 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2658 break;
2659 }
2660
2661 mVWheelScale = 1.0f;
2662 mHWheelScale = 1.0f;
2663 }
2664
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002665 if ((!changes && config->pointerCapture)
2666 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2667 if (config->pointerCapture) {
2668 if (mParameters.mode == Parameters::MODE_POINTER) {
2669 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2670 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2671 // Keep PointerController around in order to preserve the pointer position.
2672 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2673 } else {
2674 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2675 }
2676 } else {
2677 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2678 mParameters.mode = Parameters::MODE_POINTER;
2679 mSource = AINPUT_SOURCE_MOUSE;
2680 } else {
2681 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2682 }
2683 }
2684 bumpGeneration();
2685 if (changes) {
2686 getDevice()->notifyReset(when);
2687 }
2688 }
2689
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2691 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2692 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2693 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2694 }
2695
2696 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
2697 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2698 DisplayViewport v;
Santos Cordonfa5cf462017-04-05 10:37:00 -07002699 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 mOrientation = v.orientation;
2701 } else {
2702 mOrientation = DISPLAY_ORIENTATION_0;
2703 }
2704 } else {
2705 mOrientation = DISPLAY_ORIENTATION_0;
2706 }
2707 bumpGeneration();
2708 }
2709}
2710
2711void CursorInputMapper::configureParameters() {
2712 mParameters.mode = Parameters::MODE_POINTER;
2713 String8 cursorModeString;
2714 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2715 if (cursorModeString == "navigation") {
2716 mParameters.mode = Parameters::MODE_NAVIGATION;
2717 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2718 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2719 }
2720 }
2721
2722 mParameters.orientationAware = false;
2723 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2724 mParameters.orientationAware);
2725
2726 mParameters.hasAssociatedDisplay = false;
2727 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2728 mParameters.hasAssociatedDisplay = true;
2729 }
2730}
2731
2732void CursorInputMapper::dumpParameters(String8& dump) {
2733 dump.append(INDENT3 "Parameters:\n");
2734 dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n",
2735 toString(mParameters.hasAssociatedDisplay));
2736
2737 switch (mParameters.mode) {
2738 case Parameters::MODE_POINTER:
2739 dump.append(INDENT4 "Mode: pointer\n");
2740 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002741 case Parameters::MODE_POINTER_RELATIVE:
2742 dump.append(INDENT4 "Mode: relative pointer\n");
2743 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 case Parameters::MODE_NAVIGATION:
2745 dump.append(INDENT4 "Mode: navigation\n");
2746 break;
2747 default:
2748 ALOG_ASSERT(false);
2749 }
2750
2751 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2752 toString(mParameters.orientationAware));
2753}
2754
2755void CursorInputMapper::reset(nsecs_t when) {
2756 mButtonState = 0;
2757 mDownTime = 0;
2758
2759 mPointerVelocityControl.reset();
2760 mWheelXVelocityControl.reset();
2761 mWheelYVelocityControl.reset();
2762
2763 mCursorButtonAccumulator.reset(getDevice());
2764 mCursorMotionAccumulator.reset(getDevice());
2765 mCursorScrollAccumulator.reset(getDevice());
2766
2767 InputMapper::reset(when);
2768}
2769
2770void CursorInputMapper::process(const RawEvent* rawEvent) {
2771 mCursorButtonAccumulator.process(rawEvent);
2772 mCursorMotionAccumulator.process(rawEvent);
2773 mCursorScrollAccumulator.process(rawEvent);
2774
2775 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2776 sync(rawEvent->when);
2777 }
2778}
2779
2780void CursorInputMapper::sync(nsecs_t when) {
2781 int32_t lastButtonState = mButtonState;
2782 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2783 mButtonState = currentButtonState;
2784
2785 bool wasDown = isPointerDown(lastButtonState);
2786 bool down = isPointerDown(currentButtonState);
2787 bool downChanged;
2788 if (!wasDown && down) {
2789 mDownTime = when;
2790 downChanged = true;
2791 } else if (wasDown && !down) {
2792 downChanged = true;
2793 } else {
2794 downChanged = false;
2795 }
2796 nsecs_t downTime = mDownTime;
2797 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002798 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2799 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002800
2801 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2802 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2803 bool moved = deltaX != 0 || deltaY != 0;
2804
2805 // Rotate delta according to orientation if needed.
2806 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2807 && (deltaX != 0.0f || deltaY != 0.0f)) {
2808 rotateDelta(mOrientation, &deltaX, &deltaY);
2809 }
2810
2811 // Move the pointer.
2812 PointerProperties pointerProperties;
2813 pointerProperties.clear();
2814 pointerProperties.id = 0;
2815 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2816
2817 PointerCoords pointerCoords;
2818 pointerCoords.clear();
2819
2820 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2821 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2822 bool scrolled = vscroll != 0 || hscroll != 0;
2823
2824 mWheelYVelocityControl.move(when, NULL, &vscroll);
2825 mWheelXVelocityControl.move(when, &hscroll, NULL);
2826
2827 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2828
2829 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002830 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831 if (moved || scrolled || buttonsChanged) {
2832 mPointerController->setPresentation(
2833 PointerControllerInterface::PRESENTATION_POINTER);
2834
2835 if (moved) {
2836 mPointerController->move(deltaX, deltaY);
2837 }
2838
2839 if (buttonsChanged) {
2840 mPointerController->setButtonState(currentButtonState);
2841 }
2842
2843 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2844 }
2845
2846 float x, y;
2847 mPointerController->getPosition(&x, &y);
2848 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2849 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002850 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2851 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002852 displayId = ADISPLAY_ID_DEFAULT;
2853 } else {
2854 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2855 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2856 displayId = ADISPLAY_ID_NONE;
2857 }
2858
2859 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2860
2861 // Moving an external trackball or mouse should wake the device.
2862 // We don't do this for internal cursor devices to prevent them from waking up
2863 // the device in your pocket.
2864 // TODO: Use the input device configuration to control this behavior more finely.
2865 uint32_t policyFlags = 0;
2866 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002867 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 }
2869
2870 // Synthesize key down from buttons if needed.
2871 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
2872 policyFlags, lastButtonState, currentButtonState);
2873
2874 // Send motion event.
2875 if (downChanged || moved || scrolled || buttonsChanged) {
2876 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002877 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878 int32_t motionEventAction;
2879 if (downChanged) {
2880 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002881 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2883 } else {
2884 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2885 }
2886
Michael Wright7b159c92015-05-14 14:48:03 +01002887 if (buttonsReleased) {
2888 BitSet32 released(buttonsReleased);
2889 while (!released.isEmpty()) {
2890 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2891 buttonState &= ~actionButton;
2892 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags,
2893 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2894 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2895 displayId, 1, &pointerProperties, &pointerCoords,
2896 mXPrecision, mYPrecision, downTime);
2897 getListener()->notifyMotion(&releaseArgs);
2898 }
2899 }
2900
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002902 motionEventAction, 0, 0, metaState, currentButtonState,
2903 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002904 displayId, 1, &pointerProperties, &pointerCoords,
2905 mXPrecision, mYPrecision, downTime);
2906 getListener()->notifyMotion(&args);
2907
Michael Wright7b159c92015-05-14 14:48:03 +01002908 if (buttonsPressed) {
2909 BitSet32 pressed(buttonsPressed);
2910 while (!pressed.isEmpty()) {
2911 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2912 buttonState |= actionButton;
2913 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags,
2914 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2915 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2916 displayId, 1, &pointerProperties, &pointerCoords,
2917 mXPrecision, mYPrecision, downTime);
2918 getListener()->notifyMotion(&pressArgs);
2919 }
2920 }
2921
2922 ALOG_ASSERT(buttonState == currentButtonState);
2923
Michael Wrightd02c5b62014-02-10 15:10:22 -08002924 // Send hover move after UP to tell the application that the mouse is hovering now.
2925 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002926 && (mSource == AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002928 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2930 displayId, 1, &pointerProperties, &pointerCoords,
2931 mXPrecision, mYPrecision, downTime);
2932 getListener()->notifyMotion(&hoverArgs);
2933 }
2934
2935 // Send scroll events.
2936 if (scrolled) {
2937 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2938 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2939
2940 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002941 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002942 AMOTION_EVENT_EDGE_FLAG_NONE,
2943 displayId, 1, &pointerProperties, &pointerCoords,
2944 mXPrecision, mYPrecision, downTime);
2945 getListener()->notifyMotion(&scrollArgs);
2946 }
2947 }
2948
2949 // Synthesize key up from buttons if needed.
2950 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
2951 policyFlags, lastButtonState, currentButtonState);
2952
2953 mCursorMotionAccumulator.finishSync();
2954 mCursorScrollAccumulator.finishSync();
2955}
2956
2957int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2958 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2959 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2960 } else {
2961 return AKEY_STATE_UNKNOWN;
2962 }
2963}
2964
2965void CursorInputMapper::fadePointer() {
2966 if (mPointerController != NULL) {
2967 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2968 }
2969}
2970
Prashant Malani1941ff52015-08-11 18:29:28 -07002971// --- RotaryEncoderInputMapper ---
2972
2973RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002974 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002975 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2976}
2977
2978RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2979}
2980
2981uint32_t RotaryEncoderInputMapper::getSources() {
2982 return mSource;
2983}
2984
2985void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2986 InputMapper::populateDeviceInfo(info);
2987
2988 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002989 float res = 0.0f;
2990 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2991 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2992 }
2993 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2994 mScalingFactor)) {
2995 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2996 "default to 1.0!\n");
2997 mScalingFactor = 1.0f;
2998 }
2999 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3000 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003001 }
3002}
3003
3004void RotaryEncoderInputMapper::dump(String8& dump) {
3005 dump.append(INDENT2 "Rotary Encoder Input Mapper:\n");
3006 dump.appendFormat(INDENT3 "HaveWheel: %s\n",
3007 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
3008}
3009
3010void RotaryEncoderInputMapper::configure(nsecs_t when,
3011 const InputReaderConfiguration* config, uint32_t changes) {
3012 InputMapper::configure(when, config, changes);
3013 if (!changes) {
3014 mRotaryEncoderScrollAccumulator.configure(getDevice());
3015 }
Ivan Podogovad437252016-09-29 16:29:55 +01003016 if (!changes || (InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
3017 DisplayViewport v;
3018 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, NULL, &v)) {
3019 mOrientation = v.orientation;
3020 } else {
3021 mOrientation = DISPLAY_ORIENTATION_0;
3022 }
3023 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003024}
3025
3026void RotaryEncoderInputMapper::reset(nsecs_t when) {
3027 mRotaryEncoderScrollAccumulator.reset(getDevice());
3028
3029 InputMapper::reset(when);
3030}
3031
3032void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3033 mRotaryEncoderScrollAccumulator.process(rawEvent);
3034
3035 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3036 sync(rawEvent->when);
3037 }
3038}
3039
3040void RotaryEncoderInputMapper::sync(nsecs_t when) {
3041 PointerCoords pointerCoords;
3042 pointerCoords.clear();
3043
3044 PointerProperties pointerProperties;
3045 pointerProperties.clear();
3046 pointerProperties.id = 0;
3047 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3048
3049 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3050 bool scrolled = scroll != 0;
3051
3052 // This is not a pointer, so it's not associated with a display.
3053 int32_t displayId = ADISPLAY_ID_NONE;
3054
3055 // Moving the rotary encoder should wake the device (if specified).
3056 uint32_t policyFlags = 0;
3057 if (scrolled && getDevice()->isExternal()) {
3058 policyFlags |= POLICY_FLAG_WAKE;
3059 }
3060
Ivan Podogovad437252016-09-29 16:29:55 +01003061 if (mOrientation == DISPLAY_ORIENTATION_180) {
3062 scroll = -scroll;
3063 }
3064
Prashant Malani1941ff52015-08-11 18:29:28 -07003065 // Send motion event.
3066 if (scrolled) {
3067 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003068 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003069
3070 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags,
3071 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3072 AMOTION_EVENT_EDGE_FLAG_NONE,
3073 displayId, 1, &pointerProperties, &pointerCoords,
3074 0, 0, 0);
3075 getListener()->notifyMotion(&scrollArgs);
3076 }
3077
3078 mRotaryEncoderScrollAccumulator.finishSync();
3079}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003080
3081// --- TouchInputMapper ---
3082
3083TouchInputMapper::TouchInputMapper(InputDevice* device) :
3084 InputMapper(device),
3085 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3086 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
3087 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3088}
3089
3090TouchInputMapper::~TouchInputMapper() {
3091}
3092
3093uint32_t TouchInputMapper::getSources() {
3094 return mSource;
3095}
3096
3097void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3098 InputMapper::populateDeviceInfo(info);
3099
3100 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3101 info->addMotionRange(mOrientedRanges.x);
3102 info->addMotionRange(mOrientedRanges.y);
3103 info->addMotionRange(mOrientedRanges.pressure);
3104
3105 if (mOrientedRanges.haveSize) {
3106 info->addMotionRange(mOrientedRanges.size);
3107 }
3108
3109 if (mOrientedRanges.haveTouchSize) {
3110 info->addMotionRange(mOrientedRanges.touchMajor);
3111 info->addMotionRange(mOrientedRanges.touchMinor);
3112 }
3113
3114 if (mOrientedRanges.haveToolSize) {
3115 info->addMotionRange(mOrientedRanges.toolMajor);
3116 info->addMotionRange(mOrientedRanges.toolMinor);
3117 }
3118
3119 if (mOrientedRanges.haveOrientation) {
3120 info->addMotionRange(mOrientedRanges.orientation);
3121 }
3122
3123 if (mOrientedRanges.haveDistance) {
3124 info->addMotionRange(mOrientedRanges.distance);
3125 }
3126
3127 if (mOrientedRanges.haveTilt) {
3128 info->addMotionRange(mOrientedRanges.tilt);
3129 }
3130
3131 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3132 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3133 0.0f);
3134 }
3135 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3136 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3137 0.0f);
3138 }
3139 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3140 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3141 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3142 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3143 x.fuzz, x.resolution);
3144 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3145 y.fuzz, y.resolution);
3146 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3147 x.fuzz, x.resolution);
3148 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3149 y.fuzz, y.resolution);
3150 }
3151 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3152 }
3153}
3154
3155void TouchInputMapper::dump(String8& dump) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003156 dump.appendFormat(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157 dumpParameters(dump);
3158 dumpVirtualKeys(dump);
3159 dumpRawPointerAxes(dump);
3160 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003161 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162 dumpSurface(dump);
3163
3164 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
3165 dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3166 dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3167 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale);
3168 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale);
3169 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3170 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3171 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3172 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3173 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3174 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3175 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3176 dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3177 dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3178 dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3179 dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3180 dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
3181
Michael Wright7b159c92015-05-14 14:48:03 +01003182 dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003184 mLastRawState.rawPointerData.pointerCount);
3185 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3186 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
3188 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3189 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3190 "toolType=%d, isHovering=%s\n", i,
3191 pointer.id, pointer.x, pointer.y, pointer.pressure,
3192 pointer.touchMajor, pointer.touchMinor,
3193 pointer.toolMajor, pointer.toolMinor,
3194 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3195 pointer.toolType, toString(pointer.isHovering));
3196 }
3197
Michael Wright7b159c92015-05-14 14:48:03 +01003198 dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003199 dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003200 mLastCookedState.cookedPointerData.pointerCount);
3201 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3202 const PointerProperties& pointerProperties =
3203 mLastCookedState.cookedPointerData.pointerProperties[i];
3204 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
3206 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3207 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3208 "toolType=%d, isHovering=%s\n", i,
3209 pointerProperties.id,
3210 pointerCoords.getX(),
3211 pointerCoords.getY(),
3212 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3213 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3214 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3215 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3216 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3217 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3218 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3219 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3220 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003221 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 }
3223
Michael Wright842500e2015-03-13 17:32:02 -07003224 dump.append(INDENT3 "Stylus Fusion:\n");
3225 dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n",
3226 toString(mExternalStylusConnected));
3227 dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3228 dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003229 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07003230 dump.append(INDENT3 "External Stylus State:\n");
3231 dumpStylusState(dump, mExternalStylusState);
3232
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 if (mDeviceMode == DEVICE_MODE_POINTER) {
3234 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
3235 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
3236 mPointerXMovementScale);
3237 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
3238 mPointerYMovementScale);
3239 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
3240 mPointerXZoomScale);
3241 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
3242 mPointerYZoomScale);
3243 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
3244 mPointerGestureMaxSwipeWidth);
3245 }
3246}
3247
Santos Cordonfa5cf462017-04-05 10:37:00 -07003248const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3249 switch (deviceMode) {
3250 case DEVICE_MODE_DISABLED:
3251 return "disabled";
3252 case DEVICE_MODE_DIRECT:
3253 return "direct";
3254 case DEVICE_MODE_UNSCALED:
3255 return "unscaled";
3256 case DEVICE_MODE_NAVIGATION:
3257 return "navigation";
3258 case DEVICE_MODE_POINTER:
3259 return "pointer";
3260 }
3261 return "unknown";
3262}
3263
Michael Wrightd02c5b62014-02-10 15:10:22 -08003264void TouchInputMapper::configure(nsecs_t when,
3265 const InputReaderConfiguration* config, uint32_t changes) {
3266 InputMapper::configure(when, config, changes);
3267
3268 mConfig = *config;
3269
3270 if (!changes) { // first time only
3271 // Configure basic parameters.
3272 configureParameters();
3273
3274 // Configure common accumulators.
3275 mCursorScrollAccumulator.configure(getDevice());
3276 mTouchButtonAccumulator.configure(getDevice());
3277
3278 // Configure absolute axis information.
3279 configureRawPointerAxes();
3280
3281 // Prepare input device calibration.
3282 parseCalibration();
3283 resolveCalibration();
3284 }
3285
Michael Wright842500e2015-03-13 17:32:02 -07003286 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003287 // Update location calibration to reflect current settings
3288 updateAffineTransformation();
3289 }
3290
Michael Wrightd02c5b62014-02-10 15:10:22 -08003291 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3292 // Update pointer speed.
3293 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3294 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3295 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3296 }
3297
3298 bool resetNeeded = false;
3299 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3300 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003301 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3302 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303 // Configure device sources, surface dimensions, orientation and
3304 // scaling factors.
3305 configureSurface(when, &resetNeeded);
3306 }
3307
3308 if (changes && resetNeeded) {
3309 // Send reset, unless this is the first time the device has been configured,
3310 // in which case the reader will call reset itself after all mappers are ready.
3311 getDevice()->notifyReset(when);
3312 }
3313}
3314
Michael Wright842500e2015-03-13 17:32:02 -07003315void TouchInputMapper::resolveExternalStylusPresence() {
3316 Vector<InputDeviceInfo> devices;
3317 mContext->getExternalStylusDevices(devices);
3318 mExternalStylusConnected = !devices.isEmpty();
3319
3320 if (!mExternalStylusConnected) {
3321 resetExternalStylus();
3322 }
3323}
3324
Michael Wrightd02c5b62014-02-10 15:10:22 -08003325void TouchInputMapper::configureParameters() {
3326 // Use the pointer presentation mode for devices that do not support distinct
3327 // multitouch. The spot-based presentation relies on being able to accurately
3328 // locate two or more fingers on the touch pad.
3329 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003330 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331
3332 String8 gestureModeString;
3333 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3334 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003335 if (gestureModeString == "single-touch") {
3336 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3337 } else if (gestureModeString == "multi-touch") {
3338 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 } else if (gestureModeString != "default") {
3340 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3341 }
3342 }
3343
3344 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3345 // The device is a touch screen.
3346 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3347 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3348 // The device is a pointing device like a track pad.
3349 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3350 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3351 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3352 // The device is a cursor device with a touch pad attached.
3353 // By default don't use the touch pad to move the pointer.
3354 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3355 } else {
3356 // The device is a touch pad of unknown purpose.
3357 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3358 }
3359
3360 mParameters.hasButtonUnderPad=
3361 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3362
3363 String8 deviceTypeString;
3364 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3365 deviceTypeString)) {
3366 if (deviceTypeString == "touchScreen") {
3367 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3368 } else if (deviceTypeString == "touchPad") {
3369 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3370 } else if (deviceTypeString == "touchNavigation") {
3371 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3372 } else if (deviceTypeString == "pointer") {
3373 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3374 } else if (deviceTypeString != "default") {
3375 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3376 }
3377 }
3378
3379 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3380 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3381 mParameters.orientationAware);
3382
3383 mParameters.hasAssociatedDisplay = false;
3384 mParameters.associatedDisplayIsExternal = false;
3385 if (mParameters.orientationAware
3386 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3387 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3388 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003389 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3390 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3391 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3392 mParameters.uniqueDisplayId);
3393 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003395
3396 // Initial downs on external touch devices should wake the device.
3397 // Normally we don't do this for internal touch screens to prevent them from waking
3398 // up in your pocket but you can enable it using the input device configuration.
3399 mParameters.wake = getDevice()->isExternal();
3400 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3401 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402}
3403
3404void TouchInputMapper::dumpParameters(String8& dump) {
3405 dump.append(INDENT3 "Parameters:\n");
3406
3407 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003408 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3409 dump.append(INDENT4 "GestureMode: single-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003411 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3412 dump.append(INDENT4 "GestureMode: multi-touch\n");
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 break;
3414 default:
3415 assert(false);
3416 }
3417
3418 switch (mParameters.deviceType) {
3419 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3420 dump.append(INDENT4 "DeviceType: touchScreen\n");
3421 break;
3422 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3423 dump.append(INDENT4 "DeviceType: touchPad\n");
3424 break;
3425 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3426 dump.append(INDENT4 "DeviceType: touchNavigation\n");
3427 break;
3428 case Parameters::DEVICE_TYPE_POINTER:
3429 dump.append(INDENT4 "DeviceType: pointer\n");
3430 break;
3431 default:
3432 ALOG_ASSERT(false);
3433 }
3434
Santos Cordonfa5cf462017-04-05 10:37:00 -07003435 dump.appendFormat(
3436 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003438 toString(mParameters.associatedDisplayIsExternal),
3439 mParameters.uniqueDisplayId.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
3441 toString(mParameters.orientationAware));
3442}
3443
3444void TouchInputMapper::configureRawPointerAxes() {
3445 mRawPointerAxes.clear();
3446}
3447
3448void TouchInputMapper::dumpRawPointerAxes(String8& dump) {
3449 dump.append(INDENT3 "Raw Touch Axes:\n");
3450 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3451 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3452 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3453 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3454 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3455 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3456 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3457 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3458 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3459 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3460 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3461 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3462 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3463}
3464
Michael Wright842500e2015-03-13 17:32:02 -07003465bool TouchInputMapper::hasExternalStylus() const {
3466 return mExternalStylusConnected;
3467}
3468
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3470 int32_t oldDeviceMode = mDeviceMode;
3471
Michael Wright842500e2015-03-13 17:32:02 -07003472 resolveExternalStylusPresence();
3473
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 // Determine device mode.
3475 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3476 && mConfig.pointerGesturesEnabled) {
3477 mSource = AINPUT_SOURCE_MOUSE;
3478 mDeviceMode = DEVICE_MODE_POINTER;
3479 if (hasStylus()) {
3480 mSource |= AINPUT_SOURCE_STYLUS;
3481 }
3482 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3483 && mParameters.hasAssociatedDisplay) {
3484 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3485 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003486 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487 mSource |= AINPUT_SOURCE_STYLUS;
3488 }
Michael Wright2f78b682015-06-12 15:25:08 +01003489 if (hasExternalStylus()) {
3490 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3491 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3493 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3494 mDeviceMode = DEVICE_MODE_NAVIGATION;
3495 } else {
3496 mSource = AINPUT_SOURCE_TOUCHPAD;
3497 mDeviceMode = DEVICE_MODE_UNSCALED;
3498 }
3499
3500 // Ensure we have valid X and Y axes.
3501 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3502 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3503 "The device will be inoperable.", getDeviceName().string());
3504 mDeviceMode = DEVICE_MODE_DISABLED;
3505 return;
3506 }
3507
3508 // Raw width and height in the natural orientation.
3509 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3510 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3511
3512 // Get associated display dimensions.
3513 DisplayViewport newViewport;
3514 if (mParameters.hasAssociatedDisplay) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003515 const String8* uniqueDisplayId = NULL;
3516 ViewportType viewportTypeToUse;
3517
3518 if (mParameters.associatedDisplayIsExternal) {
3519 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3520 } else if (!mParameters.uniqueDisplayId.isEmpty()) {
3521 // If the IDC file specified a unique display Id, then it expects to be linked to a
3522 // virtual display with the same unique ID.
3523 uniqueDisplayId = &mParameters.uniqueDisplayId;
3524 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3525 } else {
3526 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3527 }
3528
3529 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3531 "display. The device will be inoperable until the display size "
3532 "becomes available.",
3533 getDeviceName().string());
3534 mDeviceMode = DEVICE_MODE_DISABLED;
3535 return;
3536 }
3537 } else {
3538 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3539 }
3540 bool viewportChanged = mViewport != newViewport;
3541 if (viewportChanged) {
3542 mViewport = newViewport;
3543
3544 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3545 // Convert rotated viewport to natural surface coordinates.
3546 int32_t naturalLogicalWidth, naturalLogicalHeight;
3547 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3548 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3549 int32_t naturalDeviceWidth, naturalDeviceHeight;
3550 switch (mViewport.orientation) {
3551 case DISPLAY_ORIENTATION_90:
3552 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3553 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3554 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3555 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3556 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3557 naturalPhysicalTop = mViewport.physicalLeft;
3558 naturalDeviceWidth = mViewport.deviceHeight;
3559 naturalDeviceHeight = mViewport.deviceWidth;
3560 break;
3561 case DISPLAY_ORIENTATION_180:
3562 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3563 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3564 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3565 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3566 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3567 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3568 naturalDeviceWidth = mViewport.deviceWidth;
3569 naturalDeviceHeight = mViewport.deviceHeight;
3570 break;
3571 case DISPLAY_ORIENTATION_270:
3572 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3573 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3574 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3575 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3576 naturalPhysicalLeft = mViewport.physicalTop;
3577 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3578 naturalDeviceWidth = mViewport.deviceHeight;
3579 naturalDeviceHeight = mViewport.deviceWidth;
3580 break;
3581 case DISPLAY_ORIENTATION_0:
3582 default:
3583 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3584 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3585 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3586 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3587 naturalPhysicalLeft = mViewport.physicalLeft;
3588 naturalPhysicalTop = mViewport.physicalTop;
3589 naturalDeviceWidth = mViewport.deviceWidth;
3590 naturalDeviceHeight = mViewport.deviceHeight;
3591 break;
3592 }
3593
3594 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3595 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3596 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3597 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3598
3599 mSurfaceOrientation = mParameters.orientationAware ?
3600 mViewport.orientation : DISPLAY_ORIENTATION_0;
3601 } else {
3602 mSurfaceWidth = rawWidth;
3603 mSurfaceHeight = rawHeight;
3604 mSurfaceLeft = 0;
3605 mSurfaceTop = 0;
3606 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3607 }
3608 }
3609
3610 // If moving between pointer modes, need to reset some state.
3611 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3612 if (deviceModeChanged) {
3613 mOrientedRanges.clear();
3614 }
3615
3616 // Create pointer controller if needed.
3617 if (mDeviceMode == DEVICE_MODE_POINTER ||
3618 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
3619 if (mPointerController == NULL) {
3620 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3621 }
3622 } else {
3623 mPointerController.clear();
3624 }
3625
3626 if (viewportChanged || deviceModeChanged) {
3627 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3628 "display id %d",
3629 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3630 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3631
3632 // Configure X and Y factors.
3633 mXScale = float(mSurfaceWidth) / rawWidth;
3634 mYScale = float(mSurfaceHeight) / rawHeight;
3635 mXTranslate = -mSurfaceLeft;
3636 mYTranslate = -mSurfaceTop;
3637 mXPrecision = 1.0f / mXScale;
3638 mYPrecision = 1.0f / mYScale;
3639
3640 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3641 mOrientedRanges.x.source = mSource;
3642 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3643 mOrientedRanges.y.source = mSource;
3644
3645 configureVirtualKeys();
3646
3647 // Scale factor for terms that are not oriented in a particular axis.
3648 // If the pixels are square then xScale == yScale otherwise we fake it
3649 // by choosing an average.
3650 mGeometricScale = avg(mXScale, mYScale);
3651
3652 // Size of diagonal axis.
3653 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3654
3655 // Size factors.
3656 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3657 if (mRawPointerAxes.touchMajor.valid
3658 && mRawPointerAxes.touchMajor.maxValue != 0) {
3659 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3660 } else if (mRawPointerAxes.toolMajor.valid
3661 && mRawPointerAxes.toolMajor.maxValue != 0) {
3662 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3663 } else {
3664 mSizeScale = 0.0f;
3665 }
3666
3667 mOrientedRanges.haveTouchSize = true;
3668 mOrientedRanges.haveToolSize = true;
3669 mOrientedRanges.haveSize = true;
3670
3671 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3672 mOrientedRanges.touchMajor.source = mSource;
3673 mOrientedRanges.touchMajor.min = 0;
3674 mOrientedRanges.touchMajor.max = diagonalSize;
3675 mOrientedRanges.touchMajor.flat = 0;
3676 mOrientedRanges.touchMajor.fuzz = 0;
3677 mOrientedRanges.touchMajor.resolution = 0;
3678
3679 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3680 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3681
3682 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3683 mOrientedRanges.toolMajor.source = mSource;
3684 mOrientedRanges.toolMajor.min = 0;
3685 mOrientedRanges.toolMajor.max = diagonalSize;
3686 mOrientedRanges.toolMajor.flat = 0;
3687 mOrientedRanges.toolMajor.fuzz = 0;
3688 mOrientedRanges.toolMajor.resolution = 0;
3689
3690 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3691 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3692
3693 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3694 mOrientedRanges.size.source = mSource;
3695 mOrientedRanges.size.min = 0;
3696 mOrientedRanges.size.max = 1.0;
3697 mOrientedRanges.size.flat = 0;
3698 mOrientedRanges.size.fuzz = 0;
3699 mOrientedRanges.size.resolution = 0;
3700 } else {
3701 mSizeScale = 0.0f;
3702 }
3703
3704 // Pressure factors.
3705 mPressureScale = 0;
3706 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3707 || mCalibration.pressureCalibration
3708 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3709 if (mCalibration.havePressureScale) {
3710 mPressureScale = mCalibration.pressureScale;
3711 } else if (mRawPointerAxes.pressure.valid
3712 && mRawPointerAxes.pressure.maxValue != 0) {
3713 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3714 }
3715 }
3716
3717 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3718 mOrientedRanges.pressure.source = mSource;
3719 mOrientedRanges.pressure.min = 0;
3720 mOrientedRanges.pressure.max = 1.0;
3721 mOrientedRanges.pressure.flat = 0;
3722 mOrientedRanges.pressure.fuzz = 0;
3723 mOrientedRanges.pressure.resolution = 0;
3724
3725 // Tilt
3726 mTiltXCenter = 0;
3727 mTiltXScale = 0;
3728 mTiltYCenter = 0;
3729 mTiltYScale = 0;
3730 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3731 if (mHaveTilt) {
3732 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3733 mRawPointerAxes.tiltX.maxValue);
3734 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3735 mRawPointerAxes.tiltY.maxValue);
3736 mTiltXScale = M_PI / 180;
3737 mTiltYScale = M_PI / 180;
3738
3739 mOrientedRanges.haveTilt = true;
3740
3741 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3742 mOrientedRanges.tilt.source = mSource;
3743 mOrientedRanges.tilt.min = 0;
3744 mOrientedRanges.tilt.max = M_PI_2;
3745 mOrientedRanges.tilt.flat = 0;
3746 mOrientedRanges.tilt.fuzz = 0;
3747 mOrientedRanges.tilt.resolution = 0;
3748 }
3749
3750 // Orientation
3751 mOrientationScale = 0;
3752 if (mHaveTilt) {
3753 mOrientedRanges.haveOrientation = true;
3754
3755 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3756 mOrientedRanges.orientation.source = mSource;
3757 mOrientedRanges.orientation.min = -M_PI;
3758 mOrientedRanges.orientation.max = M_PI;
3759 mOrientedRanges.orientation.flat = 0;
3760 mOrientedRanges.orientation.fuzz = 0;
3761 mOrientedRanges.orientation.resolution = 0;
3762 } else if (mCalibration.orientationCalibration !=
3763 Calibration::ORIENTATION_CALIBRATION_NONE) {
3764 if (mCalibration.orientationCalibration
3765 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3766 if (mRawPointerAxes.orientation.valid) {
3767 if (mRawPointerAxes.orientation.maxValue > 0) {
3768 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3769 } else if (mRawPointerAxes.orientation.minValue < 0) {
3770 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3771 } else {
3772 mOrientationScale = 0;
3773 }
3774 }
3775 }
3776
3777 mOrientedRanges.haveOrientation = true;
3778
3779 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3780 mOrientedRanges.orientation.source = mSource;
3781 mOrientedRanges.orientation.min = -M_PI_2;
3782 mOrientedRanges.orientation.max = M_PI_2;
3783 mOrientedRanges.orientation.flat = 0;
3784 mOrientedRanges.orientation.fuzz = 0;
3785 mOrientedRanges.orientation.resolution = 0;
3786 }
3787
3788 // Distance
3789 mDistanceScale = 0;
3790 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3791 if (mCalibration.distanceCalibration
3792 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3793 if (mCalibration.haveDistanceScale) {
3794 mDistanceScale = mCalibration.distanceScale;
3795 } else {
3796 mDistanceScale = 1.0f;
3797 }
3798 }
3799
3800 mOrientedRanges.haveDistance = true;
3801
3802 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3803 mOrientedRanges.distance.source = mSource;
3804 mOrientedRanges.distance.min =
3805 mRawPointerAxes.distance.minValue * mDistanceScale;
3806 mOrientedRanges.distance.max =
3807 mRawPointerAxes.distance.maxValue * mDistanceScale;
3808 mOrientedRanges.distance.flat = 0;
3809 mOrientedRanges.distance.fuzz =
3810 mRawPointerAxes.distance.fuzz * mDistanceScale;
3811 mOrientedRanges.distance.resolution = 0;
3812 }
3813
3814 // Compute oriented precision, scales and ranges.
3815 // Note that the maximum value reported is an inclusive maximum value so it is one
3816 // unit less than the total width or height of surface.
3817 switch (mSurfaceOrientation) {
3818 case DISPLAY_ORIENTATION_90:
3819 case DISPLAY_ORIENTATION_270:
3820 mOrientedXPrecision = mYPrecision;
3821 mOrientedYPrecision = mXPrecision;
3822
3823 mOrientedRanges.x.min = mYTranslate;
3824 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3825 mOrientedRanges.x.flat = 0;
3826 mOrientedRanges.x.fuzz = 0;
3827 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3828
3829 mOrientedRanges.y.min = mXTranslate;
3830 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3831 mOrientedRanges.y.flat = 0;
3832 mOrientedRanges.y.fuzz = 0;
3833 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3834 break;
3835
3836 default:
3837 mOrientedXPrecision = mXPrecision;
3838 mOrientedYPrecision = mYPrecision;
3839
3840 mOrientedRanges.x.min = mXTranslate;
3841 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3842 mOrientedRanges.x.flat = 0;
3843 mOrientedRanges.x.fuzz = 0;
3844 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3845
3846 mOrientedRanges.y.min = mYTranslate;
3847 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3848 mOrientedRanges.y.flat = 0;
3849 mOrientedRanges.y.fuzz = 0;
3850 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3851 break;
3852 }
3853
Jason Gerecke71b16e82014-03-10 09:47:59 -07003854 // Location
3855 updateAffineTransformation();
3856
Michael Wrightd02c5b62014-02-10 15:10:22 -08003857 if (mDeviceMode == DEVICE_MODE_POINTER) {
3858 // Compute pointer gesture detection parameters.
3859 float rawDiagonal = hypotf(rawWidth, rawHeight);
3860 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3861
3862 // Scale movements such that one whole swipe of the touch pad covers a
3863 // given area relative to the diagonal size of the display when no acceleration
3864 // is applied.
3865 // Assume that the touch pad has a square aspect ratio such that movements in
3866 // X and Y of the same number of raw units cover the same physical distance.
3867 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3868 * displayDiagonal / rawDiagonal;
3869 mPointerYMovementScale = mPointerXMovementScale;
3870
3871 // Scale zooms to cover a smaller range of the display than movements do.
3872 // This value determines the area around the pointer that is affected by freeform
3873 // pointer gestures.
3874 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3875 * displayDiagonal / rawDiagonal;
3876 mPointerYZoomScale = mPointerXZoomScale;
3877
3878 // Max width between pointers to detect a swipe gesture is more than some fraction
3879 // of the diagonal axis of the touch pad. Touches that are wider than this are
3880 // translated into freeform gestures.
3881 mPointerGestureMaxSwipeWidth =
3882 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3883
3884 // Abort current pointer usages because the state has changed.
3885 abortPointerUsage(when, 0 /*policyFlags*/);
3886 }
3887
3888 // Inform the dispatcher about the changes.
3889 *outResetNeeded = true;
3890 bumpGeneration();
3891 }
3892}
3893
3894void TouchInputMapper::dumpSurface(String8& dump) {
3895 dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, "
3896 "logicalFrame=[%d, %d, %d, %d], "
3897 "physicalFrame=[%d, %d, %d, %d], "
3898 "deviceSize=[%d, %d]\n",
3899 mViewport.displayId, mViewport.orientation,
3900 mViewport.logicalLeft, mViewport.logicalTop,
3901 mViewport.logicalRight, mViewport.logicalBottom,
3902 mViewport.physicalLeft, mViewport.physicalTop,
3903 mViewport.physicalRight, mViewport.physicalBottom,
3904 mViewport.deviceWidth, mViewport.deviceHeight);
3905
3906 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3907 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3908 dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3909 dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
3910 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
3911}
3912
3913void TouchInputMapper::configureVirtualKeys() {
3914 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3915 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3916
3917 mVirtualKeys.clear();
3918
3919 if (virtualKeyDefinitions.size() == 0) {
3920 return;
3921 }
3922
3923 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3924
3925 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3926 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3927 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3928 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3929
3930 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3931 const VirtualKeyDefinition& virtualKeyDefinition =
3932 virtualKeyDefinitions[i];
3933
3934 mVirtualKeys.add();
3935 VirtualKey& virtualKey = mVirtualKeys.editTop();
3936
3937 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3938 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003939 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003941 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3942 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3944 virtualKey.scanCode);
3945 mVirtualKeys.pop(); // drop the key
3946 continue;
3947 }
3948
3949 virtualKey.keyCode = keyCode;
3950 virtualKey.flags = flags;
3951
3952 // convert the key definition's display coordinates into touch coordinates for a hit box
3953 int32_t halfWidth = virtualKeyDefinition.width / 2;
3954 int32_t halfHeight = virtualKeyDefinition.height / 2;
3955
3956 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3957 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3958 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3959 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3960 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3961 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3962 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3963 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3964 }
3965}
3966
3967void TouchInputMapper::dumpVirtualKeys(String8& dump) {
3968 if (!mVirtualKeys.isEmpty()) {
3969 dump.append(INDENT3 "Virtual Keys:\n");
3970
3971 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3972 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Mark Salyzyn41d2f802014-03-18 10:59:23 -07003973 dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3975 i, virtualKey.scanCode, virtualKey.keyCode,
3976 virtualKey.hitLeft, virtualKey.hitRight,
3977 virtualKey.hitTop, virtualKey.hitBottom);
3978 }
3979 }
3980}
3981
3982void TouchInputMapper::parseCalibration() {
3983 const PropertyMap& in = getDevice()->getConfiguration();
3984 Calibration& out = mCalibration;
3985
3986 // Size
3987 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3988 String8 sizeCalibrationString;
3989 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3990 if (sizeCalibrationString == "none") {
3991 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3992 } else if (sizeCalibrationString == "geometric") {
3993 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3994 } else if (sizeCalibrationString == "diameter") {
3995 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3996 } else if (sizeCalibrationString == "box") {
3997 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3998 } else if (sizeCalibrationString == "area") {
3999 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4000 } else if (sizeCalibrationString != "default") {
4001 ALOGW("Invalid value for touch.size.calibration: '%s'",
4002 sizeCalibrationString.string());
4003 }
4004 }
4005
4006 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4007 out.sizeScale);
4008 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4009 out.sizeBias);
4010 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4011 out.sizeIsSummed);
4012
4013 // Pressure
4014 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4015 String8 pressureCalibrationString;
4016 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4017 if (pressureCalibrationString == "none") {
4018 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4019 } else if (pressureCalibrationString == "physical") {
4020 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4021 } else if (pressureCalibrationString == "amplitude") {
4022 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4023 } else if (pressureCalibrationString != "default") {
4024 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4025 pressureCalibrationString.string());
4026 }
4027 }
4028
4029 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4030 out.pressureScale);
4031
4032 // Orientation
4033 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4034 String8 orientationCalibrationString;
4035 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4036 if (orientationCalibrationString == "none") {
4037 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4038 } else if (orientationCalibrationString == "interpolated") {
4039 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4040 } else if (orientationCalibrationString == "vector") {
4041 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4042 } else if (orientationCalibrationString != "default") {
4043 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4044 orientationCalibrationString.string());
4045 }
4046 }
4047
4048 // Distance
4049 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4050 String8 distanceCalibrationString;
4051 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4052 if (distanceCalibrationString == "none") {
4053 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4054 } else if (distanceCalibrationString == "scaled") {
4055 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4056 } else if (distanceCalibrationString != "default") {
4057 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4058 distanceCalibrationString.string());
4059 }
4060 }
4061
4062 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4063 out.distanceScale);
4064
4065 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4066 String8 coverageCalibrationString;
4067 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4068 if (coverageCalibrationString == "none") {
4069 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4070 } else if (coverageCalibrationString == "box") {
4071 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4072 } else if (coverageCalibrationString != "default") {
4073 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4074 coverageCalibrationString.string());
4075 }
4076 }
4077}
4078
4079void TouchInputMapper::resolveCalibration() {
4080 // Size
4081 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4082 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4083 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4084 }
4085 } else {
4086 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4087 }
4088
4089 // Pressure
4090 if (mRawPointerAxes.pressure.valid) {
4091 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4092 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4093 }
4094 } else {
4095 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4096 }
4097
4098 // Orientation
4099 if (mRawPointerAxes.orientation.valid) {
4100 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4101 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4102 }
4103 } else {
4104 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4105 }
4106
4107 // Distance
4108 if (mRawPointerAxes.distance.valid) {
4109 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4110 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4111 }
4112 } else {
4113 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4114 }
4115
4116 // Coverage
4117 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4118 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4119 }
4120}
4121
4122void TouchInputMapper::dumpCalibration(String8& dump) {
4123 dump.append(INDENT3 "Calibration:\n");
4124
4125 // Size
4126 switch (mCalibration.sizeCalibration) {
4127 case Calibration::SIZE_CALIBRATION_NONE:
4128 dump.append(INDENT4 "touch.size.calibration: none\n");
4129 break;
4130 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4131 dump.append(INDENT4 "touch.size.calibration: geometric\n");
4132 break;
4133 case Calibration::SIZE_CALIBRATION_DIAMETER:
4134 dump.append(INDENT4 "touch.size.calibration: diameter\n");
4135 break;
4136 case Calibration::SIZE_CALIBRATION_BOX:
4137 dump.append(INDENT4 "touch.size.calibration: box\n");
4138 break;
4139 case Calibration::SIZE_CALIBRATION_AREA:
4140 dump.append(INDENT4 "touch.size.calibration: area\n");
4141 break;
4142 default:
4143 ALOG_ASSERT(false);
4144 }
4145
4146 if (mCalibration.haveSizeScale) {
4147 dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n",
4148 mCalibration.sizeScale);
4149 }
4150
4151 if (mCalibration.haveSizeBias) {
4152 dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n",
4153 mCalibration.sizeBias);
4154 }
4155
4156 if (mCalibration.haveSizeIsSummed) {
4157 dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n",
4158 toString(mCalibration.sizeIsSummed));
4159 }
4160
4161 // Pressure
4162 switch (mCalibration.pressureCalibration) {
4163 case Calibration::PRESSURE_CALIBRATION_NONE:
4164 dump.append(INDENT4 "touch.pressure.calibration: none\n");
4165 break;
4166 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4167 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
4168 break;
4169 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4170 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
4171 break;
4172 default:
4173 ALOG_ASSERT(false);
4174 }
4175
4176 if (mCalibration.havePressureScale) {
4177 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
4178 mCalibration.pressureScale);
4179 }
4180
4181 // Orientation
4182 switch (mCalibration.orientationCalibration) {
4183 case Calibration::ORIENTATION_CALIBRATION_NONE:
4184 dump.append(INDENT4 "touch.orientation.calibration: none\n");
4185 break;
4186 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4187 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
4188 break;
4189 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
4190 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
4191 break;
4192 default:
4193 ALOG_ASSERT(false);
4194 }
4195
4196 // Distance
4197 switch (mCalibration.distanceCalibration) {
4198 case Calibration::DISTANCE_CALIBRATION_NONE:
4199 dump.append(INDENT4 "touch.distance.calibration: none\n");
4200 break;
4201 case Calibration::DISTANCE_CALIBRATION_SCALED:
4202 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
4203 break;
4204 default:
4205 ALOG_ASSERT(false);
4206 }
4207
4208 if (mCalibration.haveDistanceScale) {
4209 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
4210 mCalibration.distanceScale);
4211 }
4212
4213 switch (mCalibration.coverageCalibration) {
4214 case Calibration::COVERAGE_CALIBRATION_NONE:
4215 dump.append(INDENT4 "touch.coverage.calibration: none\n");
4216 break;
4217 case Calibration::COVERAGE_CALIBRATION_BOX:
4218 dump.append(INDENT4 "touch.coverage.calibration: box\n");
4219 break;
4220 default:
4221 ALOG_ASSERT(false);
4222 }
4223}
4224
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004225void TouchInputMapper::dumpAffineTransformation(String8& dump) {
4226 dump.append(INDENT3 "Affine Transformation:\n");
4227
4228 dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4229 dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4230 dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4231 dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4232 dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4233 dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
4234}
4235
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004236void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004237 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4238 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004239}
4240
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241void TouchInputMapper::reset(nsecs_t when) {
4242 mCursorButtonAccumulator.reset(getDevice());
4243 mCursorScrollAccumulator.reset(getDevice());
4244 mTouchButtonAccumulator.reset(getDevice());
4245
4246 mPointerVelocityControl.reset();
4247 mWheelXVelocityControl.reset();
4248 mWheelYVelocityControl.reset();
4249
Michael Wright842500e2015-03-13 17:32:02 -07004250 mRawStatesPending.clear();
4251 mCurrentRawState.clear();
4252 mCurrentCookedState.clear();
4253 mLastRawState.clear();
4254 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004255 mPointerUsage = POINTER_USAGE_NONE;
4256 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004257 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004258 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 mDownTime = 0;
4260
4261 mCurrentVirtualKey.down = false;
4262
4263 mPointerGesture.reset();
4264 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004265 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266
4267 if (mPointerController != NULL) {
4268 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4269 mPointerController->clearSpots();
4270 }
4271
4272 InputMapper::reset(when);
4273}
4274
Michael Wright842500e2015-03-13 17:32:02 -07004275void TouchInputMapper::resetExternalStylus() {
4276 mExternalStylusState.clear();
4277 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004278 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004279 mExternalStylusDataPending = false;
4280}
4281
Michael Wright43fd19f2015-04-21 19:02:58 +01004282void TouchInputMapper::clearStylusDataPendingFlags() {
4283 mExternalStylusDataPending = false;
4284 mExternalStylusFusionTimeout = LLONG_MAX;
4285}
4286
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287void TouchInputMapper::process(const RawEvent* rawEvent) {
4288 mCursorButtonAccumulator.process(rawEvent);
4289 mCursorScrollAccumulator.process(rawEvent);
4290 mTouchButtonAccumulator.process(rawEvent);
4291
4292 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4293 sync(rawEvent->when);
4294 }
4295}
4296
4297void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004298 const RawState* last = mRawStatesPending.isEmpty() ?
4299 &mCurrentRawState : &mRawStatesPending.top();
4300
4301 // Push a new state.
4302 mRawStatesPending.push();
4303 RawState* next = &mRawStatesPending.editTop();
4304 next->clear();
4305 next->when = when;
4306
Michael Wrightd02c5b62014-02-10 15:10:22 -08004307 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004308 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 | mCursorButtonAccumulator.getButtonState();
4310
Michael Wright842500e2015-03-13 17:32:02 -07004311 // Sync scroll
4312 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4313 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004314 mCursorScrollAccumulator.finishSync();
4315
Michael Wright842500e2015-03-13 17:32:02 -07004316 // Sync touch
4317 syncTouch(when, next);
4318
4319 // Assign pointer ids.
4320 if (!mHavePointerIds) {
4321 assignPointerIds(last, next);
4322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323
4324#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004325 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4326 "hovering ids 0x%08x -> 0x%08x",
4327 last->rawPointerData.pointerCount,
4328 next->rawPointerData.pointerCount,
4329 last->rawPointerData.touchingIdBits.value,
4330 next->rawPointerData.touchingIdBits.value,
4331 last->rawPointerData.hoveringIdBits.value,
4332 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333#endif
4334
Michael Wright842500e2015-03-13 17:32:02 -07004335 processRawTouches(false /*timeout*/);
4336}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337
Michael Wright842500e2015-03-13 17:32:02 -07004338void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4340 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004341 mCurrentRawState.clear();
4342 mRawStatesPending.clear();
4343 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 }
4345
Michael Wright842500e2015-03-13 17:32:02 -07004346 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4347 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4348 // touching the current state will only observe the events that have been dispatched to the
4349 // rest of the pipeline.
4350 const size_t N = mRawStatesPending.size();
4351 size_t count;
4352 for(count = 0; count < N; count++) {
4353 const RawState& next = mRawStatesPending[count];
4354
4355 // A failure to assign the stylus id means that we're waiting on stylus data
4356 // and so should defer the rest of the pipeline.
4357 if (assignExternalStylusId(next, timeout)) {
4358 break;
4359 }
4360
4361 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004362 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004363 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004364 if (mCurrentRawState.when < mLastRawState.when) {
4365 mCurrentRawState.when = mLastRawState.when;
4366 }
Michael Wright842500e2015-03-13 17:32:02 -07004367 cookAndDispatch(mCurrentRawState.when);
4368 }
4369 if (count != 0) {
4370 mRawStatesPending.removeItemsAt(0, count);
4371 }
4372
Michael Wright842500e2015-03-13 17:32:02 -07004373 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004374 if (timeout) {
4375 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4376 clearStylusDataPendingFlags();
4377 mCurrentRawState.copyFrom(mLastRawState);
4378#if DEBUG_STYLUS_FUSION
4379 ALOGD("Timeout expired, synthesizing event with new stylus data");
4380#endif
4381 cookAndDispatch(when);
4382 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4383 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4384 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4385 }
Michael Wright842500e2015-03-13 17:32:02 -07004386 }
4387}
4388
4389void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4390 // Always start with a clean state.
4391 mCurrentCookedState.clear();
4392
4393 // Apply stylus buttons to current raw state.
4394 applyExternalStylusButtonState(when);
4395
4396 // Handle policy on initial down or hover events.
4397 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4398 && mCurrentRawState.rawPointerData.pointerCount != 0;
4399
4400 uint32_t policyFlags = 0;
4401 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4402 if (initialDown || buttonsPressed) {
4403 // If this is a touch screen, hide the pointer on an initial down.
4404 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4405 getContext()->fadePointer();
4406 }
4407
4408 if (mParameters.wake) {
4409 policyFlags |= POLICY_FLAG_WAKE;
4410 }
4411 }
4412
4413 // Consume raw off-screen touches before cooking pointer data.
4414 // If touches are consumed, subsequent code will not receive any pointer data.
4415 if (consumeRawTouches(when, policyFlags)) {
4416 mCurrentRawState.rawPointerData.clear();
4417 }
4418
4419 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4420 // with cooked pointer data that has the same ids and indices as the raw data.
4421 // The following code can use either the raw or cooked data, as needed.
4422 cookPointerData();
4423
4424 // Apply stylus pressure to current cooked state.
4425 applyExternalStylusTouchState(when);
4426
4427 // Synthesize key down from raw buttons if needed.
4428 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004429 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004430
4431 // Dispatch the touches either directly or by translation through a pointer on screen.
4432 if (mDeviceMode == DEVICE_MODE_POINTER) {
4433 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4434 !idBits.isEmpty(); ) {
4435 uint32_t id = idBits.clearFirstMarkedBit();
4436 const RawPointerData::Pointer& pointer =
4437 mCurrentRawState.rawPointerData.pointerForId(id);
4438 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4439 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4440 mCurrentCookedState.stylusIdBits.markBit(id);
4441 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4442 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4443 mCurrentCookedState.fingerIdBits.markBit(id);
4444 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4445 mCurrentCookedState.mouseIdBits.markBit(id);
4446 }
4447 }
4448 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4449 !idBits.isEmpty(); ) {
4450 uint32_t id = idBits.clearFirstMarkedBit();
4451 const RawPointerData::Pointer& pointer =
4452 mCurrentRawState.rawPointerData.pointerForId(id);
4453 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4454 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4455 mCurrentCookedState.stylusIdBits.markBit(id);
4456 }
4457 }
4458
4459 // Stylus takes precedence over all tools, then mouse, then finger.
4460 PointerUsage pointerUsage = mPointerUsage;
4461 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4462 mCurrentCookedState.mouseIdBits.clear();
4463 mCurrentCookedState.fingerIdBits.clear();
4464 pointerUsage = POINTER_USAGE_STYLUS;
4465 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4466 mCurrentCookedState.fingerIdBits.clear();
4467 pointerUsage = POINTER_USAGE_MOUSE;
4468 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4469 isPointerDown(mCurrentRawState.buttonState)) {
4470 pointerUsage = POINTER_USAGE_GESTURES;
4471 }
4472
4473 dispatchPointerUsage(when, policyFlags, pointerUsage);
4474 } else {
4475 if (mDeviceMode == DEVICE_MODE_DIRECT
4476 && mConfig.showTouches && mPointerController != NULL) {
4477 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4478 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4479
4480 mPointerController->setButtonState(mCurrentRawState.buttonState);
4481 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4482 mCurrentCookedState.cookedPointerData.idToIndex,
4483 mCurrentCookedState.cookedPointerData.touchingIdBits);
4484 }
4485
Michael Wright8e812822015-06-22 16:18:21 +01004486 if (!mCurrentMotionAborted) {
4487 dispatchButtonRelease(when, policyFlags);
4488 dispatchHoverExit(when, policyFlags);
4489 dispatchTouches(when, policyFlags);
4490 dispatchHoverEnterAndMove(when, policyFlags);
4491 dispatchButtonPress(when, policyFlags);
4492 }
4493
4494 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4495 mCurrentMotionAborted = false;
4496 }
Michael Wright842500e2015-03-13 17:32:02 -07004497 }
4498
4499 // Synthesize key up from raw buttons if needed.
4500 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004501 policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004502
4503 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004504 mCurrentRawState.rawVScroll = 0;
4505 mCurrentRawState.rawHScroll = 0;
4506
4507 // Copy current touch to last touch in preparation for the next cycle.
4508 mLastRawState.copyFrom(mCurrentRawState);
4509 mLastCookedState.copyFrom(mCurrentCookedState);
4510}
4511
4512void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004513 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004514 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4515 }
4516}
4517
4518void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004519 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4520 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004521
Michael Wright53dca3a2015-04-23 17:39:53 +01004522 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4523 float pressure = mExternalStylusState.pressure;
4524 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4525 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4526 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4527 }
4528 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4529 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4530
4531 PointerProperties& properties =
4532 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004533 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4534 properties.toolType = mExternalStylusState.toolType;
4535 }
4536 }
4537}
4538
4539bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4540 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4541 return false;
4542 }
4543
4544 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4545 && state.rawPointerData.pointerCount != 0;
4546 if (initialDown) {
4547 if (mExternalStylusState.pressure != 0.0f) {
4548#if DEBUG_STYLUS_FUSION
4549 ALOGD("Have both stylus and touch data, beginning fusion");
4550#endif
4551 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4552 } else if (timeout) {
4553#if DEBUG_STYLUS_FUSION
4554 ALOGD("Timeout expired, assuming touch is not a stylus.");
4555#endif
4556 resetExternalStylus();
4557 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004558 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4559 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004560 }
4561#if DEBUG_STYLUS_FUSION
4562 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004563 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004564#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004565 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004566 return true;
4567 }
4568 }
4569
4570 // Check if the stylus pointer has gone up.
4571 if (mExternalStylusId != -1 &&
4572 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4573#if DEBUG_STYLUS_FUSION
4574 ALOGD("Stylus pointer is going up");
4575#endif
4576 mExternalStylusId = -1;
4577 }
4578
4579 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004580}
4581
4582void TouchInputMapper::timeoutExpired(nsecs_t when) {
4583 if (mDeviceMode == DEVICE_MODE_POINTER) {
4584 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4585 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4586 }
Michael Wright842500e2015-03-13 17:32:02 -07004587 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004588 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004589 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004590 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4591 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004592 }
4593 }
4594}
4595
4596void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004597 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004598 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004599 // We're either in the middle of a fused stream of data or we're waiting on data before
4600 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4601 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004602 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004603 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604 }
4605}
4606
4607bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4608 // Check for release of a virtual key.
4609 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004610 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004611 // Pointer went up while virtual key was down.
4612 mCurrentVirtualKey.down = false;
4613 if (!mCurrentVirtualKey.ignored) {
4614#if DEBUG_VIRTUAL_KEYS
4615 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4616 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4617#endif
4618 dispatchVirtualKey(when, policyFlags,
4619 AKEY_EVENT_ACTION_UP,
4620 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4621 }
4622 return true;
4623 }
4624
Michael Wright842500e2015-03-13 17:32:02 -07004625 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4626 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4627 const RawPointerData::Pointer& pointer =
4628 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004629 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4630 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4631 // Pointer is still within the space of the virtual key.
4632 return true;
4633 }
4634 }
4635
4636 // Pointer left virtual key area or another pointer also went down.
4637 // Send key cancellation but do not consume the touch yet.
4638 // This is useful when the user swipes through from the virtual key area
4639 // into the main display surface.
4640 mCurrentVirtualKey.down = false;
4641 if (!mCurrentVirtualKey.ignored) {
4642#if DEBUG_VIRTUAL_KEYS
4643 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4644 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4645#endif
4646 dispatchVirtualKey(when, policyFlags,
4647 AKEY_EVENT_ACTION_UP,
4648 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4649 | AKEY_EVENT_FLAG_CANCELED);
4650 }
4651 }
4652
Michael Wright842500e2015-03-13 17:32:02 -07004653 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4654 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004656 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4657 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4659 // If exactly one pointer went down, check for virtual key hit.
4660 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004661 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004662 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4663 if (virtualKey) {
4664 mCurrentVirtualKey.down = true;
4665 mCurrentVirtualKey.downTime = when;
4666 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4667 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4668 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4669 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4670
4671 if (!mCurrentVirtualKey.ignored) {
4672#if DEBUG_VIRTUAL_KEYS
4673 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4674 mCurrentVirtualKey.keyCode,
4675 mCurrentVirtualKey.scanCode);
4676#endif
4677 dispatchVirtualKey(when, policyFlags,
4678 AKEY_EVENT_ACTION_DOWN,
4679 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4680 }
4681 }
4682 }
4683 return true;
4684 }
4685 }
4686
4687 // Disable all virtual key touches that happen within a short time interval of the
4688 // most recent touch within the screen area. The idea is to filter out stray
4689 // virtual key presses when interacting with the touch screen.
4690 //
4691 // Problems we're trying to solve:
4692 //
4693 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4694 // virtual key area that is implemented by a separate touch panel and accidentally
4695 // triggers a virtual key.
4696 //
4697 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4698 // area and accidentally triggers a virtual key. This often happens when virtual keys
4699 // are layed out below the screen near to where the on screen keyboard's space bar
4700 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004701 if (mConfig.virtualKeyQuietTime > 0 &&
4702 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4704 }
4705 return false;
4706}
4707
4708void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4709 int32_t keyEventAction, int32_t keyEventFlags) {
4710 int32_t keyCode = mCurrentVirtualKey.keyCode;
4711 int32_t scanCode = mCurrentVirtualKey.scanCode;
4712 nsecs_t downTime = mCurrentVirtualKey.downTime;
4713 int32_t metaState = mContext->getGlobalMetaState();
4714 policyFlags |= POLICY_FLAG_VIRTUAL;
4715
4716 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
4717 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
4718 getListener()->notifyKey(&args);
4719}
4720
Michael Wright8e812822015-06-22 16:18:21 +01004721void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4722 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4723 if (!currentIdBits.isEmpty()) {
4724 int32_t metaState = getContext()->getGlobalMetaState();
4725 int32_t buttonState = mCurrentCookedState.buttonState;
4726 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4727 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4728 mCurrentCookedState.cookedPointerData.pointerProperties,
4729 mCurrentCookedState.cookedPointerData.pointerCoords,
4730 mCurrentCookedState.cookedPointerData.idToIndex,
4731 currentIdBits, -1,
4732 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4733 mCurrentMotionAborted = true;
4734 }
4735}
4736
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004738 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4739 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004741 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742
4743 if (currentIdBits == lastIdBits) {
4744 if (!currentIdBits.isEmpty()) {
4745 // No pointer id changes so this is a move event.
4746 // The listener takes care of batching moves so we don't have to deal with that here.
4747 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004748 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004750 mCurrentCookedState.cookedPointerData.pointerProperties,
4751 mCurrentCookedState.cookedPointerData.pointerCoords,
4752 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 currentIdBits, -1,
4754 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4755 }
4756 } else {
4757 // There may be pointers going up and pointers going down and pointers moving
4758 // all at the same time.
4759 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4760 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4761 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4762 BitSet32 dispatchedIdBits(lastIdBits.value);
4763
4764 // Update last coordinates of pointers that have moved so that we observe the new
4765 // pointer positions at the same time as other pointers that have just gone up.
4766 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004767 mCurrentCookedState.cookedPointerData.pointerProperties,
4768 mCurrentCookedState.cookedPointerData.pointerCoords,
4769 mCurrentCookedState.cookedPointerData.idToIndex,
4770 mLastCookedState.cookedPointerData.pointerProperties,
4771 mLastCookedState.cookedPointerData.pointerCoords,
4772 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004774 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 moveNeeded = true;
4776 }
4777
4778 // Dispatch pointer up events.
4779 while (!upIdBits.isEmpty()) {
4780 uint32_t upId = upIdBits.clearFirstMarkedBit();
4781
4782 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004783 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004784 mLastCookedState.cookedPointerData.pointerProperties,
4785 mLastCookedState.cookedPointerData.pointerCoords,
4786 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004787 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 dispatchedIdBits.clearBit(upId);
4789 }
4790
4791 // Dispatch move events if any of the remaining pointers moved from their old locations.
4792 // Although applications receive new locations as part of individual pointer up
4793 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004794 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4796 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004797 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004798 mCurrentCookedState.cookedPointerData.pointerProperties,
4799 mCurrentCookedState.cookedPointerData.pointerCoords,
4800 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004801 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 }
4803
4804 // Dispatch pointer down events using the new pointer locations.
4805 while (!downIdBits.isEmpty()) {
4806 uint32_t downId = downIdBits.clearFirstMarkedBit();
4807 dispatchedIdBits.markBit(downId);
4808
4809 if (dispatchedIdBits.count() == 1) {
4810 // First pointer is going down. Set down time.
4811 mDownTime = when;
4812 }
4813
4814 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004815 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004816 mCurrentCookedState.cookedPointerData.pointerProperties,
4817 mCurrentCookedState.cookedPointerData.pointerCoords,
4818 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004819 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 }
4821 }
4822}
4823
4824void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4825 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004826 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4827 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 int32_t metaState = getContext()->getGlobalMetaState();
4829 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004830 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004831 mLastCookedState.cookedPointerData.pointerProperties,
4832 mLastCookedState.cookedPointerData.pointerCoords,
4833 mLastCookedState.cookedPointerData.idToIndex,
4834 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4836 mSentHoverEnter = false;
4837 }
4838}
4839
4840void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004841 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4842 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 int32_t metaState = getContext()->getGlobalMetaState();
4844 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004845 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004846 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004847 mCurrentCookedState.cookedPointerData.pointerProperties,
4848 mCurrentCookedState.cookedPointerData.pointerCoords,
4849 mCurrentCookedState.cookedPointerData.idToIndex,
4850 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4852 mSentHoverEnter = true;
4853 }
4854
4855 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004856 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004857 mCurrentRawState.buttonState, 0,
4858 mCurrentCookedState.cookedPointerData.pointerProperties,
4859 mCurrentCookedState.cookedPointerData.pointerCoords,
4860 mCurrentCookedState.cookedPointerData.idToIndex,
4861 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4863 }
4864}
4865
Michael Wright7b159c92015-05-14 14:48:03 +01004866void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4867 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4868 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4869 const int32_t metaState = getContext()->getGlobalMetaState();
4870 int32_t buttonState = mLastCookedState.buttonState;
4871 while (!releasedButtons.isEmpty()) {
4872 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4873 buttonState &= ~actionButton;
4874 dispatchMotion(when, policyFlags, mSource,
4875 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4876 0, metaState, buttonState, 0,
4877 mCurrentCookedState.cookedPointerData.pointerProperties,
4878 mCurrentCookedState.cookedPointerData.pointerCoords,
4879 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4880 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4881 }
4882}
4883
4884void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4885 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4886 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4887 const int32_t metaState = getContext()->getGlobalMetaState();
4888 int32_t buttonState = mLastCookedState.buttonState;
4889 while (!pressedButtons.isEmpty()) {
4890 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4891 buttonState |= actionButton;
4892 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4893 0, metaState, buttonState, 0,
4894 mCurrentCookedState.cookedPointerData.pointerProperties,
4895 mCurrentCookedState.cookedPointerData.pointerCoords,
4896 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4897 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4898 }
4899}
4900
4901const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4902 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4903 return cookedPointerData.touchingIdBits;
4904 }
4905 return cookedPointerData.hoveringIdBits;
4906}
4907
Michael Wrightd02c5b62014-02-10 15:10:22 -08004908void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004909 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910
Michael Wright842500e2015-03-13 17:32:02 -07004911 mCurrentCookedState.cookedPointerData.clear();
4912 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4913 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4914 mCurrentRawState.rawPointerData.hoveringIdBits;
4915 mCurrentCookedState.cookedPointerData.touchingIdBits =
4916 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917
Michael Wright7b159c92015-05-14 14:48:03 +01004918 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4919 mCurrentCookedState.buttonState = 0;
4920 } else {
4921 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4922 }
4923
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924 // Walk through the the active pointers and map device coordinates onto
4925 // surface coordinates and adjust for display orientation.
4926 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004927 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004928
4929 // Size
4930 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4931 switch (mCalibration.sizeCalibration) {
4932 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4933 case Calibration::SIZE_CALIBRATION_DIAMETER:
4934 case Calibration::SIZE_CALIBRATION_BOX:
4935 case Calibration::SIZE_CALIBRATION_AREA:
4936 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4937 touchMajor = in.touchMajor;
4938 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4939 toolMajor = in.toolMajor;
4940 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4941 size = mRawPointerAxes.touchMinor.valid
4942 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4943 } else if (mRawPointerAxes.touchMajor.valid) {
4944 toolMajor = touchMajor = in.touchMajor;
4945 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4946 ? in.touchMinor : in.touchMajor;
4947 size = mRawPointerAxes.touchMinor.valid
4948 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4949 } else if (mRawPointerAxes.toolMajor.valid) {
4950 touchMajor = toolMajor = in.toolMajor;
4951 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4952 ? in.toolMinor : in.toolMajor;
4953 size = mRawPointerAxes.toolMinor.valid
4954 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4955 } else {
4956 ALOG_ASSERT(false, "No touch or tool axes. "
4957 "Size calibration should have been resolved to NONE.");
4958 touchMajor = 0;
4959 touchMinor = 0;
4960 toolMajor = 0;
4961 toolMinor = 0;
4962 size = 0;
4963 }
4964
4965 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004966 uint32_t touchingCount =
4967 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004968 if (touchingCount > 1) {
4969 touchMajor /= touchingCount;
4970 touchMinor /= touchingCount;
4971 toolMajor /= touchingCount;
4972 toolMinor /= touchingCount;
4973 size /= touchingCount;
4974 }
4975 }
4976
4977 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4978 touchMajor *= mGeometricScale;
4979 touchMinor *= mGeometricScale;
4980 toolMajor *= mGeometricScale;
4981 toolMinor *= mGeometricScale;
4982 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4983 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4984 touchMinor = touchMajor;
4985 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4986 toolMinor = toolMajor;
4987 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4988 touchMinor = touchMajor;
4989 toolMinor = toolMajor;
4990 }
4991
4992 mCalibration.applySizeScaleAndBias(&touchMajor);
4993 mCalibration.applySizeScaleAndBias(&touchMinor);
4994 mCalibration.applySizeScaleAndBias(&toolMajor);
4995 mCalibration.applySizeScaleAndBias(&toolMinor);
4996 size *= mSizeScale;
4997 break;
4998 default:
4999 touchMajor = 0;
5000 touchMinor = 0;
5001 toolMajor = 0;
5002 toolMinor = 0;
5003 size = 0;
5004 break;
5005 }
5006
5007 // Pressure
5008 float pressure;
5009 switch (mCalibration.pressureCalibration) {
5010 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5011 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5012 pressure = in.pressure * mPressureScale;
5013 break;
5014 default:
5015 pressure = in.isHovering ? 0 : 1;
5016 break;
5017 }
5018
5019 // Tilt and Orientation
5020 float tilt;
5021 float orientation;
5022 if (mHaveTilt) {
5023 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5024 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5025 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5026 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5027 } else {
5028 tilt = 0;
5029
5030 switch (mCalibration.orientationCalibration) {
5031 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5032 orientation = in.orientation * mOrientationScale;
5033 break;
5034 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5035 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5036 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5037 if (c1 != 0 || c2 != 0) {
5038 orientation = atan2f(c1, c2) * 0.5f;
5039 float confidence = hypotf(c1, c2);
5040 float scale = 1.0f + confidence / 16.0f;
5041 touchMajor *= scale;
5042 touchMinor /= scale;
5043 toolMajor *= scale;
5044 toolMinor /= scale;
5045 } else {
5046 orientation = 0;
5047 }
5048 break;
5049 }
5050 default:
5051 orientation = 0;
5052 }
5053 }
5054
5055 // Distance
5056 float distance;
5057 switch (mCalibration.distanceCalibration) {
5058 case Calibration::DISTANCE_CALIBRATION_SCALED:
5059 distance = in.distance * mDistanceScale;
5060 break;
5061 default:
5062 distance = 0;
5063 }
5064
5065 // Coverage
5066 int32_t rawLeft, rawTop, rawRight, rawBottom;
5067 switch (mCalibration.coverageCalibration) {
5068 case Calibration::COVERAGE_CALIBRATION_BOX:
5069 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5070 rawRight = in.toolMinor & 0x0000ffff;
5071 rawBottom = in.toolMajor & 0x0000ffff;
5072 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5073 break;
5074 default:
5075 rawLeft = rawTop = rawRight = rawBottom = 0;
5076 break;
5077 }
5078
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005079 // Adjust X,Y coords for device calibration
5080 // TODO: Adjust coverage coords?
5081 float xTransformed = in.x, yTransformed = in.y;
5082 mAffineTransform.applyTo(xTransformed, yTransformed);
5083
5084 // Adjust X, Y, and coverage coords for surface orientation.
5085 float x, y;
5086 float left, top, right, bottom;
5087
Michael Wrightd02c5b62014-02-10 15:10:22 -08005088 switch (mSurfaceOrientation) {
5089 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005090 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5091 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005092 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5093 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5094 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5095 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5096 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005097 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5099 }
5100 break;
5101 case DISPLAY_ORIENTATION_180:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005102 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5103 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005104 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5105 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5106 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5107 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5108 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005109 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5111 }
5112 break;
5113 case DISPLAY_ORIENTATION_270:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005114 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5115 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5117 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5118 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5119 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5120 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005121 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005122 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5123 }
5124 break;
5125 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005126 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5127 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5129 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5130 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5131 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5132 break;
5133 }
5134
5135 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005136 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005137 out.clear();
5138 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5139 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5140 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5141 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5142 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5143 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5144 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5145 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5146 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5147 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5148 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5149 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5150 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5151 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5152 } else {
5153 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5154 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5155 }
5156
5157 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005158 PointerProperties& properties =
5159 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 uint32_t id = in.id;
5161 properties.clear();
5162 properties.id = id;
5163 properties.toolType = in.toolType;
5164
5165 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005166 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005167 }
5168}
5169
5170void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5171 PointerUsage pointerUsage) {
5172 if (pointerUsage != mPointerUsage) {
5173 abortPointerUsage(when, policyFlags);
5174 mPointerUsage = pointerUsage;
5175 }
5176
5177 switch (mPointerUsage) {
5178 case POINTER_USAGE_GESTURES:
5179 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5180 break;
5181 case POINTER_USAGE_STYLUS:
5182 dispatchPointerStylus(when, policyFlags);
5183 break;
5184 case POINTER_USAGE_MOUSE:
5185 dispatchPointerMouse(when, policyFlags);
5186 break;
5187 default:
5188 break;
5189 }
5190}
5191
5192void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5193 switch (mPointerUsage) {
5194 case POINTER_USAGE_GESTURES:
5195 abortPointerGestures(when, policyFlags);
5196 break;
5197 case POINTER_USAGE_STYLUS:
5198 abortPointerStylus(when, policyFlags);
5199 break;
5200 case POINTER_USAGE_MOUSE:
5201 abortPointerMouse(when, policyFlags);
5202 break;
5203 default:
5204 break;
5205 }
5206
5207 mPointerUsage = POINTER_USAGE_NONE;
5208}
5209
5210void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5211 bool isTimeout) {
5212 // Update current gesture coordinates.
5213 bool cancelPreviousGesture, finishPreviousGesture;
5214 bool sendEvents = preparePointerGestures(when,
5215 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5216 if (!sendEvents) {
5217 return;
5218 }
5219 if (finishPreviousGesture) {
5220 cancelPreviousGesture = false;
5221 }
5222
5223 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005224 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5225 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005226 if (finishPreviousGesture || cancelPreviousGesture) {
5227 mPointerController->clearSpots();
5228 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005229
5230 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5231 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5232 mPointerGesture.currentGestureIdToIndex,
5233 mPointerGesture.currentGestureIdBits);
5234 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235 } else {
5236 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5237 }
5238
5239 // Show or hide the pointer if needed.
5240 switch (mPointerGesture.currentGestureMode) {
5241 case PointerGesture::NEUTRAL:
5242 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005243 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5244 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 // Remind the user of where the pointer is after finishing a gesture with spots.
5246 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5247 }
5248 break;
5249 case PointerGesture::TAP:
5250 case PointerGesture::TAP_DRAG:
5251 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5252 case PointerGesture::HOVER:
5253 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005254 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255 // Unfade the pointer when the current gesture manipulates the
5256 // area directly under the pointer.
5257 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5258 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005259 case PointerGesture::FREEFORM:
5260 // Fade the pointer when the current gesture manipulates a different
5261 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005262 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5264 } else {
5265 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5266 }
5267 break;
5268 }
5269
5270 // Send events!
5271 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005272 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273
5274 // Update last coordinates of pointers that have moved so that we observe the new
5275 // pointer positions at the same time as other pointers that have just gone up.
5276 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5277 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5278 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5279 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5280 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5281 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5282 bool moveNeeded = false;
5283 if (down && !cancelPreviousGesture && !finishPreviousGesture
5284 && !mPointerGesture.lastGestureIdBits.isEmpty()
5285 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5286 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5287 & mPointerGesture.lastGestureIdBits.value);
5288 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5289 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5290 mPointerGesture.lastGestureProperties,
5291 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5292 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005293 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 moveNeeded = true;
5295 }
5296 }
5297
5298 // Send motion events for all pointers that went up or were canceled.
5299 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5300 if (!dispatchedGestureIdBits.isEmpty()) {
5301 if (cancelPreviousGesture) {
5302 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005303 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 AMOTION_EVENT_EDGE_FLAG_NONE,
5305 mPointerGesture.lastGestureProperties,
5306 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005307 dispatchedGestureIdBits, -1, 0,
5308 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309
5310 dispatchedGestureIdBits.clear();
5311 } else {
5312 BitSet32 upGestureIdBits;
5313 if (finishPreviousGesture) {
5314 upGestureIdBits = dispatchedGestureIdBits;
5315 } else {
5316 upGestureIdBits.value = dispatchedGestureIdBits.value
5317 & ~mPointerGesture.currentGestureIdBits.value;
5318 }
5319 while (!upGestureIdBits.isEmpty()) {
5320 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5321
5322 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005323 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5325 mPointerGesture.lastGestureProperties,
5326 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5327 dispatchedGestureIdBits, id,
5328 0, 0, mPointerGesture.downTime);
5329
5330 dispatchedGestureIdBits.clearBit(id);
5331 }
5332 }
5333 }
5334
5335 // Send motion events for all pointers that moved.
5336 if (moveNeeded) {
5337 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005338 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
5339 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005340 mPointerGesture.currentGestureProperties,
5341 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5342 dispatchedGestureIdBits, -1,
5343 0, 0, mPointerGesture.downTime);
5344 }
5345
5346 // Send motion events for all pointers that went down.
5347 if (down) {
5348 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5349 & ~dispatchedGestureIdBits.value);
5350 while (!downGestureIdBits.isEmpty()) {
5351 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5352 dispatchedGestureIdBits.markBit(id);
5353
5354 if (dispatchedGestureIdBits.count() == 1) {
5355 mPointerGesture.downTime = when;
5356 }
5357
5358 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005359 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360 mPointerGesture.currentGestureProperties,
5361 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5362 dispatchedGestureIdBits, id,
5363 0, 0, mPointerGesture.downTime);
5364 }
5365 }
5366
5367 // Send motion events for hover.
5368 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5369 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005370 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5372 mPointerGesture.currentGestureProperties,
5373 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5374 mPointerGesture.currentGestureIdBits, -1,
5375 0, 0, mPointerGesture.downTime);
5376 } else if (dispatchedGestureIdBits.isEmpty()
5377 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5378 // Synthesize a hover move event after all pointers go up to indicate that
5379 // the pointer is hovering again even if the user is not currently touching
5380 // the touch pad. This ensures that a view will receive a fresh hover enter
5381 // event after a tap.
5382 float x, y;
5383 mPointerController->getPosition(&x, &y);
5384
5385 PointerProperties pointerProperties;
5386 pointerProperties.clear();
5387 pointerProperties.id = 0;
5388 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5389
5390 PointerCoords pointerCoords;
5391 pointerCoords.clear();
5392 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5393 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5394
5395 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005396 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5398 mViewport.displayId, 1, &pointerProperties, &pointerCoords,
5399 0, 0, mPointerGesture.downTime);
5400 getListener()->notifyMotion(&args);
5401 }
5402
5403 // Update state.
5404 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5405 if (!down) {
5406 mPointerGesture.lastGestureIdBits.clear();
5407 } else {
5408 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5409 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5410 uint32_t id = idBits.clearFirstMarkedBit();
5411 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5412 mPointerGesture.lastGestureProperties[index].copyFrom(
5413 mPointerGesture.currentGestureProperties[index]);
5414 mPointerGesture.lastGestureCoords[index].copyFrom(
5415 mPointerGesture.currentGestureCoords[index]);
5416 mPointerGesture.lastGestureIdToIndex[id] = index;
5417 }
5418 }
5419}
5420
5421void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5422 // Cancel previously dispatches pointers.
5423 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5424 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005425 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005427 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 AMOTION_EVENT_EDGE_FLAG_NONE,
5429 mPointerGesture.lastGestureProperties,
5430 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5431 mPointerGesture.lastGestureIdBits, -1,
5432 0, 0, mPointerGesture.downTime);
5433 }
5434
5435 // Reset the current pointer gesture.
5436 mPointerGesture.reset();
5437 mPointerVelocityControl.reset();
5438
5439 // Remove any current spots.
5440 if (mPointerController != NULL) {
5441 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5442 mPointerController->clearSpots();
5443 }
5444}
5445
5446bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5447 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5448 *outCancelPreviousGesture = false;
5449 *outFinishPreviousGesture = false;
5450
5451 // Handle TAP timeout.
5452 if (isTimeout) {
5453#if DEBUG_GESTURES
5454 ALOGD("Gestures: Processing timeout");
5455#endif
5456
5457 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5458 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5459 // The tap/drag timeout has not yet expired.
5460 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5461 + mConfig.pointerGestureTapDragInterval);
5462 } else {
5463 // The tap is finished.
5464#if DEBUG_GESTURES
5465 ALOGD("Gestures: TAP finished");
5466#endif
5467 *outFinishPreviousGesture = true;
5468
5469 mPointerGesture.activeGestureId = -1;
5470 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5471 mPointerGesture.currentGestureIdBits.clear();
5472
5473 mPointerVelocityControl.reset();
5474 return true;
5475 }
5476 }
5477
5478 // We did not handle this timeout.
5479 return false;
5480 }
5481
Michael Wright842500e2015-03-13 17:32:02 -07005482 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5483 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484
5485 // Update the velocity tracker.
5486 {
5487 VelocityTracker::Position positions[MAX_POINTERS];
5488 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005489 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005491 const RawPointerData::Pointer& pointer =
5492 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493 positions[count].x = pointer.x * mPointerXMovementScale;
5494 positions[count].y = pointer.y * mPointerYMovementScale;
5495 }
5496 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005497 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 }
5499
5500 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5501 // to NEUTRAL, then we should not generate tap event.
5502 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5503 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5504 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5505 mPointerGesture.resetTap();
5506 }
5507
5508 // Pick a new active touch id if needed.
5509 // Choose an arbitrary pointer that just went down, if there is one.
5510 // Otherwise choose an arbitrary remaining pointer.
5511 // This guarantees we always have an active touch id when there is at least one pointer.
5512 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5514 int32_t activeTouchId = lastActiveTouchId;
5515 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005516 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005518 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519 mPointerGesture.firstTouchTime = when;
5520 }
Michael Wright842500e2015-03-13 17:32:02 -07005521 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005522 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005523 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005524 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 } else {
5526 activeTouchId = mPointerGesture.activeTouchId = -1;
5527 }
5528 }
5529
5530 // Determine whether we are in quiet time.
5531 bool isQuietTime = false;
5532 if (activeTouchId < 0) {
5533 mPointerGesture.resetQuietTime();
5534 } else {
5535 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5536 if (!isQuietTime) {
5537 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5538 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5539 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5540 && currentFingerCount < 2) {
5541 // Enter quiet time when exiting swipe or freeform state.
5542 // This is to prevent accidentally entering the hover state and flinging the
5543 // pointer when finishing a swipe and there is still one pointer left onscreen.
5544 isQuietTime = true;
5545 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5546 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005547 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 // Enter quiet time when releasing the button and there are still two or more
5549 // fingers down. This may indicate that one finger was used to press the button
5550 // but it has not gone up yet.
5551 isQuietTime = true;
5552 }
5553 if (isQuietTime) {
5554 mPointerGesture.quietTime = when;
5555 }
5556 }
5557 }
5558
5559 // Switch states based on button and pointer state.
5560 if (isQuietTime) {
5561 // Case 1: Quiet time. (QUIET)
5562#if DEBUG_GESTURES
5563 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5564 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5565#endif
5566 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5567 *outFinishPreviousGesture = true;
5568 }
5569
5570 mPointerGesture.activeGestureId = -1;
5571 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5572 mPointerGesture.currentGestureIdBits.clear();
5573
5574 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005575 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5577 // The pointer follows the active touch point.
5578 // Emit DOWN, MOVE, UP events at the pointer location.
5579 //
5580 // Only the active touch matters; other fingers are ignored. This policy helps
5581 // to handle the case where the user places a second finger on the touch pad
5582 // to apply the necessary force to depress an integrated button below the surface.
5583 // We don't want the second finger to be delivered to applications.
5584 //
5585 // For this to work well, we need to make sure to track the pointer that is really
5586 // active. If the user first puts one finger down to click then adds another
5587 // finger to drag then the active pointer should switch to the finger that is
5588 // being dragged.
5589#if DEBUG_GESTURES
5590 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5591 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5592#endif
5593 // Reset state when just starting.
5594 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5595 *outFinishPreviousGesture = true;
5596 mPointerGesture.activeGestureId = 0;
5597 }
5598
5599 // Switch pointers if needed.
5600 // Find the fastest pointer and follow it.
5601 if (activeTouchId >= 0 && currentFingerCount > 1) {
5602 int32_t bestId = -1;
5603 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005604 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 uint32_t id = idBits.clearFirstMarkedBit();
5606 float vx, vy;
5607 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5608 float speed = hypotf(vx, vy);
5609 if (speed > bestSpeed) {
5610 bestId = id;
5611 bestSpeed = speed;
5612 }
5613 }
5614 }
5615 if (bestId >= 0 && bestId != activeTouchId) {
5616 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617#if DEBUG_GESTURES
5618 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5619 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5620#endif
5621 }
5622 }
5623
Jun Mukaifa1706a2015-12-03 01:14:46 -08005624 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005625 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005627 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005629 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005630 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5631 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632
5633 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5634 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5635
5636 // Move the pointer using a relative motion.
5637 // When using spots, the click will occur at the position of the anchor
5638 // spot and all other spots will move there.
5639 mPointerController->move(deltaX, deltaY);
5640 } else {
5641 mPointerVelocityControl.reset();
5642 }
5643
5644 float x, y;
5645 mPointerController->getPosition(&x, &y);
5646
5647 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5648 mPointerGesture.currentGestureIdBits.clear();
5649 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5650 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5651 mPointerGesture.currentGestureProperties[0].clear();
5652 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5653 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5654 mPointerGesture.currentGestureCoords[0].clear();
5655 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5656 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5657 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5658 } else if (currentFingerCount == 0) {
5659 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5660 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5661 *outFinishPreviousGesture = true;
5662 }
5663
5664 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5665 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5666 bool tapped = false;
5667 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5668 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5669 && lastFingerCount == 1) {
5670 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5671 float x, y;
5672 mPointerController->getPosition(&x, &y);
5673 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5674 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5675#if DEBUG_GESTURES
5676 ALOGD("Gestures: TAP");
5677#endif
5678
5679 mPointerGesture.tapUpTime = when;
5680 getContext()->requestTimeoutAtTime(when
5681 + mConfig.pointerGestureTapDragInterval);
5682
5683 mPointerGesture.activeGestureId = 0;
5684 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5685 mPointerGesture.currentGestureIdBits.clear();
5686 mPointerGesture.currentGestureIdBits.markBit(
5687 mPointerGesture.activeGestureId);
5688 mPointerGesture.currentGestureIdToIndex[
5689 mPointerGesture.activeGestureId] = 0;
5690 mPointerGesture.currentGestureProperties[0].clear();
5691 mPointerGesture.currentGestureProperties[0].id =
5692 mPointerGesture.activeGestureId;
5693 mPointerGesture.currentGestureProperties[0].toolType =
5694 AMOTION_EVENT_TOOL_TYPE_FINGER;
5695 mPointerGesture.currentGestureCoords[0].clear();
5696 mPointerGesture.currentGestureCoords[0].setAxisValue(
5697 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5698 mPointerGesture.currentGestureCoords[0].setAxisValue(
5699 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5700 mPointerGesture.currentGestureCoords[0].setAxisValue(
5701 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5702
5703 tapped = true;
5704 } else {
5705#if DEBUG_GESTURES
5706 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5707 x - mPointerGesture.tapX,
5708 y - mPointerGesture.tapY);
5709#endif
5710 }
5711 } else {
5712#if DEBUG_GESTURES
5713 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5714 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5715 (when - mPointerGesture.tapDownTime) * 0.000001f);
5716 } else {
5717 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5718 }
5719#endif
5720 }
5721 }
5722
5723 mPointerVelocityControl.reset();
5724
5725 if (!tapped) {
5726#if DEBUG_GESTURES
5727 ALOGD("Gestures: NEUTRAL");
5728#endif
5729 mPointerGesture.activeGestureId = -1;
5730 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5731 mPointerGesture.currentGestureIdBits.clear();
5732 }
5733 } else if (currentFingerCount == 1) {
5734 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5735 // The pointer follows the active touch point.
5736 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5737 // When in TAP_DRAG, emit MOVE events at the pointer location.
5738 ALOG_ASSERT(activeTouchId >= 0);
5739
5740 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5741 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5742 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5743 float x, y;
5744 mPointerController->getPosition(&x, &y);
5745 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5746 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5747 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5748 } else {
5749#if DEBUG_GESTURES
5750 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5751 x - mPointerGesture.tapX,
5752 y - mPointerGesture.tapY);
5753#endif
5754 }
5755 } else {
5756#if DEBUG_GESTURES
5757 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5758 (when - mPointerGesture.tapUpTime) * 0.000001f);
5759#endif
5760 }
5761 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5762 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5763 }
5764
Jun Mukaifa1706a2015-12-03 01:14:46 -08005765 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005766 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005767 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005768 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005770 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005771 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5772 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773
5774 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5775 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5776
5777 // Move the pointer using a relative motion.
5778 // When using spots, the hover or drag will occur at the position of the anchor spot.
5779 mPointerController->move(deltaX, deltaY);
5780 } else {
5781 mPointerVelocityControl.reset();
5782 }
5783
5784 bool down;
5785 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5786#if DEBUG_GESTURES
5787 ALOGD("Gestures: TAP_DRAG");
5788#endif
5789 down = true;
5790 } else {
5791#if DEBUG_GESTURES
5792 ALOGD("Gestures: HOVER");
5793#endif
5794 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5795 *outFinishPreviousGesture = true;
5796 }
5797 mPointerGesture.activeGestureId = 0;
5798 down = false;
5799 }
5800
5801 float x, y;
5802 mPointerController->getPosition(&x, &y);
5803
5804 mPointerGesture.currentGestureIdBits.clear();
5805 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5806 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5807 mPointerGesture.currentGestureProperties[0].clear();
5808 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5809 mPointerGesture.currentGestureProperties[0].toolType =
5810 AMOTION_EVENT_TOOL_TYPE_FINGER;
5811 mPointerGesture.currentGestureCoords[0].clear();
5812 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5813 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5814 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5815 down ? 1.0f : 0.0f);
5816
5817 if (lastFingerCount == 0 && currentFingerCount != 0) {
5818 mPointerGesture.resetTap();
5819 mPointerGesture.tapDownTime = when;
5820 mPointerGesture.tapX = x;
5821 mPointerGesture.tapY = y;
5822 }
5823 } else {
5824 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5825 // We need to provide feedback for each finger that goes down so we cannot wait
5826 // for the fingers to move before deciding what to do.
5827 //
5828 // The ambiguous case is deciding what to do when there are two fingers down but they
5829 // have not moved enough to determine whether they are part of a drag or part of a
5830 // freeform gesture, or just a press or long-press at the pointer location.
5831 //
5832 // When there are two fingers we start with the PRESS hypothesis and we generate a
5833 // down at the pointer location.
5834 //
5835 // When the two fingers move enough or when additional fingers are added, we make
5836 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5837 ALOG_ASSERT(activeTouchId >= 0);
5838
5839 bool settled = when >= mPointerGesture.firstTouchTime
5840 + mConfig.pointerGestureMultitouchSettleInterval;
5841 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5842 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5843 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5844 *outFinishPreviousGesture = true;
5845 } else if (!settled && currentFingerCount > lastFingerCount) {
5846 // Additional pointers have gone down but not yet settled.
5847 // Reset the gesture.
5848#if DEBUG_GESTURES
5849 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5850 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5851 + mConfig.pointerGestureMultitouchSettleInterval - when)
5852 * 0.000001f);
5853#endif
5854 *outCancelPreviousGesture = true;
5855 } else {
5856 // Continue previous gesture.
5857 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5858 }
5859
5860 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5861 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5862 mPointerGesture.activeGestureId = 0;
5863 mPointerGesture.referenceIdBits.clear();
5864 mPointerVelocityControl.reset();
5865
5866 // Use the centroid and pointer location as the reference points for the gesture.
5867#if DEBUG_GESTURES
5868 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5869 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5870 + mConfig.pointerGestureMultitouchSettleInterval - when)
5871 * 0.000001f);
5872#endif
Michael Wright842500e2015-03-13 17:32:02 -07005873 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874 &mPointerGesture.referenceTouchX,
5875 &mPointerGesture.referenceTouchY);
5876 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5877 &mPointerGesture.referenceGestureY);
5878 }
5879
5880 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005881 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5883 uint32_t id = idBits.clearFirstMarkedBit();
5884 mPointerGesture.referenceDeltas[id].dx = 0;
5885 mPointerGesture.referenceDeltas[id].dy = 0;
5886 }
Michael Wright842500e2015-03-13 17:32:02 -07005887 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888
5889 // Add delta for all fingers and calculate a common movement delta.
5890 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005891 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5892 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5894 bool first = (idBits == commonIdBits);
5895 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005896 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5897 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5899 delta.dx += cpd.x - lpd.x;
5900 delta.dy += cpd.y - lpd.y;
5901
5902 if (first) {
5903 commonDeltaX = delta.dx;
5904 commonDeltaY = delta.dy;
5905 } else {
5906 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5907 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5908 }
5909 }
5910
5911 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5912 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5913 float dist[MAX_POINTER_ID + 1];
5914 int32_t distOverThreshold = 0;
5915 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5916 uint32_t id = idBits.clearFirstMarkedBit();
5917 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5918 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5919 delta.dy * mPointerYZoomScale);
5920 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5921 distOverThreshold += 1;
5922 }
5923 }
5924
5925 // Only transition when at least two pointers have moved further than
5926 // the minimum distance threshold.
5927 if (distOverThreshold >= 2) {
5928 if (currentFingerCount > 2) {
5929 // There are more than two pointers, switch to FREEFORM.
5930#if DEBUG_GESTURES
5931 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5932 currentFingerCount);
5933#endif
5934 *outCancelPreviousGesture = true;
5935 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5936 } else {
5937 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005938 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 uint32_t id1 = idBits.clearFirstMarkedBit();
5940 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005941 const RawPointerData::Pointer& p1 =
5942 mCurrentRawState.rawPointerData.pointerForId(id1);
5943 const RawPointerData::Pointer& p2 =
5944 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005945 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5946 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5947 // There are two pointers but they are too far apart for a SWIPE,
5948 // switch to FREEFORM.
5949#if DEBUG_GESTURES
5950 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5951 mutualDistance, mPointerGestureMaxSwipeWidth);
5952#endif
5953 *outCancelPreviousGesture = true;
5954 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5955 } else {
5956 // There are two pointers. Wait for both pointers to start moving
5957 // before deciding whether this is a SWIPE or FREEFORM gesture.
5958 float dist1 = dist[id1];
5959 float dist2 = dist[id2];
5960 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5961 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5962 // Calculate the dot product of the displacement vectors.
5963 // When the vectors are oriented in approximately the same direction,
5964 // the angle betweeen them is near zero and the cosine of the angle
5965 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5966 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5967 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5968 float dx1 = delta1.dx * mPointerXZoomScale;
5969 float dy1 = delta1.dy * mPointerYZoomScale;
5970 float dx2 = delta2.dx * mPointerXZoomScale;
5971 float dy2 = delta2.dy * mPointerYZoomScale;
5972 float dot = dx1 * dx2 + dy1 * dy2;
5973 float cosine = dot / (dist1 * dist2); // denominator always > 0
5974 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5975 // Pointers are moving in the same direction. Switch to SWIPE.
5976#if DEBUG_GESTURES
5977 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5978 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5979 "cosine %0.3f >= %0.3f",
5980 dist1, mConfig.pointerGestureMultitouchMinDistance,
5981 dist2, mConfig.pointerGestureMultitouchMinDistance,
5982 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5983#endif
5984 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5985 } else {
5986 // Pointers are moving in different directions. Switch to FREEFORM.
5987#if DEBUG_GESTURES
5988 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5989 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5990 "cosine %0.3f < %0.3f",
5991 dist1, mConfig.pointerGestureMultitouchMinDistance,
5992 dist2, mConfig.pointerGestureMultitouchMinDistance,
5993 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5994#endif
5995 *outCancelPreviousGesture = true;
5996 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5997 }
5998 }
5999 }
6000 }
6001 }
6002 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6003 // Switch from SWIPE to FREEFORM if additional pointers go down.
6004 // Cancel previous gesture.
6005 if (currentFingerCount > 2) {
6006#if DEBUG_GESTURES
6007 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6008 currentFingerCount);
6009#endif
6010 *outCancelPreviousGesture = true;
6011 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6012 }
6013 }
6014
6015 // Move the reference points based on the overall group motion of the fingers
6016 // except in PRESS mode while waiting for a transition to occur.
6017 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6018 && (commonDeltaX || commonDeltaY)) {
6019 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6020 uint32_t id = idBits.clearFirstMarkedBit();
6021 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6022 delta.dx = 0;
6023 delta.dy = 0;
6024 }
6025
6026 mPointerGesture.referenceTouchX += commonDeltaX;
6027 mPointerGesture.referenceTouchY += commonDeltaY;
6028
6029 commonDeltaX *= mPointerXMovementScale;
6030 commonDeltaY *= mPointerYMovementScale;
6031
6032 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6033 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6034
6035 mPointerGesture.referenceGestureX += commonDeltaX;
6036 mPointerGesture.referenceGestureY += commonDeltaY;
6037 }
6038
6039 // Report gestures.
6040 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6041 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6042 // PRESS or SWIPE mode.
6043#if DEBUG_GESTURES
6044 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6045 "activeGestureId=%d, currentTouchPointerCount=%d",
6046 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6047#endif
6048 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6049
6050 mPointerGesture.currentGestureIdBits.clear();
6051 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6052 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6053 mPointerGesture.currentGestureProperties[0].clear();
6054 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6055 mPointerGesture.currentGestureProperties[0].toolType =
6056 AMOTION_EVENT_TOOL_TYPE_FINGER;
6057 mPointerGesture.currentGestureCoords[0].clear();
6058 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6059 mPointerGesture.referenceGestureX);
6060 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6061 mPointerGesture.referenceGestureY);
6062 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6063 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6064 // FREEFORM mode.
6065#if DEBUG_GESTURES
6066 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6067 "activeGestureId=%d, currentTouchPointerCount=%d",
6068 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6069#endif
6070 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6071
6072 mPointerGesture.currentGestureIdBits.clear();
6073
6074 BitSet32 mappedTouchIdBits;
6075 BitSet32 usedGestureIdBits;
6076 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6077 // Initially, assign the active gesture id to the active touch point
6078 // if there is one. No other touch id bits are mapped yet.
6079 if (!*outCancelPreviousGesture) {
6080 mappedTouchIdBits.markBit(activeTouchId);
6081 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6082 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6083 mPointerGesture.activeGestureId;
6084 } else {
6085 mPointerGesture.activeGestureId = -1;
6086 }
6087 } else {
6088 // Otherwise, assume we mapped all touches from the previous frame.
6089 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006090 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6091 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6093
6094 // Check whether we need to choose a new active gesture id because the
6095 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006096 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6097 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006098 !upTouchIdBits.isEmpty(); ) {
6099 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6100 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6101 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6102 mPointerGesture.activeGestureId = -1;
6103 break;
6104 }
6105 }
6106 }
6107
6108#if DEBUG_GESTURES
6109 ALOGD("Gestures: FREEFORM follow up "
6110 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6111 "activeGestureId=%d",
6112 mappedTouchIdBits.value, usedGestureIdBits.value,
6113 mPointerGesture.activeGestureId);
6114#endif
6115
Michael Wright842500e2015-03-13 17:32:02 -07006116 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006117 for (uint32_t i = 0; i < currentFingerCount; i++) {
6118 uint32_t touchId = idBits.clearFirstMarkedBit();
6119 uint32_t gestureId;
6120 if (!mappedTouchIdBits.hasBit(touchId)) {
6121 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6122 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6123#if DEBUG_GESTURES
6124 ALOGD("Gestures: FREEFORM "
6125 "new mapping for touch id %d -> gesture id %d",
6126 touchId, gestureId);
6127#endif
6128 } else {
6129 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6130#if DEBUG_GESTURES
6131 ALOGD("Gestures: FREEFORM "
6132 "existing mapping for touch id %d -> gesture id %d",
6133 touchId, gestureId);
6134#endif
6135 }
6136 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6137 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6138
6139 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006140 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006141 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6142 * mPointerXZoomScale;
6143 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6144 * mPointerYZoomScale;
6145 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6146
6147 mPointerGesture.currentGestureProperties[i].clear();
6148 mPointerGesture.currentGestureProperties[i].id = gestureId;
6149 mPointerGesture.currentGestureProperties[i].toolType =
6150 AMOTION_EVENT_TOOL_TYPE_FINGER;
6151 mPointerGesture.currentGestureCoords[i].clear();
6152 mPointerGesture.currentGestureCoords[i].setAxisValue(
6153 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6154 mPointerGesture.currentGestureCoords[i].setAxisValue(
6155 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6156 mPointerGesture.currentGestureCoords[i].setAxisValue(
6157 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6158 }
6159
6160 if (mPointerGesture.activeGestureId < 0) {
6161 mPointerGesture.activeGestureId =
6162 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6163#if DEBUG_GESTURES
6164 ALOGD("Gestures: FREEFORM new "
6165 "activeGestureId=%d", mPointerGesture.activeGestureId);
6166#endif
6167 }
6168 }
6169 }
6170
Michael Wright842500e2015-03-13 17:32:02 -07006171 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006172
6173#if DEBUG_GESTURES
6174 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6175 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6176 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6177 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6178 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6179 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6180 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6181 uint32_t id = idBits.clearFirstMarkedBit();
6182 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6183 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6184 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6185 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6186 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6187 id, index, properties.toolType,
6188 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6189 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6190 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6191 }
6192 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6193 uint32_t id = idBits.clearFirstMarkedBit();
6194 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6195 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6196 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6197 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6198 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6199 id, index, properties.toolType,
6200 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6201 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6202 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6203 }
6204#endif
6205 return true;
6206}
6207
6208void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6209 mPointerSimple.currentCoords.clear();
6210 mPointerSimple.currentProperties.clear();
6211
6212 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006213 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6214 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6215 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6216 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6217 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 mPointerController->setPosition(x, y);
6219
Michael Wright842500e2015-03-13 17:32:02 -07006220 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006221 down = !hovering;
6222
6223 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006224 mPointerSimple.currentCoords.copyFrom(
6225 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6227 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6228 mPointerSimple.currentProperties.id = 0;
6229 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006230 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231 } else {
6232 down = false;
6233 hovering = false;
6234 }
6235
6236 dispatchPointerSimple(when, policyFlags, down, hovering);
6237}
6238
6239void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6240 abortPointerSimple(when, policyFlags);
6241}
6242
6243void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6244 mPointerSimple.currentCoords.clear();
6245 mPointerSimple.currentProperties.clear();
6246
6247 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006248 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6249 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6250 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006251 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006252 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6253 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006254 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006255 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006257 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006258 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006259 * mPointerYMovementScale;
6260
6261 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6262 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6263
6264 mPointerController->move(deltaX, deltaY);
6265 } else {
6266 mPointerVelocityControl.reset();
6267 }
6268
Michael Wright842500e2015-03-13 17:32:02 -07006269 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006270 hovering = !down;
6271
6272 float x, y;
6273 mPointerController->getPosition(&x, &y);
6274 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006275 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006276 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6277 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6278 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6279 hovering ? 0.0f : 1.0f);
6280 mPointerSimple.currentProperties.id = 0;
6281 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006282 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006283 } else {
6284 mPointerVelocityControl.reset();
6285
6286 down = false;
6287 hovering = false;
6288 }
6289
6290 dispatchPointerSimple(when, policyFlags, down, hovering);
6291}
6292
6293void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6294 abortPointerSimple(when, policyFlags);
6295
6296 mPointerVelocityControl.reset();
6297}
6298
6299void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6300 bool down, bool hovering) {
6301 int32_t metaState = getContext()->getGlobalMetaState();
6302
6303 if (mPointerController != NULL) {
6304 if (down || hovering) {
6305 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6306 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006307 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6309 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6310 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6311 }
6312 }
6313
6314 if (mPointerSimple.down && !down) {
6315 mPointerSimple.down = false;
6316
6317 // Send up.
6318 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006319 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006320 mViewport.displayId,
6321 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6322 mOrientedXPrecision, mOrientedYPrecision,
6323 mPointerSimple.downTime);
6324 getListener()->notifyMotion(&args);
6325 }
6326
6327 if (mPointerSimple.hovering && !hovering) {
6328 mPointerSimple.hovering = false;
6329
6330 // Send hover exit.
6331 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006332 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006333 mViewport.displayId,
6334 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6335 mOrientedXPrecision, mOrientedYPrecision,
6336 mPointerSimple.downTime);
6337 getListener()->notifyMotion(&args);
6338 }
6339
6340 if (down) {
6341 if (!mPointerSimple.down) {
6342 mPointerSimple.down = true;
6343 mPointerSimple.downTime = when;
6344
6345 // Send down.
6346 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006347 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006348 mViewport.displayId,
6349 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6350 mOrientedXPrecision, mOrientedYPrecision,
6351 mPointerSimple.downTime);
6352 getListener()->notifyMotion(&args);
6353 }
6354
6355 // Send move.
6356 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006357 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006358 mViewport.displayId,
6359 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6360 mOrientedXPrecision, mOrientedYPrecision,
6361 mPointerSimple.downTime);
6362 getListener()->notifyMotion(&args);
6363 }
6364
6365 if (hovering) {
6366 if (!mPointerSimple.hovering) {
6367 mPointerSimple.hovering = true;
6368
6369 // Send hover enter.
6370 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006371 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006372 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373 mViewport.displayId,
6374 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6375 mOrientedXPrecision, mOrientedYPrecision,
6376 mPointerSimple.downTime);
6377 getListener()->notifyMotion(&args);
6378 }
6379
6380 // Send hover move.
6381 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006382 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006383 mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006384 mViewport.displayId,
6385 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6386 mOrientedXPrecision, mOrientedYPrecision,
6387 mPointerSimple.downTime);
6388 getListener()->notifyMotion(&args);
6389 }
6390
Michael Wright842500e2015-03-13 17:32:02 -07006391 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6392 float vscroll = mCurrentRawState.rawVScroll;
6393 float hscroll = mCurrentRawState.rawHScroll;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006394 mWheelYVelocityControl.move(when, NULL, &vscroll);
6395 mWheelXVelocityControl.move(when, &hscroll, NULL);
6396
6397 // Send scroll.
6398 PointerCoords pointerCoords;
6399 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6400 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6401 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6402
6403 NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006404 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006405 mViewport.displayId,
6406 1, &mPointerSimple.currentProperties, &pointerCoords,
6407 mOrientedXPrecision, mOrientedYPrecision,
6408 mPointerSimple.downTime);
6409 getListener()->notifyMotion(&args);
6410 }
6411
6412 // Save state.
6413 if (down || hovering) {
6414 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6415 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6416 } else {
6417 mPointerSimple.reset();
6418 }
6419}
6420
6421void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6422 mPointerSimple.currentCoords.clear();
6423 mPointerSimple.currentProperties.clear();
6424
6425 dispatchPointerSimple(when, policyFlags, false, false);
6426}
6427
6428void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006429 int32_t action, int32_t actionButton, int32_t flags,
6430 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006431 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006432 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6433 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006434 PointerCoords pointerCoords[MAX_POINTERS];
6435 PointerProperties pointerProperties[MAX_POINTERS];
6436 uint32_t pointerCount = 0;
6437 while (!idBits.isEmpty()) {
6438 uint32_t id = idBits.clearFirstMarkedBit();
6439 uint32_t index = idToIndex[id];
6440 pointerProperties[pointerCount].copyFrom(properties[index]);
6441 pointerCoords[pointerCount].copyFrom(coords[index]);
6442
6443 if (changedId >= 0 && id == uint32_t(changedId)) {
6444 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6445 }
6446
6447 pointerCount += 1;
6448 }
6449
6450 ALOG_ASSERT(pointerCount != 0);
6451
6452 if (changedId >= 0 && pointerCount == 1) {
6453 // Replace initial down and final up action.
6454 // We can compare the action without masking off the changed pointer index
6455 // because we know the index is 0.
6456 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6457 action = AMOTION_EVENT_ACTION_DOWN;
6458 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6459 action = AMOTION_EVENT_ACTION_UP;
6460 } else {
6461 // Can't happen.
6462 ALOG_ASSERT(false);
6463 }
6464 }
6465
6466 NotifyMotionArgs args(when, getDeviceId(), source, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006467 action, actionButton, flags, metaState, buttonState, edgeFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006468 mViewport.displayId, pointerCount, pointerProperties, pointerCoords,
6469 xPrecision, yPrecision, downTime);
6470 getListener()->notifyMotion(&args);
6471}
6472
6473bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6474 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6475 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6476 BitSet32 idBits) const {
6477 bool changed = false;
6478 while (!idBits.isEmpty()) {
6479 uint32_t id = idBits.clearFirstMarkedBit();
6480 uint32_t inIndex = inIdToIndex[id];
6481 uint32_t outIndex = outIdToIndex[id];
6482
6483 const PointerProperties& curInProperties = inProperties[inIndex];
6484 const PointerCoords& curInCoords = inCoords[inIndex];
6485 PointerProperties& curOutProperties = outProperties[outIndex];
6486 PointerCoords& curOutCoords = outCoords[outIndex];
6487
6488 if (curInProperties != curOutProperties) {
6489 curOutProperties.copyFrom(curInProperties);
6490 changed = true;
6491 }
6492
6493 if (curInCoords != curOutCoords) {
6494 curOutCoords.copyFrom(curInCoords);
6495 changed = true;
6496 }
6497 }
6498 return changed;
6499}
6500
6501void TouchInputMapper::fadePointer() {
6502 if (mPointerController != NULL) {
6503 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6504 }
6505}
6506
Jeff Brownc9aa6282015-02-11 19:03:28 -08006507void TouchInputMapper::cancelTouch(nsecs_t when) {
6508 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006509 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006510}
6511
Michael Wrightd02c5b62014-02-10 15:10:22 -08006512bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
6513 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
6514 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue;
6515}
6516
6517const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6518 int32_t x, int32_t y) {
6519 size_t numVirtualKeys = mVirtualKeys.size();
6520 for (size_t i = 0; i < numVirtualKeys; i++) {
6521 const VirtualKey& virtualKey = mVirtualKeys[i];
6522
6523#if DEBUG_VIRTUAL_KEYS
6524 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6525 "left=%d, top=%d, right=%d, bottom=%d",
6526 x, y,
6527 virtualKey.keyCode, virtualKey.scanCode,
6528 virtualKey.hitLeft, virtualKey.hitTop,
6529 virtualKey.hitRight, virtualKey.hitBottom);
6530#endif
6531
6532 if (virtualKey.isHit(x, y)) {
6533 return & virtualKey;
6534 }
6535 }
6536
6537 return NULL;
6538}
6539
Michael Wright842500e2015-03-13 17:32:02 -07006540void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6541 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6542 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006543
Michael Wright842500e2015-03-13 17:32:02 -07006544 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006545
6546 if (currentPointerCount == 0) {
6547 // No pointers to assign.
6548 return;
6549 }
6550
6551 if (lastPointerCount == 0) {
6552 // All pointers are new.
6553 for (uint32_t i = 0; i < currentPointerCount; i++) {
6554 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006555 current->rawPointerData.pointers[i].id = id;
6556 current->rawPointerData.idToIndex[id] = i;
6557 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006558 }
6559 return;
6560 }
6561
6562 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006563 && current->rawPointerData.pointers[0].toolType
6564 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006565 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006566 uint32_t id = last->rawPointerData.pointers[0].id;
6567 current->rawPointerData.pointers[0].id = id;
6568 current->rawPointerData.idToIndex[id] = 0;
6569 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006570 return;
6571 }
6572
6573 // General case.
6574 // We build a heap of squared euclidean distances between current and last pointers
6575 // associated with the current and last pointer indices. Then, we find the best
6576 // match (by distance) for each current pointer.
6577 // The pointers must have the same tool type but it is possible for them to
6578 // transition from hovering to touching or vice-versa while retaining the same id.
6579 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6580
6581 uint32_t heapSize = 0;
6582 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6583 currentPointerIndex++) {
6584 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6585 lastPointerIndex++) {
6586 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006587 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006588 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006589 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006590 if (currentPointer.toolType == lastPointer.toolType) {
6591 int64_t deltaX = currentPointer.x - lastPointer.x;
6592 int64_t deltaY = currentPointer.y - lastPointer.y;
6593
6594 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6595
6596 // Insert new element into the heap (sift up).
6597 heap[heapSize].currentPointerIndex = currentPointerIndex;
6598 heap[heapSize].lastPointerIndex = lastPointerIndex;
6599 heap[heapSize].distance = distance;
6600 heapSize += 1;
6601 }
6602 }
6603 }
6604
6605 // Heapify
6606 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6607 startIndex -= 1;
6608 for (uint32_t parentIndex = startIndex; ;) {
6609 uint32_t childIndex = parentIndex * 2 + 1;
6610 if (childIndex >= heapSize) {
6611 break;
6612 }
6613
6614 if (childIndex + 1 < heapSize
6615 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6616 childIndex += 1;
6617 }
6618
6619 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6620 break;
6621 }
6622
6623 swap(heap[parentIndex], heap[childIndex]);
6624 parentIndex = childIndex;
6625 }
6626 }
6627
6628#if DEBUG_POINTER_ASSIGNMENT
6629 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6630 for (size_t i = 0; i < heapSize; i++) {
6631 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6632 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6633 heap[i].distance);
6634 }
6635#endif
6636
6637 // Pull matches out by increasing order of distance.
6638 // To avoid reassigning pointers that have already been matched, the loop keeps track
6639 // of which last and current pointers have been matched using the matchedXXXBits variables.
6640 // It also tracks the used pointer id bits.
6641 BitSet32 matchedLastBits(0);
6642 BitSet32 matchedCurrentBits(0);
6643 BitSet32 usedIdBits(0);
6644 bool first = true;
6645 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6646 while (heapSize > 0) {
6647 if (first) {
6648 // The first time through the loop, we just consume the root element of
6649 // the heap (the one with smallest distance).
6650 first = false;
6651 } else {
6652 // Previous iterations consumed the root element of the heap.
6653 // Pop root element off of the heap (sift down).
6654 heap[0] = heap[heapSize];
6655 for (uint32_t parentIndex = 0; ;) {
6656 uint32_t childIndex = parentIndex * 2 + 1;
6657 if (childIndex >= heapSize) {
6658 break;
6659 }
6660
6661 if (childIndex + 1 < heapSize
6662 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6663 childIndex += 1;
6664 }
6665
6666 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6667 break;
6668 }
6669
6670 swap(heap[parentIndex], heap[childIndex]);
6671 parentIndex = childIndex;
6672 }
6673
6674#if DEBUG_POINTER_ASSIGNMENT
6675 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6676 for (size_t i = 0; i < heapSize; i++) {
6677 ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
6678 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6679 heap[i].distance);
6680 }
6681#endif
6682 }
6683
6684 heapSize -= 1;
6685
6686 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6687 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6688
6689 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6690 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6691
6692 matchedCurrentBits.markBit(currentPointerIndex);
6693 matchedLastBits.markBit(lastPointerIndex);
6694
Michael Wright842500e2015-03-13 17:32:02 -07006695 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6696 current->rawPointerData.pointers[currentPointerIndex].id = id;
6697 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6698 current->rawPointerData.markIdBit(id,
6699 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006700 usedIdBits.markBit(id);
6701
6702#if DEBUG_POINTER_ASSIGNMENT
6703 ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
6704 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6705#endif
6706 break;
6707 }
6708 }
6709
6710 // Assign fresh ids to pointers that were not matched in the process.
6711 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6712 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6713 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6714
Michael Wright842500e2015-03-13 17:32:02 -07006715 current->rawPointerData.pointers[currentPointerIndex].id = id;
6716 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6717 current->rawPointerData.markIdBit(id,
6718 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006719
6720#if DEBUG_POINTER_ASSIGNMENT
6721 ALOGD("assignPointerIds - assigned: cur=%d, id=%d",
6722 currentPointerIndex, id);
6723#endif
6724 }
6725}
6726
6727int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6728 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6729 return AKEY_STATE_VIRTUAL;
6730 }
6731
6732 size_t numVirtualKeys = mVirtualKeys.size();
6733 for (size_t i = 0; i < numVirtualKeys; i++) {
6734 const VirtualKey& virtualKey = mVirtualKeys[i];
6735 if (virtualKey.keyCode == keyCode) {
6736 return AKEY_STATE_UP;
6737 }
6738 }
6739
6740 return AKEY_STATE_UNKNOWN;
6741}
6742
6743int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6744 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6745 return AKEY_STATE_VIRTUAL;
6746 }
6747
6748 size_t numVirtualKeys = mVirtualKeys.size();
6749 for (size_t i = 0; i < numVirtualKeys; i++) {
6750 const VirtualKey& virtualKey = mVirtualKeys[i];
6751 if (virtualKey.scanCode == scanCode) {
6752 return AKEY_STATE_UP;
6753 }
6754 }
6755
6756 return AKEY_STATE_UNKNOWN;
6757}
6758
6759bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6760 const int32_t* keyCodes, uint8_t* outFlags) {
6761 size_t numVirtualKeys = mVirtualKeys.size();
6762 for (size_t i = 0; i < numVirtualKeys; i++) {
6763 const VirtualKey& virtualKey = mVirtualKeys[i];
6764
6765 for (size_t i = 0; i < numCodes; i++) {
6766 if (virtualKey.keyCode == keyCodes[i]) {
6767 outFlags[i] = 1;
6768 }
6769 }
6770 }
6771
6772 return true;
6773}
6774
6775
6776// --- SingleTouchInputMapper ---
6777
6778SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6779 TouchInputMapper(device) {
6780}
6781
6782SingleTouchInputMapper::~SingleTouchInputMapper() {
6783}
6784
6785void SingleTouchInputMapper::reset(nsecs_t when) {
6786 mSingleTouchMotionAccumulator.reset(getDevice());
6787
6788 TouchInputMapper::reset(when);
6789}
6790
6791void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6792 TouchInputMapper::process(rawEvent);
6793
6794 mSingleTouchMotionAccumulator.process(rawEvent);
6795}
6796
Michael Wright842500e2015-03-13 17:32:02 -07006797void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006798 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006799 outState->rawPointerData.pointerCount = 1;
6800 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006801
6802 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6803 && (mTouchButtonAccumulator.isHovering()
6804 || (mRawPointerAxes.pressure.valid
6805 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006806 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006807
Michael Wright842500e2015-03-13 17:32:02 -07006808 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006809 outPointer.id = 0;
6810 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6811 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6812 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6813 outPointer.touchMajor = 0;
6814 outPointer.touchMinor = 0;
6815 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6816 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6817 outPointer.orientation = 0;
6818 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6819 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6820 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6821 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6822 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6823 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6824 }
6825 outPointer.isHovering = isHovering;
6826 }
6827}
6828
6829void SingleTouchInputMapper::configureRawPointerAxes() {
6830 TouchInputMapper::configureRawPointerAxes();
6831
6832 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6833 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6834 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6835 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6836 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6837 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6838 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6839}
6840
6841bool SingleTouchInputMapper::hasStylus() const {
6842 return mTouchButtonAccumulator.hasStylus();
6843}
6844
6845
6846// --- MultiTouchInputMapper ---
6847
6848MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6849 TouchInputMapper(device) {
6850}
6851
6852MultiTouchInputMapper::~MultiTouchInputMapper() {
6853}
6854
6855void MultiTouchInputMapper::reset(nsecs_t when) {
6856 mMultiTouchMotionAccumulator.reset(getDevice());
6857
6858 mPointerIdBits.clear();
6859
6860 TouchInputMapper::reset(when);
6861}
6862
6863void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6864 TouchInputMapper::process(rawEvent);
6865
6866 mMultiTouchMotionAccumulator.process(rawEvent);
6867}
6868
Michael Wright842500e2015-03-13 17:32:02 -07006869void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006870 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6871 size_t outCount = 0;
6872 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006873 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006874
6875 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6876 const MultiTouchMotionAccumulator::Slot* inSlot =
6877 mMultiTouchMotionAccumulator.getSlot(inIndex);
6878 if (!inSlot->isInUse()) {
6879 continue;
6880 }
6881
6882 if (outCount >= MAX_POINTERS) {
6883#if DEBUG_POINTERS
6884 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6885 "ignoring the rest.",
6886 getDeviceName().string(), MAX_POINTERS);
6887#endif
6888 break; // too many fingers!
6889 }
6890
Michael Wright842500e2015-03-13 17:32:02 -07006891 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006892 outPointer.x = inSlot->getX();
6893 outPointer.y = inSlot->getY();
6894 outPointer.pressure = inSlot->getPressure();
6895 outPointer.touchMajor = inSlot->getTouchMajor();
6896 outPointer.touchMinor = inSlot->getTouchMinor();
6897 outPointer.toolMajor = inSlot->getToolMajor();
6898 outPointer.toolMinor = inSlot->getToolMinor();
6899 outPointer.orientation = inSlot->getOrientation();
6900 outPointer.distance = inSlot->getDistance();
6901 outPointer.tiltX = 0;
6902 outPointer.tiltY = 0;
6903
6904 outPointer.toolType = inSlot->getToolType();
6905 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6906 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6907 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6908 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6909 }
6910 }
6911
6912 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6913 && (mTouchButtonAccumulator.isHovering()
6914 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6915 outPointer.isHovering = isHovering;
6916
6917 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006918 if (mHavePointerIds) {
6919 int32_t trackingId = inSlot->getTrackingId();
6920 int32_t id = -1;
6921 if (trackingId >= 0) {
6922 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6923 uint32_t n = idBits.clearFirstMarkedBit();
6924 if (mPointerTrackingIdMap[n] == trackingId) {
6925 id = n;
6926 }
6927 }
6928
6929 if (id < 0 && !mPointerIdBits.isFull()) {
6930 id = mPointerIdBits.markFirstUnmarkedBit();
6931 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006932 }
Michael Wright842500e2015-03-13 17:32:02 -07006933 }
gaoshang1a632de2016-08-24 10:23:50 +08006934 if (id < 0) {
6935 mHavePointerIds = false;
6936 outState->rawPointerData.clearIdBits();
6937 newPointerIdBits.clear();
6938 } else {
6939 outPointer.id = id;
6940 outState->rawPointerData.idToIndex[id] = outCount;
6941 outState->rawPointerData.markIdBit(id, isHovering);
6942 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006943 }
Michael Wright842500e2015-03-13 17:32:02 -07006944 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006945 outCount += 1;
6946 }
6947
Michael Wright842500e2015-03-13 17:32:02 -07006948 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006949 mPointerIdBits = newPointerIdBits;
6950
6951 mMultiTouchMotionAccumulator.finishSync();
6952}
6953
6954void MultiTouchInputMapper::configureRawPointerAxes() {
6955 TouchInputMapper::configureRawPointerAxes();
6956
6957 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6958 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6959 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6960 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6961 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6962 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6963 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6964 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6965 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6966 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6967 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6968
6969 if (mRawPointerAxes.trackingId.valid
6970 && mRawPointerAxes.slot.valid
6971 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6972 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6973 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006974 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6975 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08006976 getDeviceName().string(), slotCount, MAX_SLOTS);
6977 slotCount = MAX_SLOTS;
6978 }
6979 mMultiTouchMotionAccumulator.configure(getDevice(),
6980 slotCount, true /*usingSlotsProtocol*/);
6981 } else {
6982 mMultiTouchMotionAccumulator.configure(getDevice(),
6983 MAX_POINTERS, false /*usingSlotsProtocol*/);
6984 }
6985}
6986
6987bool MultiTouchInputMapper::hasStylus() const {
6988 return mMultiTouchMotionAccumulator.hasStylus()
6989 || mTouchButtonAccumulator.hasStylus();
6990}
6991
Michael Wright842500e2015-03-13 17:32:02 -07006992// --- ExternalStylusInputMapper
6993
6994ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6995 InputMapper(device) {
6996
6997}
6998
6999uint32_t ExternalStylusInputMapper::getSources() {
7000 return AINPUT_SOURCE_STYLUS;
7001}
7002
7003void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7004 InputMapper::populateDeviceInfo(info);
7005 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7006 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7007}
7008
7009void ExternalStylusInputMapper::dump(String8& dump) {
7010 dump.append(INDENT2 "External Stylus Input Mapper:\n");
7011 dump.append(INDENT3 "Raw Stylus Axes:\n");
7012 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
7013 dump.append(INDENT3 "Stylus State:\n");
7014 dumpStylusState(dump, mStylusState);
7015}
7016
7017void ExternalStylusInputMapper::configure(nsecs_t when,
7018 const InputReaderConfiguration* config, uint32_t changes) {
7019 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7020 mTouchButtonAccumulator.configure(getDevice());
7021}
7022
7023void ExternalStylusInputMapper::reset(nsecs_t when) {
7024 InputDevice* device = getDevice();
7025 mSingleTouchMotionAccumulator.reset(device);
7026 mTouchButtonAccumulator.reset(device);
7027 InputMapper::reset(when);
7028}
7029
7030void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7031 mSingleTouchMotionAccumulator.process(rawEvent);
7032 mTouchButtonAccumulator.process(rawEvent);
7033
7034 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7035 sync(rawEvent->when);
7036 }
7037}
7038
7039void ExternalStylusInputMapper::sync(nsecs_t when) {
7040 mStylusState.clear();
7041
7042 mStylusState.when = when;
7043
Michael Wright45ccacf2015-04-21 19:01:58 +01007044 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7045 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7046 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7047 }
7048
Michael Wright842500e2015-03-13 17:32:02 -07007049 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7050 if (mRawPressureAxis.valid) {
7051 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7052 } else if (mTouchButtonAccumulator.isToolActive()) {
7053 mStylusState.pressure = 1.0f;
7054 } else {
7055 mStylusState.pressure = 0.0f;
7056 }
7057
7058 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007059
7060 mContext->dispatchExternalStylusState(mStylusState);
7061}
7062
Michael Wrightd02c5b62014-02-10 15:10:22 -08007063
7064// --- JoystickInputMapper ---
7065
7066JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7067 InputMapper(device) {
7068}
7069
7070JoystickInputMapper::~JoystickInputMapper() {
7071}
7072
7073uint32_t JoystickInputMapper::getSources() {
7074 return AINPUT_SOURCE_JOYSTICK;
7075}
7076
7077void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7078 InputMapper::populateDeviceInfo(info);
7079
7080 for (size_t i = 0; i < mAxes.size(); i++) {
7081 const Axis& axis = mAxes.valueAt(i);
7082 addMotionRange(axis.axisInfo.axis, axis, info);
7083
7084 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7085 addMotionRange(axis.axisInfo.highAxis, axis, info);
7086
7087 }
7088 }
7089}
7090
7091void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7092 InputDeviceInfo* info) {
7093 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7094 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7095 /* In order to ease the transition for developers from using the old axes
7096 * to the newer, more semantically correct axes, we'll continue to register
7097 * the old axes as duplicates of their corresponding new ones. */
7098 int32_t compatAxis = getCompatAxis(axisId);
7099 if (compatAxis >= 0) {
7100 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7101 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7102 }
7103}
7104
7105/* A mapping from axes the joystick actually has to the axes that should be
7106 * artificially created for compatibility purposes.
7107 * Returns -1 if no compatibility axis is needed. */
7108int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7109 switch(axis) {
7110 case AMOTION_EVENT_AXIS_LTRIGGER:
7111 return AMOTION_EVENT_AXIS_BRAKE;
7112 case AMOTION_EVENT_AXIS_RTRIGGER:
7113 return AMOTION_EVENT_AXIS_GAS;
7114 }
7115 return -1;
7116}
7117
7118void JoystickInputMapper::dump(String8& dump) {
7119 dump.append(INDENT2 "Joystick Input Mapper:\n");
7120
7121 dump.append(INDENT3 "Axes:\n");
7122 size_t numAxes = mAxes.size();
7123 for (size_t i = 0; i < numAxes; i++) {
7124 const Axis& axis = mAxes.valueAt(i);
7125 const char* label = getAxisLabel(axis.axisInfo.axis);
7126 if (label) {
7127 dump.appendFormat(INDENT4 "%s", label);
7128 } else {
7129 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
7130 }
7131 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7132 label = getAxisLabel(axis.axisInfo.highAxis);
7133 if (label) {
7134 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
7135 } else {
7136 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
7137 axis.axisInfo.splitValue);
7138 }
7139 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
7140 dump.append(" (invert)");
7141 }
7142
7143 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
7144 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7145 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
7146 "highScale=%0.5f, highOffset=%0.5f\n",
7147 axis.scale, axis.offset, axis.highScale, axis.highOffset);
7148 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
7149 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7150 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7151 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7152 }
7153}
7154
7155void JoystickInputMapper::configure(nsecs_t when,
7156 const InputReaderConfiguration* config, uint32_t changes) {
7157 InputMapper::configure(when, config, changes);
7158
7159 if (!changes) { // first time only
7160 // Collect all axes.
7161 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7162 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7163 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7164 continue; // axis must be claimed by a different device
7165 }
7166
7167 RawAbsoluteAxisInfo rawAxisInfo;
7168 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7169 if (rawAxisInfo.valid) {
7170 // Map axis.
7171 AxisInfo axisInfo;
7172 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7173 if (!explicitlyMapped) {
7174 // Axis is not explicitly mapped, will choose a generic axis later.
7175 axisInfo.mode = AxisInfo::MODE_NORMAL;
7176 axisInfo.axis = -1;
7177 }
7178
7179 // Apply flat override.
7180 int32_t rawFlat = axisInfo.flatOverride < 0
7181 ? rawAxisInfo.flat : axisInfo.flatOverride;
7182
7183 // Calculate scaling factors and limits.
7184 Axis axis;
7185 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7186 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7187 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7188 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7189 scale, 0.0f, highScale, 0.0f,
7190 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7191 rawAxisInfo.resolution * scale);
7192 } else if (isCenteredAxis(axisInfo.axis)) {
7193 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7194 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7195 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7196 scale, offset, scale, offset,
7197 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7198 rawAxisInfo.resolution * scale);
7199 } else {
7200 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7201 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7202 scale, 0.0f, scale, 0.0f,
7203 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7204 rawAxisInfo.resolution * scale);
7205 }
7206
7207 // To eliminate noise while the joystick is at rest, filter out small variations
7208 // in axis values up front.
7209 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7210
7211 mAxes.add(abs, axis);
7212 }
7213 }
7214
7215 // If there are too many axes, start dropping them.
7216 // Prefer to keep explicitly mapped axes.
7217 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007218 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007219 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7220 pruneAxes(true);
7221 pruneAxes(false);
7222 }
7223
7224 // Assign generic axis ids to remaining axes.
7225 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7226 size_t numAxes = mAxes.size();
7227 for (size_t i = 0; i < numAxes; i++) {
7228 Axis& axis = mAxes.editValueAt(i);
7229 if (axis.axisInfo.axis < 0) {
7230 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7231 && haveAxis(nextGenericAxisId)) {
7232 nextGenericAxisId += 1;
7233 }
7234
7235 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7236 axis.axisInfo.axis = nextGenericAxisId;
7237 nextGenericAxisId += 1;
7238 } else {
7239 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7240 "have already been assigned to other axes.",
7241 getDeviceName().string(), mAxes.keyAt(i));
7242 mAxes.removeItemsAt(i--);
7243 numAxes -= 1;
7244 }
7245 }
7246 }
7247 }
7248}
7249
7250bool JoystickInputMapper::haveAxis(int32_t axisId) {
7251 size_t numAxes = mAxes.size();
7252 for (size_t i = 0; i < numAxes; i++) {
7253 const Axis& axis = mAxes.valueAt(i);
7254 if (axis.axisInfo.axis == axisId
7255 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7256 && axis.axisInfo.highAxis == axisId)) {
7257 return true;
7258 }
7259 }
7260 return false;
7261}
7262
7263void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7264 size_t i = mAxes.size();
7265 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7266 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7267 continue;
7268 }
7269 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7270 getDeviceName().string(), mAxes.keyAt(i));
7271 mAxes.removeItemsAt(i);
7272 }
7273}
7274
7275bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7276 switch (axis) {
7277 case AMOTION_EVENT_AXIS_X:
7278 case AMOTION_EVENT_AXIS_Y:
7279 case AMOTION_EVENT_AXIS_Z:
7280 case AMOTION_EVENT_AXIS_RX:
7281 case AMOTION_EVENT_AXIS_RY:
7282 case AMOTION_EVENT_AXIS_RZ:
7283 case AMOTION_EVENT_AXIS_HAT_X:
7284 case AMOTION_EVENT_AXIS_HAT_Y:
7285 case AMOTION_EVENT_AXIS_ORIENTATION:
7286 case AMOTION_EVENT_AXIS_RUDDER:
7287 case AMOTION_EVENT_AXIS_WHEEL:
7288 return true;
7289 default:
7290 return false;
7291 }
7292}
7293
7294void JoystickInputMapper::reset(nsecs_t when) {
7295 // Recenter all axes.
7296 size_t numAxes = mAxes.size();
7297 for (size_t i = 0; i < numAxes; i++) {
7298 Axis& axis = mAxes.editValueAt(i);
7299 axis.resetValue();
7300 }
7301
7302 InputMapper::reset(when);
7303}
7304
7305void JoystickInputMapper::process(const RawEvent* rawEvent) {
7306 switch (rawEvent->type) {
7307 case EV_ABS: {
7308 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7309 if (index >= 0) {
7310 Axis& axis = mAxes.editValueAt(index);
7311 float newValue, highNewValue;
7312 switch (axis.axisInfo.mode) {
7313 case AxisInfo::MODE_INVERT:
7314 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7315 * axis.scale + axis.offset;
7316 highNewValue = 0.0f;
7317 break;
7318 case AxisInfo::MODE_SPLIT:
7319 if (rawEvent->value < axis.axisInfo.splitValue) {
7320 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7321 * axis.scale + axis.offset;
7322 highNewValue = 0.0f;
7323 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7324 newValue = 0.0f;
7325 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7326 * axis.highScale + axis.highOffset;
7327 } else {
7328 newValue = 0.0f;
7329 highNewValue = 0.0f;
7330 }
7331 break;
7332 default:
7333 newValue = rawEvent->value * axis.scale + axis.offset;
7334 highNewValue = 0.0f;
7335 break;
7336 }
7337 axis.newValue = newValue;
7338 axis.highNewValue = highNewValue;
7339 }
7340 break;
7341 }
7342
7343 case EV_SYN:
7344 switch (rawEvent->code) {
7345 case SYN_REPORT:
7346 sync(rawEvent->when, false /*force*/);
7347 break;
7348 }
7349 break;
7350 }
7351}
7352
7353void JoystickInputMapper::sync(nsecs_t when, bool force) {
7354 if (!filterAxes(force)) {
7355 return;
7356 }
7357
7358 int32_t metaState = mContext->getGlobalMetaState();
7359 int32_t buttonState = 0;
7360
7361 PointerProperties pointerProperties;
7362 pointerProperties.clear();
7363 pointerProperties.id = 0;
7364 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7365
7366 PointerCoords pointerCoords;
7367 pointerCoords.clear();
7368
7369 size_t numAxes = mAxes.size();
7370 for (size_t i = 0; i < numAxes; i++) {
7371 const Axis& axis = mAxes.valueAt(i);
7372 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7373 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7374 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7375 axis.highCurrentValue);
7376 }
7377 }
7378
7379 // Moving a joystick axis should not wake the device because joysticks can
7380 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7381 // button will likely wake the device.
7382 // TODO: Use the input device configuration to control this behavior more finely.
7383 uint32_t policyFlags = 0;
7384
7385 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007386 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007387 ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0);
7388 getListener()->notifyMotion(&args);
7389}
7390
7391void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7392 int32_t axis, float value) {
7393 pointerCoords->setAxisValue(axis, value);
7394 /* In order to ease the transition for developers from using the old axes
7395 * to the newer, more semantically correct axes, we'll continue to produce
7396 * values for the old axes as mirrors of the value of their corresponding
7397 * new axes. */
7398 int32_t compatAxis = getCompatAxis(axis);
7399 if (compatAxis >= 0) {
7400 pointerCoords->setAxisValue(compatAxis, value);
7401 }
7402}
7403
7404bool JoystickInputMapper::filterAxes(bool force) {
7405 bool atLeastOneSignificantChange = force;
7406 size_t numAxes = mAxes.size();
7407 for (size_t i = 0; i < numAxes; i++) {
7408 Axis& axis = mAxes.editValueAt(i);
7409 if (force || hasValueChangedSignificantly(axis.filter,
7410 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7411 axis.currentValue = axis.newValue;
7412 atLeastOneSignificantChange = true;
7413 }
7414 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7415 if (force || hasValueChangedSignificantly(axis.filter,
7416 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7417 axis.highCurrentValue = axis.highNewValue;
7418 atLeastOneSignificantChange = true;
7419 }
7420 }
7421 }
7422 return atLeastOneSignificantChange;
7423}
7424
7425bool JoystickInputMapper::hasValueChangedSignificantly(
7426 float filter, float newValue, float currentValue, float min, float max) {
7427 if (newValue != currentValue) {
7428 // Filter out small changes in value unless the value is converging on the axis
7429 // bounds or center point. This is intended to reduce the amount of information
7430 // sent to applications by particularly noisy joysticks (such as PS3).
7431 if (fabs(newValue - currentValue) > filter
7432 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7433 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7434 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7435 return true;
7436 }
7437 }
7438 return false;
7439}
7440
7441bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7442 float filter, float newValue, float currentValue, float thresholdValue) {
7443 float newDistance = fabs(newValue - thresholdValue);
7444 if (newDistance < filter) {
7445 float oldDistance = fabs(currentValue - thresholdValue);
7446 if (newDistance < oldDistance) {
7447 return true;
7448 }
7449 }
7450 return false;
7451}
7452
7453} // namespace android