blob: a4f83b7ebbf3e04683444f5d6d772aab5ce48140 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputReader"
18
19//#define LOG_NDEBUG 0
20
21// Log debug messages for each raw event received from the EventHub.
22#define DEBUG_RAW_EVENTS 0
23
24// Log debug messages about touch screen filtering hacks.
25#define DEBUG_HACKS 0
26
27// Log debug messages about virtual key processing.
28#define DEBUG_VIRTUAL_KEYS 0
29
30// Log debug messages about pointers.
31#define DEBUG_POINTERS 0
32
33// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
36// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
39// Log debug messages about the vibrator.
40#define DEBUG_VIBRATOR 0
41
Michael Wright842500e2015-03-13 17:32:02 -070042// Log debug messages about fusing stylus data.
43#define DEBUG_STYLUS_FUSION 0
44
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include "InputReader.h"
46
Mark Salyzyna5e161b2016-09-29 08:08:05 -070047#include <errno.h>
Michael Wright842500e2015-03-13 17:32:02 -070048#include <inttypes.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070049#include <limits.h>
50#include <math.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <stddef.h>
52#include <stdlib.h>
53#include <unistd.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054
Mark Salyzyn7823e122016-09-29 08:08:05 -070055#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057#include <android-base/stringprintf.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <input/Keyboard.h>
59#include <input/VirtualKeyMap.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
61#define INDENT " "
62#define INDENT2 " "
63#define INDENT3 " "
64#define INDENT4 " "
65#define INDENT5 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
71// --- Constants ---
72
73// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
74static const size_t MAX_SLOTS = 32;
75
Michael Wright842500e2015-03-13 17:32:02 -070076// Maximum amount of latency to add to touch events while waiting for data from an
77// external stylus.
Michael Wright5e17a5d2015-04-21 22:45:13 +010078static const nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
Michael Wright842500e2015-03-13 17:32:02 -070079
Michael Wright43fd19f2015-04-21 19:02:58 +010080// Maximum amount of time to wait on touch data before pushing out new pressure data.
81static const nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
82
83// Artificial latency on synthetic events created from stylus data without corresponding touch
84// data.
85static const nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
86
Michael Wrightd02c5b62014-02-10 15:10:22 -080087// --- Static Functions ---
88
89template<typename T>
90inline static T abs(const T& value) {
91 return value < 0 ? - value : value;
92}
93
94template<typename T>
95inline static T min(const T& a, const T& b) {
96 return a < b ? a : b;
97}
98
99template<typename T>
100inline static void swap(T& a, T& b) {
101 T temp = a;
102 a = b;
103 b = temp;
104}
105
106inline static float avg(float x, float y) {
107 return (x + y) / 2;
108}
109
110inline static float distance(float x1, float y1, float x2, float y2) {
111 return hypotf(x1 - x2, y1 - y2);
112}
113
114inline static int32_t signExtendNybble(int32_t value) {
115 return value >= 8 ? value - 16 : value;
116}
117
118static inline const char* toString(bool value) {
119 return value ? "true" : "false";
120}
121
122static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
123 const int32_t map[][4], size_t mapSize) {
124 if (orientation != DISPLAY_ORIENTATION_0) {
125 for (size_t i = 0; i < mapSize; i++) {
126 if (value == map[i][0]) {
127 return map[i][orientation];
128 }
129 }
130 }
131 return value;
132}
133
134static const int32_t keyCodeRotationMap[][4] = {
135 // key codes enumerated counter-clockwise with the original (unrotated) key first
136 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
137 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
138 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
139 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
140 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jim Millere7a57d12016-06-22 15:58:31 -0700141 { AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
142 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT },
143 { AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
144 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN },
145 { AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
146 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT },
147 { AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
148 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP },
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149};
150static const size_t keyCodeRotationMapSize =
151 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
152
Ivan Podogovb9afef32017-02-13 15:34:32 +0000153static int32_t rotateStemKey(int32_t value, int32_t orientation,
154 const int32_t map[][2], size_t mapSize) {
155 if (orientation == DISPLAY_ORIENTATION_180) {
156 for (size_t i = 0; i < mapSize; i++) {
157 if (value == map[i][0]) {
158 return map[i][1];
159 }
160 }
161 }
162 return value;
163}
164
165// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
166static int32_t stemKeyRotationMap[][2] = {
167 // key codes enumerated with the original (unrotated) key first
168 // no rotation, 180 degree rotation
169 { AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
170 { AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
171 { AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
172 { AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
173};
174static const size_t stemKeyRotationMapSize =
175 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
176
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000178 keyCode = rotateStemKey(keyCode, orientation,
179 stemKeyRotationMap, stemKeyRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 return rotateValueUsingRotationMap(keyCode, orientation,
181 keyCodeRotationMap, keyCodeRotationMapSize);
182}
183
184static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
185 float temp;
186 switch (orientation) {
187 case DISPLAY_ORIENTATION_90:
188 temp = *deltaX;
189 *deltaX = *deltaY;
190 *deltaY = -temp;
191 break;
192
193 case DISPLAY_ORIENTATION_180:
194 *deltaX = -*deltaX;
195 *deltaY = -*deltaY;
196 break;
197
198 case DISPLAY_ORIENTATION_270:
199 temp = *deltaX;
200 *deltaX = -*deltaY;
201 *deltaY = temp;
202 break;
203 }
204}
205
206static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
207 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
208}
209
210// Returns true if the pointer should be reported as being down given the specified
211// button states. This determines whether the event is reported as a touch event.
212static bool isPointerDown(int32_t buttonState) {
213 return buttonState &
214 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
215 | AMOTION_EVENT_BUTTON_TERTIARY);
216}
217
218static float calculateCommonVector(float a, float b) {
219 if (a > 0 && b > 0) {
220 return a < b ? a : b;
221 } else if (a < 0 && b < 0) {
222 return a > b ? a : b;
223 } else {
224 return 0;
225 }
226}
227
228static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100229 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
231 int32_t buttonState, int32_t keyCode) {
232 if (
233 (action == AKEY_EVENT_ACTION_DOWN
234 && !(lastButtonState & buttonState)
235 && (currentButtonState & buttonState))
236 || (action == AKEY_EVENT_ACTION_UP
237 && (lastButtonState & buttonState)
238 && !(currentButtonState & buttonState))) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100239 NotifyKeyArgs args(when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240 action, 0, keyCode, 0, context->getGlobalMetaState(), when);
241 context->getListener()->notifyKey(&args);
242 }
243}
244
245static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100246 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100248 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 lastButtonState, currentButtonState,
250 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100251 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 lastButtonState, currentButtonState,
253 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
254}
255
256
257// --- InputReaderConfiguration ---
258
Santos Cordonfa5cf462017-04-05 10:37:00 -0700259bool InputReaderConfiguration::getDisplayViewport(ViewportType viewportType,
260 const String8* uniqueDisplayId, DisplayViewport* outViewport) const {
Yi Kong9b14ac62018-07-17 13:48:38 -0700261 const DisplayViewport* viewport = nullptr;
262 if (viewportType == ViewportType::VIEWPORT_VIRTUAL && uniqueDisplayId != nullptr) {
Michael Spangf88ea9b2017-09-05 20:17:16 -0400263 for (const DisplayViewport& currentViewport : mVirtualDisplays) {
Santos Cordonfa5cf462017-04-05 10:37:00 -0700264 if (currentViewport.uniqueId == *uniqueDisplayId) {
265 viewport = &currentViewport;
266 break;
267 }
268 }
269 } else if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
270 viewport = &mExternalDisplay;
271 } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
272 viewport = &mInternalDisplay;
273 }
274
Yi Kong9b14ac62018-07-17 13:48:38 -0700275 if (viewport != nullptr && viewport->displayId >= 0) {
Santos Cordonfa5cf462017-04-05 10:37:00 -0700276 *outViewport = *viewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800277 return true;
278 }
279 return false;
280}
281
Santos Cordonfa5cf462017-04-05 10:37:00 -0700282void InputReaderConfiguration::setPhysicalDisplayViewport(ViewportType viewportType,
283 const DisplayViewport& viewport) {
284 if (viewportType == ViewportType::VIEWPORT_EXTERNAL) {
285 mExternalDisplay = viewport;
286 } else if (viewportType == ViewportType::VIEWPORT_INTERNAL) {
287 mInternalDisplay = viewport;
288 }
289}
290
291void InputReaderConfiguration::setVirtualDisplayViewports(
292 const Vector<DisplayViewport>& viewports) {
293 mVirtualDisplays = viewports;
294}
295
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800296void InputReaderConfiguration::dump(std::string& dump) const {
297 dump += INDENT4 "ViewportInternal:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700298 dumpViewport(dump, mInternalDisplay);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800299 dump += INDENT4 "ViewportExternal:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700300 dumpViewport(dump, mExternalDisplay);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800301 dump += INDENT4 "ViewportVirtual:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700302 for (const DisplayViewport& viewport : mVirtualDisplays) {
303 dumpViewport(dump, viewport);
304 }
305}
306
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800307void InputReaderConfiguration::dumpViewport(std::string& dump, const DisplayViewport& viewport) const {
308 dump += StringPrintf(INDENT5 "Viewport: displayId=%d, orientation=%d, uniqueId='%s', "
Santos Cordonfa5cf462017-04-05 10:37:00 -0700309 "logicalFrame=[%d, %d, %d, %d], "
310 "physicalFrame=[%d, %d, %d, %d], "
311 "deviceSize=[%d, %d]\n",
312 viewport.displayId, viewport.orientation, viewport.uniqueId.c_str(),
313 viewport.logicalLeft, viewport.logicalTop,
314 viewport.logicalRight, viewport.logicalBottom,
315 viewport.physicalLeft, viewport.physicalTop,
316 viewport.physicalRight, viewport.physicalBottom,
317 viewport.deviceWidth, viewport.deviceHeight);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800318}
319
320
Jason Gereckeaf126fb2012-05-10 14:22:47 -0700321// -- TouchAffineTransformation --
322void TouchAffineTransformation::applyTo(float& x, float& y) const {
323 float newX, newY;
324 newX = x * x_scale + y * x_ymix + x_offset;
325 newY = x * y_xmix + y * y_scale + y_offset;
326
327 x = newX;
328 y = newY;
329}
330
331
Michael Wrightd02c5b62014-02-10 15:10:22 -0800332// --- InputReader ---
333
334InputReader::InputReader(const sp<EventHubInterface>& eventHub,
335 const sp<InputReaderPolicyInterface>& policy,
336 const sp<InputListenerInterface>& listener) :
337 mContext(this), mEventHub(eventHub), mPolicy(policy),
338 mGlobalMetaState(0), mGeneration(1),
339 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
340 mConfigurationChangesToRefresh(0) {
341 mQueuedListener = new QueuedInputListener(listener);
342
343 { // acquire lock
344 AutoMutex _l(mLock);
345
346 refreshConfigurationLocked(0);
347 updateGlobalMetaStateLocked();
348 } // release lock
349}
350
351InputReader::~InputReader() {
352 for (size_t i = 0; i < mDevices.size(); i++) {
353 delete mDevices.valueAt(i);
354 }
355}
356
357void InputReader::loopOnce() {
358 int32_t oldGeneration;
359 int32_t timeoutMillis;
360 bool inputDevicesChanged = false;
361 Vector<InputDeviceInfo> inputDevices;
362 { // acquire lock
363 AutoMutex _l(mLock);
364
365 oldGeneration = mGeneration;
366 timeoutMillis = -1;
367
368 uint32_t changes = mConfigurationChangesToRefresh;
369 if (changes) {
370 mConfigurationChangesToRefresh = 0;
371 timeoutMillis = 0;
372 refreshConfigurationLocked(changes);
373 } else if (mNextTimeout != LLONG_MAX) {
374 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
375 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
376 }
377 } // release lock
378
379 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
380
381 { // acquire lock
382 AutoMutex _l(mLock);
383 mReaderIsAliveCondition.broadcast();
384
385 if (count) {
386 processEventsLocked(mEventBuffer, count);
387 }
388
389 if (mNextTimeout != LLONG_MAX) {
390 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
391 if (now >= mNextTimeout) {
392#if DEBUG_RAW_EVENTS
393 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
394#endif
395 mNextTimeout = LLONG_MAX;
396 timeoutExpiredLocked(now);
397 }
398 }
399
400 if (oldGeneration != mGeneration) {
401 inputDevicesChanged = true;
402 getInputDevicesLocked(inputDevices);
403 }
404 } // release lock
405
406 // Send out a message that the describes the changed input devices.
407 if (inputDevicesChanged) {
408 mPolicy->notifyInputDevicesChanged(inputDevices);
409 }
410
411 // Flush queued events out to the listener.
412 // This must happen outside of the lock because the listener could potentially call
413 // back into the InputReader's methods, such as getScanCodeState, or become blocked
414 // on another thread similarly waiting to acquire the InputReader lock thereby
415 // resulting in a deadlock. This situation is actually quite plausible because the
416 // listener is actually the input dispatcher, which calls into the window manager,
417 // which occasionally calls into the input reader.
418 mQueuedListener->flush();
419}
420
421void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
422 for (const RawEvent* rawEvent = rawEvents; count;) {
423 int32_t type = rawEvent->type;
424 size_t batchSize = 1;
425 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
426 int32_t deviceId = rawEvent->deviceId;
427 while (batchSize < count) {
428 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
429 || rawEvent[batchSize].deviceId != deviceId) {
430 break;
431 }
432 batchSize += 1;
433 }
434#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700435 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800436#endif
437 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
438 } else {
439 switch (rawEvent->type) {
440 case EventHubInterface::DEVICE_ADDED:
441 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
442 break;
443 case EventHubInterface::DEVICE_REMOVED:
444 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
445 break;
446 case EventHubInterface::FINISHED_DEVICE_SCAN:
447 handleConfigurationChangedLocked(rawEvent->when);
448 break;
449 default:
450 ALOG_ASSERT(false); // can't happen
451 break;
452 }
453 }
454 count -= batchSize;
455 rawEvent += batchSize;
456 }
457}
458
459void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
460 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
461 if (deviceIndex >= 0) {
462 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
463 return;
464 }
465
466 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
467 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
468 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
469
470 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
471 device->configure(when, &mConfig, 0);
472 device->reset(when);
473
474 if (device->isIgnored()) {
475 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
476 identifier.name.string());
477 } else {
478 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
479 identifier.name.string(), device->getSources());
480 }
481
482 mDevices.add(deviceId, device);
483 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700484
485 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
486 notifyExternalStylusPresenceChanged();
487 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488}
489
490void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700491 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
493 if (deviceIndex < 0) {
494 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
495 return;
496 }
497
498 device = mDevices.valueAt(deviceIndex);
499 mDevices.removeItemsAt(deviceIndex, 1);
500 bumpGenerationLocked();
501
502 if (device->isIgnored()) {
503 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
504 device->getId(), device->getName().string());
505 } else {
506 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
507 device->getId(), device->getName().string(), device->getSources());
508 }
509
Michael Wright842500e2015-03-13 17:32:02 -0700510 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
511 notifyExternalStylusPresenceChanged();
512 }
513
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514 device->reset(when);
515 delete device;
516}
517
518InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
519 const InputDeviceIdentifier& identifier, uint32_t classes) {
520 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
521 controllerNumber, identifier, classes);
522
523 // External devices.
524 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
525 device->setExternal(true);
526 }
527
Tim Kilbourn063ff532015-04-08 10:26:18 -0700528 // Devices with mics.
529 if (classes & INPUT_DEVICE_CLASS_MIC) {
530 device->setMic(true);
531 }
532
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533 // Switch-like devices.
534 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
535 device->addMapper(new SwitchInputMapper(device));
536 }
537
Prashant Malani1941ff52015-08-11 18:29:28 -0700538 // Scroll wheel-like devices.
539 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
540 device->addMapper(new RotaryEncoderInputMapper(device));
541 }
542
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 // Vibrator-like devices.
544 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
545 device->addMapper(new VibratorInputMapper(device));
546 }
547
548 // Keyboard-like devices.
549 uint32_t keyboardSource = 0;
550 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
551 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
552 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
553 }
554 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
555 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
556 }
557 if (classes & INPUT_DEVICE_CLASS_DPAD) {
558 keyboardSource |= AINPUT_SOURCE_DPAD;
559 }
560 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
561 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
562 }
563
564 if (keyboardSource != 0) {
565 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
566 }
567
568 // Cursor-like devices.
569 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
570 device->addMapper(new CursorInputMapper(device));
571 }
572
573 // Touchscreens and touchpad devices.
574 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
575 device->addMapper(new MultiTouchInputMapper(device));
576 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
577 device->addMapper(new SingleTouchInputMapper(device));
578 }
579
580 // Joystick-like devices.
581 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
582 device->addMapper(new JoystickInputMapper(device));
583 }
584
Michael Wright842500e2015-03-13 17:32:02 -0700585 // External stylus-like devices.
586 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
587 device->addMapper(new ExternalStylusInputMapper(device));
588 }
589
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590 return device;
591}
592
593void InputReader::processEventsForDeviceLocked(int32_t deviceId,
594 const RawEvent* rawEvents, size_t count) {
595 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
596 if (deviceIndex < 0) {
597 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
598 return;
599 }
600
601 InputDevice* device = mDevices.valueAt(deviceIndex);
602 if (device->isIgnored()) {
603 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
604 return;
605 }
606
607 device->process(rawEvents, count);
608}
609
610void InputReader::timeoutExpiredLocked(nsecs_t when) {
611 for (size_t i = 0; i < mDevices.size(); i++) {
612 InputDevice* device = mDevices.valueAt(i);
613 if (!device->isIgnored()) {
614 device->timeoutExpired(when);
615 }
616 }
617}
618
619void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
620 // Reset global meta state because it depends on the list of all configured devices.
621 updateGlobalMetaStateLocked();
622
623 // Enqueue configuration changed.
624 NotifyConfigurationChangedArgs args(when);
625 mQueuedListener->notifyConfigurationChanged(&args);
626}
627
628void InputReader::refreshConfigurationLocked(uint32_t changes) {
629 mPolicy->getReaderConfiguration(&mConfig);
630 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
631
632 if (changes) {
633 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
634 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
635
636 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
637 mEventHub->requestReopenDevices();
638 } else {
639 for (size_t i = 0; i < mDevices.size(); i++) {
640 InputDevice* device = mDevices.valueAt(i);
641 device->configure(now, &mConfig, changes);
642 }
643 }
644 }
645}
646
647void InputReader::updateGlobalMetaStateLocked() {
648 mGlobalMetaState = 0;
649
650 for (size_t i = 0; i < mDevices.size(); i++) {
651 InputDevice* device = mDevices.valueAt(i);
652 mGlobalMetaState |= device->getMetaState();
653 }
654}
655
656int32_t InputReader::getGlobalMetaStateLocked() {
657 return mGlobalMetaState;
658}
659
Michael Wright842500e2015-03-13 17:32:02 -0700660void InputReader::notifyExternalStylusPresenceChanged() {
661 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
662}
663
664void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
665 for (size_t i = 0; i < mDevices.size(); i++) {
666 InputDevice* device = mDevices.valueAt(i);
667 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
668 outDevices.push();
669 device->getDeviceInfo(&outDevices.editTop());
670 }
671 }
672}
673
674void InputReader::dispatchExternalStylusState(const StylusState& state) {
675 for (size_t i = 0; i < mDevices.size(); i++) {
676 InputDevice* device = mDevices.valueAt(i);
677 device->updateExternalStylusState(state);
678 }
679}
680
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
682 mDisableVirtualKeysTimeout = time;
683}
684
685bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
686 InputDevice* device, int32_t keyCode, int32_t scanCode) {
687 if (now < mDisableVirtualKeysTimeout) {
688 ALOGI("Dropping virtual key from device %s because virtual keys are "
689 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
690 device->getName().string(),
691 (mDisableVirtualKeysTimeout - now) * 0.000001,
692 keyCode, scanCode);
693 return true;
694 } else {
695 return false;
696 }
697}
698
699void InputReader::fadePointerLocked() {
700 for (size_t i = 0; i < mDevices.size(); i++) {
701 InputDevice* device = mDevices.valueAt(i);
702 device->fadePointer();
703 }
704}
705
706void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
707 if (when < mNextTimeout) {
708 mNextTimeout = when;
709 mEventHub->wake();
710 }
711}
712
713int32_t InputReader::bumpGenerationLocked() {
714 return ++mGeneration;
715}
716
717void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
718 AutoMutex _l(mLock);
719 getInputDevicesLocked(outInputDevices);
720}
721
722void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
723 outInputDevices.clear();
724
725 size_t numDevices = mDevices.size();
726 for (size_t i = 0; i < numDevices; i++) {
727 InputDevice* device = mDevices.valueAt(i);
728 if (!device->isIgnored()) {
729 outInputDevices.push();
730 device->getDeviceInfo(&outInputDevices.editTop());
731 }
732 }
733}
734
735int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
736 int32_t keyCode) {
737 AutoMutex _l(mLock);
738
739 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
740}
741
742int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
743 int32_t scanCode) {
744 AutoMutex _l(mLock);
745
746 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
747}
748
749int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
750 AutoMutex _l(mLock);
751
752 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
753}
754
755int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
756 GetStateFunc getStateFunc) {
757 int32_t result = AKEY_STATE_UNKNOWN;
758 if (deviceId >= 0) {
759 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
760 if (deviceIndex >= 0) {
761 InputDevice* device = mDevices.valueAt(deviceIndex);
762 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
763 result = (device->*getStateFunc)(sourceMask, code);
764 }
765 }
766 } else {
767 size_t numDevices = mDevices.size();
768 for (size_t i = 0; i < numDevices; i++) {
769 InputDevice* device = mDevices.valueAt(i);
770 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
771 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
772 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
773 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
774 if (currentResult >= AKEY_STATE_DOWN) {
775 return currentResult;
776 } else if (currentResult == AKEY_STATE_UP) {
777 result = currentResult;
778 }
779 }
780 }
781 }
782 return result;
783}
784
Andrii Kulian763a3a42016-03-08 10:46:16 -0800785void InputReader::toggleCapsLockState(int32_t deviceId) {
786 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
787 if (deviceIndex < 0) {
788 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
789 return;
790 }
791
792 InputDevice* device = mDevices.valueAt(deviceIndex);
793 if (device->isIgnored()) {
794 return;
795 }
796
797 device->updateMetaState(AKEYCODE_CAPS_LOCK);
798}
799
Michael Wrightd02c5b62014-02-10 15:10:22 -0800800bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
801 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
802 AutoMutex _l(mLock);
803
804 memset(outFlags, 0, numCodes);
805 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
806}
807
808bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
809 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
810 bool result = false;
811 if (deviceId >= 0) {
812 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
813 if (deviceIndex >= 0) {
814 InputDevice* device = mDevices.valueAt(deviceIndex);
815 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
816 result = device->markSupportedKeyCodes(sourceMask,
817 numCodes, keyCodes, outFlags);
818 }
819 }
820 } else {
821 size_t numDevices = mDevices.size();
822 for (size_t i = 0; i < numDevices; i++) {
823 InputDevice* device = mDevices.valueAt(i);
824 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
825 result |= device->markSupportedKeyCodes(sourceMask,
826 numCodes, keyCodes, outFlags);
827 }
828 }
829 }
830 return result;
831}
832
833void InputReader::requestRefreshConfiguration(uint32_t changes) {
834 AutoMutex _l(mLock);
835
836 if (changes) {
837 bool needWake = !mConfigurationChangesToRefresh;
838 mConfigurationChangesToRefresh |= changes;
839
840 if (needWake) {
841 mEventHub->wake();
842 }
843 }
844}
845
846void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
847 ssize_t repeat, int32_t token) {
848 AutoMutex _l(mLock);
849
850 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
851 if (deviceIndex >= 0) {
852 InputDevice* device = mDevices.valueAt(deviceIndex);
853 device->vibrate(pattern, patternSize, repeat, token);
854 }
855}
856
857void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
858 AutoMutex _l(mLock);
859
860 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
861 if (deviceIndex >= 0) {
862 InputDevice* device = mDevices.valueAt(deviceIndex);
863 device->cancelVibrate(token);
864 }
865}
866
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700867bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
868 AutoMutex _l(mLock);
869
870 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
871 if (deviceIndex >= 0) {
872 InputDevice* device = mDevices.valueAt(deviceIndex);
873 return device->isEnabled();
874 }
875 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
876 return false;
877}
878
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800879void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 AutoMutex _l(mLock);
881
882 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800883 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800885 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886
887 for (size_t i = 0; i < mDevices.size(); i++) {
888 mDevices.valueAt(i)->dump(dump);
889 }
890
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800891 dump += INDENT "Configuration:\n";
892 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
894 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800895 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800897 dump += mConfig.excludedDeviceNames.itemAt(i).string();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800899 dump += "]\n";
900 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 mConfig.virtualKeyQuietTime * 0.000001f);
902
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800903 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
905 mConfig.pointerVelocityControlParameters.scale,
906 mConfig.pointerVelocityControlParameters.lowThreshold,
907 mConfig.pointerVelocityControlParameters.highThreshold,
908 mConfig.pointerVelocityControlParameters.acceleration);
909
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800910 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800911 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
912 mConfig.wheelVelocityControlParameters.scale,
913 mConfig.wheelVelocityControlParameters.lowThreshold,
914 mConfig.wheelVelocityControlParameters.highThreshold,
915 mConfig.wheelVelocityControlParameters.acceleration);
916
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800917 dump += StringPrintf(INDENT2 "PointerGesture:\n");
918 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800919 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800920 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800922 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800923 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800924 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800925 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800926 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800927 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800928 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800930 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800932 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800934 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800936 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800937 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800938 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800940 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700942
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800943 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700944 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800945}
946
947void InputReader::monitor() {
948 // Acquire and release the lock to ensure that the reader has not deadlocked.
949 mLock.lock();
950 mEventHub->wake();
951 mReaderIsAliveCondition.wait(mLock);
952 mLock.unlock();
953
954 // Check the EventHub
955 mEventHub->monitor();
956}
957
958
959// --- InputReader::ContextImpl ---
960
961InputReader::ContextImpl::ContextImpl(InputReader* reader) :
962 mReader(reader) {
963}
964
965void InputReader::ContextImpl::updateGlobalMetaState() {
966 // lock is already held by the input loop
967 mReader->updateGlobalMetaStateLocked();
968}
969
970int32_t InputReader::ContextImpl::getGlobalMetaState() {
971 // lock is already held by the input loop
972 return mReader->getGlobalMetaStateLocked();
973}
974
975void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
976 // lock is already held by the input loop
977 mReader->disableVirtualKeysUntilLocked(time);
978}
979
980bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
981 InputDevice* device, int32_t keyCode, int32_t scanCode) {
982 // lock is already held by the input loop
983 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
984}
985
986void InputReader::ContextImpl::fadePointer() {
987 // lock is already held by the input loop
988 mReader->fadePointerLocked();
989}
990
991void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
992 // lock is already held by the input loop
993 mReader->requestTimeoutAtTimeLocked(when);
994}
995
996int32_t InputReader::ContextImpl::bumpGeneration() {
997 // lock is already held by the input loop
998 return mReader->bumpGenerationLocked();
999}
1000
Michael Wright842500e2015-03-13 17:32:02 -07001001void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
1002 // lock is already held by whatever called refreshConfigurationLocked
1003 mReader->getExternalStylusDevicesLocked(outDevices);
1004}
1005
1006void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
1007 mReader->dispatchExternalStylusState(state);
1008}
1009
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
1011 return mReader->mPolicy.get();
1012}
1013
1014InputListenerInterface* InputReader::ContextImpl::getListener() {
1015 return mReader->mQueuedListener.get();
1016}
1017
1018EventHubInterface* InputReader::ContextImpl::getEventHub() {
1019 return mReader->mEventHub.get();
1020}
1021
1022
1023// --- InputReaderThread ---
1024
1025InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
1026 Thread(/*canCallJava*/ true), mReader(reader) {
1027}
1028
1029InputReaderThread::~InputReaderThread() {
1030}
1031
1032bool InputReaderThread::threadLoop() {
1033 mReader->loopOnce();
1034 return true;
1035}
1036
1037
1038// --- InputDevice ---
1039
1040InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
1041 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
1042 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
1043 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -07001044 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045}
1046
1047InputDevice::~InputDevice() {
1048 size_t numMappers = mMappers.size();
1049 for (size_t i = 0; i < numMappers; i++) {
1050 delete mMappers[i];
1051 }
1052 mMappers.clear();
1053}
1054
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001055bool InputDevice::isEnabled() {
1056 return getEventHub()->isDeviceEnabled(mId);
1057}
1058
1059void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1060 if (isEnabled() == enabled) {
1061 return;
1062 }
1063
1064 if (enabled) {
1065 getEventHub()->enableDevice(mId);
1066 reset(when);
1067 } else {
1068 reset(when);
1069 getEventHub()->disableDevice(mId);
1070 }
1071 // Must change generation to flag this device as changed
1072 bumpGeneration();
1073}
1074
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001075void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076 InputDeviceInfo deviceInfo;
1077 getDeviceInfo(& deviceInfo);
1078
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001079 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 deviceInfo.getDisplayName().string());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001081 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1082 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
1083 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1084 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1085 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086
1087 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1088 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001089 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 for (size_t i = 0; i < ranges.size(); i++) {
1091 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1092 const char* label = getAxisLabel(range.axis);
1093 char name[32];
1094 if (label) {
1095 strncpy(name, label, sizeof(name));
1096 name[sizeof(name) - 1] = '\0';
1097 } else {
1098 snprintf(name, sizeof(name), "%d", range.axis);
1099 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001100 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1102 name, range.source, range.min, range.max, range.flat, range.fuzz,
1103 range.resolution);
1104 }
1105 }
1106
1107 size_t numMappers = mMappers.size();
1108 for (size_t i = 0; i < numMappers; i++) {
1109 InputMapper* mapper = mMappers[i];
1110 mapper->dump(dump);
1111 }
1112}
1113
1114void InputDevice::addMapper(InputMapper* mapper) {
1115 mMappers.add(mapper);
1116}
1117
1118void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1119 mSources = 0;
1120
1121 if (!isIgnored()) {
1122 if (!changes) { // first time only
1123 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1124 }
1125
1126 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1127 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1128 sp<KeyCharacterMap> keyboardLayout =
1129 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1130 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1131 bumpGeneration();
1132 }
1133 }
1134 }
1135
1136 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1137 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1138 String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
1139 if (mAlias != alias) {
1140 mAlias = alias;
1141 bumpGeneration();
1142 }
1143 }
1144 }
1145
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001146 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1147 ssize_t index = config->disabledDevices.indexOf(mId);
1148 bool enabled = index < 0;
1149 setEnabled(enabled, when);
1150 }
1151
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 size_t numMappers = mMappers.size();
1153 for (size_t i = 0; i < numMappers; i++) {
1154 InputMapper* mapper = mMappers[i];
1155 mapper->configure(when, config, changes);
1156 mSources |= mapper->getSources();
1157 }
1158 }
1159}
1160
1161void InputDevice::reset(nsecs_t when) {
1162 size_t numMappers = mMappers.size();
1163 for (size_t i = 0; i < numMappers; i++) {
1164 InputMapper* mapper = mMappers[i];
1165 mapper->reset(when);
1166 }
1167
1168 mContext->updateGlobalMetaState();
1169
1170 notifyReset(when);
1171}
1172
1173void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1174 // Process all of the events in order for each mapper.
1175 // We cannot simply ask each mapper to process them in bulk because mappers may
1176 // have side-effects that must be interleaved. For example, joystick movement events and
1177 // gamepad button presses are handled by different mappers but they should be dispatched
1178 // in the order received.
1179 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001180 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001182 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1184 rawEvent->when);
1185#endif
1186
1187 if (mDropUntilNextSync) {
1188 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1189 mDropUntilNextSync = false;
1190#if DEBUG_RAW_EVENTS
1191 ALOGD("Recovered from input event buffer overrun.");
1192#endif
1193 } else {
1194#if DEBUG_RAW_EVENTS
1195 ALOGD("Dropped input event while waiting for next input sync.");
1196#endif
1197 }
1198 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
1199 ALOGI("Detected input event buffer overrun for device %s.", getName().string());
1200 mDropUntilNextSync = true;
1201 reset(rawEvent->when);
1202 } else {
1203 for (size_t i = 0; i < numMappers; i++) {
1204 InputMapper* mapper = mMappers[i];
1205 mapper->process(rawEvent);
1206 }
1207 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001208 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001209 }
1210}
1211
1212void InputDevice::timeoutExpired(nsecs_t when) {
1213 size_t numMappers = mMappers.size();
1214 for (size_t i = 0; i < numMappers; i++) {
1215 InputMapper* mapper = mMappers[i];
1216 mapper->timeoutExpired(when);
1217 }
1218}
1219
Michael Wright842500e2015-03-13 17:32:02 -07001220void InputDevice::updateExternalStylusState(const StylusState& state) {
1221 size_t numMappers = mMappers.size();
1222 for (size_t i = 0; i < numMappers; i++) {
1223 InputMapper* mapper = mMappers[i];
1224 mapper->updateExternalStylusState(state);
1225 }
1226}
1227
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1229 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001230 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231 size_t numMappers = mMappers.size();
1232 for (size_t i = 0; i < numMappers; i++) {
1233 InputMapper* mapper = mMappers[i];
1234 mapper->populateDeviceInfo(outDeviceInfo);
1235 }
1236}
1237
1238int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1239 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1240}
1241
1242int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1243 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1244}
1245
1246int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1247 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1248}
1249
1250int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1251 int32_t result = AKEY_STATE_UNKNOWN;
1252 size_t numMappers = mMappers.size();
1253 for (size_t i = 0; i < numMappers; i++) {
1254 InputMapper* mapper = mMappers[i];
1255 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1256 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1257 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1258 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1259 if (currentResult >= AKEY_STATE_DOWN) {
1260 return currentResult;
1261 } else if (currentResult == AKEY_STATE_UP) {
1262 result = currentResult;
1263 }
1264 }
1265 }
1266 return result;
1267}
1268
1269bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1270 const int32_t* keyCodes, uint8_t* outFlags) {
1271 bool result = false;
1272 size_t numMappers = mMappers.size();
1273 for (size_t i = 0; i < numMappers; i++) {
1274 InputMapper* mapper = mMappers[i];
1275 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1276 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1277 }
1278 }
1279 return result;
1280}
1281
1282void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1283 int32_t token) {
1284 size_t numMappers = mMappers.size();
1285 for (size_t i = 0; i < numMappers; i++) {
1286 InputMapper* mapper = mMappers[i];
1287 mapper->vibrate(pattern, patternSize, repeat, token);
1288 }
1289}
1290
1291void InputDevice::cancelVibrate(int32_t token) {
1292 size_t numMappers = mMappers.size();
1293 for (size_t i = 0; i < numMappers; i++) {
1294 InputMapper* mapper = mMappers[i];
1295 mapper->cancelVibrate(token);
1296 }
1297}
1298
Jeff Brownc9aa6282015-02-11 19:03:28 -08001299void InputDevice::cancelTouch(nsecs_t when) {
1300 size_t numMappers = mMappers.size();
1301 for (size_t i = 0; i < numMappers; i++) {
1302 InputMapper* mapper = mMappers[i];
1303 mapper->cancelTouch(when);
1304 }
1305}
1306
Michael Wrightd02c5b62014-02-10 15:10:22 -08001307int32_t InputDevice::getMetaState() {
1308 int32_t result = 0;
1309 size_t numMappers = mMappers.size();
1310 for (size_t i = 0; i < numMappers; i++) {
1311 InputMapper* mapper = mMappers[i];
1312 result |= mapper->getMetaState();
1313 }
1314 return result;
1315}
1316
Andrii Kulian763a3a42016-03-08 10:46:16 -08001317void InputDevice::updateMetaState(int32_t keyCode) {
1318 size_t numMappers = mMappers.size();
1319 for (size_t i = 0; i < numMappers; i++) {
1320 mMappers[i]->updateMetaState(keyCode);
1321 }
1322}
1323
Michael Wrightd02c5b62014-02-10 15:10:22 -08001324void InputDevice::fadePointer() {
1325 size_t numMappers = mMappers.size();
1326 for (size_t i = 0; i < numMappers; i++) {
1327 InputMapper* mapper = mMappers[i];
1328 mapper->fadePointer();
1329 }
1330}
1331
1332void InputDevice::bumpGeneration() {
1333 mGeneration = mContext->bumpGeneration();
1334}
1335
1336void InputDevice::notifyReset(nsecs_t when) {
1337 NotifyDeviceResetArgs args(when, mId);
1338 mContext->getListener()->notifyDeviceReset(&args);
1339}
1340
1341
1342// --- CursorButtonAccumulator ---
1343
1344CursorButtonAccumulator::CursorButtonAccumulator() {
1345 clearButtons();
1346}
1347
1348void CursorButtonAccumulator::reset(InputDevice* device) {
1349 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1350 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1351 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1352 mBtnBack = device->isKeyPressed(BTN_BACK);
1353 mBtnSide = device->isKeyPressed(BTN_SIDE);
1354 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1355 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1356 mBtnTask = device->isKeyPressed(BTN_TASK);
1357}
1358
1359void CursorButtonAccumulator::clearButtons() {
1360 mBtnLeft = 0;
1361 mBtnRight = 0;
1362 mBtnMiddle = 0;
1363 mBtnBack = 0;
1364 mBtnSide = 0;
1365 mBtnForward = 0;
1366 mBtnExtra = 0;
1367 mBtnTask = 0;
1368}
1369
1370void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1371 if (rawEvent->type == EV_KEY) {
1372 switch (rawEvent->code) {
1373 case BTN_LEFT:
1374 mBtnLeft = rawEvent->value;
1375 break;
1376 case BTN_RIGHT:
1377 mBtnRight = rawEvent->value;
1378 break;
1379 case BTN_MIDDLE:
1380 mBtnMiddle = rawEvent->value;
1381 break;
1382 case BTN_BACK:
1383 mBtnBack = rawEvent->value;
1384 break;
1385 case BTN_SIDE:
1386 mBtnSide = rawEvent->value;
1387 break;
1388 case BTN_FORWARD:
1389 mBtnForward = rawEvent->value;
1390 break;
1391 case BTN_EXTRA:
1392 mBtnExtra = rawEvent->value;
1393 break;
1394 case BTN_TASK:
1395 mBtnTask = rawEvent->value;
1396 break;
1397 }
1398 }
1399}
1400
1401uint32_t CursorButtonAccumulator::getButtonState() const {
1402 uint32_t result = 0;
1403 if (mBtnLeft) {
1404 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1405 }
1406 if (mBtnRight) {
1407 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1408 }
1409 if (mBtnMiddle) {
1410 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1411 }
1412 if (mBtnBack || mBtnSide) {
1413 result |= AMOTION_EVENT_BUTTON_BACK;
1414 }
1415 if (mBtnForward || mBtnExtra) {
1416 result |= AMOTION_EVENT_BUTTON_FORWARD;
1417 }
1418 return result;
1419}
1420
1421
1422// --- CursorMotionAccumulator ---
1423
1424CursorMotionAccumulator::CursorMotionAccumulator() {
1425 clearRelativeAxes();
1426}
1427
1428void CursorMotionAccumulator::reset(InputDevice* device) {
1429 clearRelativeAxes();
1430}
1431
1432void CursorMotionAccumulator::clearRelativeAxes() {
1433 mRelX = 0;
1434 mRelY = 0;
1435}
1436
1437void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1438 if (rawEvent->type == EV_REL) {
1439 switch (rawEvent->code) {
1440 case REL_X:
1441 mRelX = rawEvent->value;
1442 break;
1443 case REL_Y:
1444 mRelY = rawEvent->value;
1445 break;
1446 }
1447 }
1448}
1449
1450void CursorMotionAccumulator::finishSync() {
1451 clearRelativeAxes();
1452}
1453
1454
1455// --- CursorScrollAccumulator ---
1456
1457CursorScrollAccumulator::CursorScrollAccumulator() :
1458 mHaveRelWheel(false), mHaveRelHWheel(false) {
1459 clearRelativeAxes();
1460}
1461
1462void CursorScrollAccumulator::configure(InputDevice* device) {
1463 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1464 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1465}
1466
1467void CursorScrollAccumulator::reset(InputDevice* device) {
1468 clearRelativeAxes();
1469}
1470
1471void CursorScrollAccumulator::clearRelativeAxes() {
1472 mRelWheel = 0;
1473 mRelHWheel = 0;
1474}
1475
1476void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1477 if (rawEvent->type == EV_REL) {
1478 switch (rawEvent->code) {
1479 case REL_WHEEL:
1480 mRelWheel = rawEvent->value;
1481 break;
1482 case REL_HWHEEL:
1483 mRelHWheel = rawEvent->value;
1484 break;
1485 }
1486 }
1487}
1488
1489void CursorScrollAccumulator::finishSync() {
1490 clearRelativeAxes();
1491}
1492
1493
1494// --- TouchButtonAccumulator ---
1495
1496TouchButtonAccumulator::TouchButtonAccumulator() :
1497 mHaveBtnTouch(false), mHaveStylus(false) {
1498 clearButtons();
1499}
1500
1501void TouchButtonAccumulator::configure(InputDevice* device) {
1502 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1503 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1504 || device->hasKey(BTN_TOOL_RUBBER)
1505 || device->hasKey(BTN_TOOL_BRUSH)
1506 || device->hasKey(BTN_TOOL_PENCIL)
1507 || device->hasKey(BTN_TOOL_AIRBRUSH);
1508}
1509
1510void TouchButtonAccumulator::reset(InputDevice* device) {
1511 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1512 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001513 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1514 mBtnStylus2 =
1515 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001516 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1517 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1518 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1519 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1520 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1521 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1522 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1523 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1524 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1525 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1526 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1527}
1528
1529void TouchButtonAccumulator::clearButtons() {
1530 mBtnTouch = 0;
1531 mBtnStylus = 0;
1532 mBtnStylus2 = 0;
1533 mBtnToolFinger = 0;
1534 mBtnToolPen = 0;
1535 mBtnToolRubber = 0;
1536 mBtnToolBrush = 0;
1537 mBtnToolPencil = 0;
1538 mBtnToolAirbrush = 0;
1539 mBtnToolMouse = 0;
1540 mBtnToolLens = 0;
1541 mBtnToolDoubleTap = 0;
1542 mBtnToolTripleTap = 0;
1543 mBtnToolQuadTap = 0;
1544}
1545
1546void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1547 if (rawEvent->type == EV_KEY) {
1548 switch (rawEvent->code) {
1549 case BTN_TOUCH:
1550 mBtnTouch = rawEvent->value;
1551 break;
1552 case BTN_STYLUS:
1553 mBtnStylus = rawEvent->value;
1554 break;
1555 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001556 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 mBtnStylus2 = rawEvent->value;
1558 break;
1559 case BTN_TOOL_FINGER:
1560 mBtnToolFinger = rawEvent->value;
1561 break;
1562 case BTN_TOOL_PEN:
1563 mBtnToolPen = rawEvent->value;
1564 break;
1565 case BTN_TOOL_RUBBER:
1566 mBtnToolRubber = rawEvent->value;
1567 break;
1568 case BTN_TOOL_BRUSH:
1569 mBtnToolBrush = rawEvent->value;
1570 break;
1571 case BTN_TOOL_PENCIL:
1572 mBtnToolPencil = rawEvent->value;
1573 break;
1574 case BTN_TOOL_AIRBRUSH:
1575 mBtnToolAirbrush = rawEvent->value;
1576 break;
1577 case BTN_TOOL_MOUSE:
1578 mBtnToolMouse = rawEvent->value;
1579 break;
1580 case BTN_TOOL_LENS:
1581 mBtnToolLens = rawEvent->value;
1582 break;
1583 case BTN_TOOL_DOUBLETAP:
1584 mBtnToolDoubleTap = rawEvent->value;
1585 break;
1586 case BTN_TOOL_TRIPLETAP:
1587 mBtnToolTripleTap = rawEvent->value;
1588 break;
1589 case BTN_TOOL_QUADTAP:
1590 mBtnToolQuadTap = rawEvent->value;
1591 break;
1592 }
1593 }
1594}
1595
1596uint32_t TouchButtonAccumulator::getButtonState() const {
1597 uint32_t result = 0;
1598 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001599 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 }
1601 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001602 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 }
1604 return result;
1605}
1606
1607int32_t TouchButtonAccumulator::getToolType() const {
1608 if (mBtnToolMouse || mBtnToolLens) {
1609 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1610 }
1611 if (mBtnToolRubber) {
1612 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1613 }
1614 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1615 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1616 }
1617 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1618 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1619 }
1620 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1621}
1622
1623bool TouchButtonAccumulator::isToolActive() const {
1624 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1625 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1626 || mBtnToolMouse || mBtnToolLens
1627 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1628}
1629
1630bool TouchButtonAccumulator::isHovering() const {
1631 return mHaveBtnTouch && !mBtnTouch;
1632}
1633
1634bool TouchButtonAccumulator::hasStylus() const {
1635 return mHaveStylus;
1636}
1637
1638
1639// --- RawPointerAxes ---
1640
1641RawPointerAxes::RawPointerAxes() {
1642 clear();
1643}
1644
1645void RawPointerAxes::clear() {
1646 x.clear();
1647 y.clear();
1648 pressure.clear();
1649 touchMajor.clear();
1650 touchMinor.clear();
1651 toolMajor.clear();
1652 toolMinor.clear();
1653 orientation.clear();
1654 distance.clear();
1655 tiltX.clear();
1656 tiltY.clear();
1657 trackingId.clear();
1658 slot.clear();
1659}
1660
1661
1662// --- RawPointerData ---
1663
1664RawPointerData::RawPointerData() {
1665 clear();
1666}
1667
1668void RawPointerData::clear() {
1669 pointerCount = 0;
1670 clearIdBits();
1671}
1672
1673void RawPointerData::copyFrom(const RawPointerData& other) {
1674 pointerCount = other.pointerCount;
1675 hoveringIdBits = other.hoveringIdBits;
1676 touchingIdBits = other.touchingIdBits;
1677
1678 for (uint32_t i = 0; i < pointerCount; i++) {
1679 pointers[i] = other.pointers[i];
1680
1681 int id = pointers[i].id;
1682 idToIndex[id] = other.idToIndex[id];
1683 }
1684}
1685
1686void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1687 float x = 0, y = 0;
1688 uint32_t count = touchingIdBits.count();
1689 if (count) {
1690 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1691 uint32_t id = idBits.clearFirstMarkedBit();
1692 const Pointer& pointer = pointerForId(id);
1693 x += pointer.x;
1694 y += pointer.y;
1695 }
1696 x /= count;
1697 y /= count;
1698 }
1699 *outX = x;
1700 *outY = y;
1701}
1702
1703
1704// --- CookedPointerData ---
1705
1706CookedPointerData::CookedPointerData() {
1707 clear();
1708}
1709
1710void CookedPointerData::clear() {
1711 pointerCount = 0;
1712 hoveringIdBits.clear();
1713 touchingIdBits.clear();
1714}
1715
1716void CookedPointerData::copyFrom(const CookedPointerData& other) {
1717 pointerCount = other.pointerCount;
1718 hoveringIdBits = other.hoveringIdBits;
1719 touchingIdBits = other.touchingIdBits;
1720
1721 for (uint32_t i = 0; i < pointerCount; i++) {
1722 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1723 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1724
1725 int id = pointerProperties[i].id;
1726 idToIndex[id] = other.idToIndex[id];
1727 }
1728}
1729
1730
1731// --- SingleTouchMotionAccumulator ---
1732
1733SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1734 clearAbsoluteAxes();
1735}
1736
1737void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1738 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1739 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1740 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1741 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1742 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1743 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1744 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1745}
1746
1747void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1748 mAbsX = 0;
1749 mAbsY = 0;
1750 mAbsPressure = 0;
1751 mAbsToolWidth = 0;
1752 mAbsDistance = 0;
1753 mAbsTiltX = 0;
1754 mAbsTiltY = 0;
1755}
1756
1757void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1758 if (rawEvent->type == EV_ABS) {
1759 switch (rawEvent->code) {
1760 case ABS_X:
1761 mAbsX = rawEvent->value;
1762 break;
1763 case ABS_Y:
1764 mAbsY = rawEvent->value;
1765 break;
1766 case ABS_PRESSURE:
1767 mAbsPressure = rawEvent->value;
1768 break;
1769 case ABS_TOOL_WIDTH:
1770 mAbsToolWidth = rawEvent->value;
1771 break;
1772 case ABS_DISTANCE:
1773 mAbsDistance = rawEvent->value;
1774 break;
1775 case ABS_TILT_X:
1776 mAbsTiltX = rawEvent->value;
1777 break;
1778 case ABS_TILT_Y:
1779 mAbsTiltY = rawEvent->value;
1780 break;
1781 }
1782 }
1783}
1784
1785
1786// --- MultiTouchMotionAccumulator ---
1787
1788MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001789 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001790 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791}
1792
1793MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1794 delete[] mSlots;
1795}
1796
1797void MultiTouchMotionAccumulator::configure(InputDevice* device,
1798 size_t slotCount, bool usingSlotsProtocol) {
1799 mSlotCount = slotCount;
1800 mUsingSlotsProtocol = usingSlotsProtocol;
1801 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1802
1803 delete[] mSlots;
1804 mSlots = new Slot[slotCount];
1805}
1806
1807void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1808 // Unfortunately there is no way to read the initial contents of the slots.
1809 // So when we reset the accumulator, we must assume they are all zeroes.
1810 if (mUsingSlotsProtocol) {
1811 // Query the driver for the current slot index and use it as the initial slot
1812 // before we start reading events from the device. It is possible that the
1813 // current slot index will not be the same as it was when the first event was
1814 // written into the evdev buffer, which means the input mapper could start
1815 // out of sync with the initial state of the events in the evdev buffer.
1816 // In the extremely unlikely case that this happens, the data from
1817 // two slots will be confused until the next ABS_MT_SLOT event is received.
1818 // This can cause the touch point to "jump", but at least there will be
1819 // no stuck touches.
1820 int32_t initialSlot;
1821 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1822 ABS_MT_SLOT, &initialSlot);
1823 if (status) {
1824 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1825 initialSlot = -1;
1826 }
1827 clearSlots(initialSlot);
1828 } else {
1829 clearSlots(-1);
1830 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001831 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832}
1833
1834void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1835 if (mSlots) {
1836 for (size_t i = 0; i < mSlotCount; i++) {
1837 mSlots[i].clear();
1838 }
1839 }
1840 mCurrentSlot = initialSlot;
1841}
1842
1843void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1844 if (rawEvent->type == EV_ABS) {
1845 bool newSlot = false;
1846 if (mUsingSlotsProtocol) {
1847 if (rawEvent->code == ABS_MT_SLOT) {
1848 mCurrentSlot = rawEvent->value;
1849 newSlot = true;
1850 }
1851 } else if (mCurrentSlot < 0) {
1852 mCurrentSlot = 0;
1853 }
1854
1855 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1856#if DEBUG_POINTERS
1857 if (newSlot) {
1858 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001859 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 mCurrentSlot, mSlotCount - 1);
1861 }
1862#endif
1863 } else {
1864 Slot* slot = &mSlots[mCurrentSlot];
1865
1866 switch (rawEvent->code) {
1867 case ABS_MT_POSITION_X:
1868 slot->mInUse = true;
1869 slot->mAbsMTPositionX = rawEvent->value;
1870 break;
1871 case ABS_MT_POSITION_Y:
1872 slot->mInUse = true;
1873 slot->mAbsMTPositionY = rawEvent->value;
1874 break;
1875 case ABS_MT_TOUCH_MAJOR:
1876 slot->mInUse = true;
1877 slot->mAbsMTTouchMajor = rawEvent->value;
1878 break;
1879 case ABS_MT_TOUCH_MINOR:
1880 slot->mInUse = true;
1881 slot->mAbsMTTouchMinor = rawEvent->value;
1882 slot->mHaveAbsMTTouchMinor = true;
1883 break;
1884 case ABS_MT_WIDTH_MAJOR:
1885 slot->mInUse = true;
1886 slot->mAbsMTWidthMajor = rawEvent->value;
1887 break;
1888 case ABS_MT_WIDTH_MINOR:
1889 slot->mInUse = true;
1890 slot->mAbsMTWidthMinor = rawEvent->value;
1891 slot->mHaveAbsMTWidthMinor = true;
1892 break;
1893 case ABS_MT_ORIENTATION:
1894 slot->mInUse = true;
1895 slot->mAbsMTOrientation = rawEvent->value;
1896 break;
1897 case ABS_MT_TRACKING_ID:
1898 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1899 // The slot is no longer in use but it retains its previous contents,
1900 // which may be reused for subsequent touches.
1901 slot->mInUse = false;
1902 } else {
1903 slot->mInUse = true;
1904 slot->mAbsMTTrackingId = rawEvent->value;
1905 }
1906 break;
1907 case ABS_MT_PRESSURE:
1908 slot->mInUse = true;
1909 slot->mAbsMTPressure = rawEvent->value;
1910 break;
1911 case ABS_MT_DISTANCE:
1912 slot->mInUse = true;
1913 slot->mAbsMTDistance = rawEvent->value;
1914 break;
1915 case ABS_MT_TOOL_TYPE:
1916 slot->mInUse = true;
1917 slot->mAbsMTToolType = rawEvent->value;
1918 slot->mHaveAbsMTToolType = true;
1919 break;
1920 }
1921 }
1922 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1923 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1924 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001925 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1926 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 }
1928}
1929
1930void MultiTouchMotionAccumulator::finishSync() {
1931 if (!mUsingSlotsProtocol) {
1932 clearSlots(-1);
1933 }
1934}
1935
1936bool MultiTouchMotionAccumulator::hasStylus() const {
1937 return mHaveStylus;
1938}
1939
1940
1941// --- MultiTouchMotionAccumulator::Slot ---
1942
1943MultiTouchMotionAccumulator::Slot::Slot() {
1944 clear();
1945}
1946
1947void MultiTouchMotionAccumulator::Slot::clear() {
1948 mInUse = false;
1949 mHaveAbsMTTouchMinor = false;
1950 mHaveAbsMTWidthMinor = false;
1951 mHaveAbsMTToolType = false;
1952 mAbsMTPositionX = 0;
1953 mAbsMTPositionY = 0;
1954 mAbsMTTouchMajor = 0;
1955 mAbsMTTouchMinor = 0;
1956 mAbsMTWidthMajor = 0;
1957 mAbsMTWidthMinor = 0;
1958 mAbsMTOrientation = 0;
1959 mAbsMTTrackingId = -1;
1960 mAbsMTPressure = 0;
1961 mAbsMTDistance = 0;
1962 mAbsMTToolType = 0;
1963}
1964
1965int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1966 if (mHaveAbsMTToolType) {
1967 switch (mAbsMTToolType) {
1968 case MT_TOOL_FINGER:
1969 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1970 case MT_TOOL_PEN:
1971 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1972 }
1973 }
1974 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1975}
1976
1977
1978// --- InputMapper ---
1979
1980InputMapper::InputMapper(InputDevice* device) :
1981 mDevice(device), mContext(device->getContext()) {
1982}
1983
1984InputMapper::~InputMapper() {
1985}
1986
1987void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1988 info->addSource(getSources());
1989}
1990
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001991void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992}
1993
1994void InputMapper::configure(nsecs_t when,
1995 const InputReaderConfiguration* config, uint32_t changes) {
1996}
1997
1998void InputMapper::reset(nsecs_t when) {
1999}
2000
2001void InputMapper::timeoutExpired(nsecs_t when) {
2002}
2003
2004int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2005 return AKEY_STATE_UNKNOWN;
2006}
2007
2008int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2009 return AKEY_STATE_UNKNOWN;
2010}
2011
2012int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2013 return AKEY_STATE_UNKNOWN;
2014}
2015
2016bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2017 const int32_t* keyCodes, uint8_t* outFlags) {
2018 return false;
2019}
2020
2021void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2022 int32_t token) {
2023}
2024
2025void InputMapper::cancelVibrate(int32_t token) {
2026}
2027
Jeff Brownc9aa6282015-02-11 19:03:28 -08002028void InputMapper::cancelTouch(nsecs_t when) {
2029}
2030
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031int32_t InputMapper::getMetaState() {
2032 return 0;
2033}
2034
Andrii Kulian763a3a42016-03-08 10:46:16 -08002035void InputMapper::updateMetaState(int32_t keyCode) {
2036}
2037
Michael Wright842500e2015-03-13 17:32:02 -07002038void InputMapper::updateExternalStylusState(const StylusState& state) {
2039
2040}
2041
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042void InputMapper::fadePointer() {
2043}
2044
2045status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2046 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2047}
2048
2049void InputMapper::bumpGeneration() {
2050 mDevice->bumpGeneration();
2051}
2052
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002053void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 const RawAbsoluteAxisInfo& axis, const char* name) {
2055 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002056 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2058 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002059 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 }
2061}
2062
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002063void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2064 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2065 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2066 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2067 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002068}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069
2070// --- SwitchInputMapper ---
2071
2072SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002073 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074}
2075
2076SwitchInputMapper::~SwitchInputMapper() {
2077}
2078
2079uint32_t SwitchInputMapper::getSources() {
2080 return AINPUT_SOURCE_SWITCH;
2081}
2082
2083void SwitchInputMapper::process(const RawEvent* rawEvent) {
2084 switch (rawEvent->type) {
2085 case EV_SW:
2086 processSwitch(rawEvent->code, rawEvent->value);
2087 break;
2088
2089 case EV_SYN:
2090 if (rawEvent->code == SYN_REPORT) {
2091 sync(rawEvent->when);
2092 }
2093 }
2094}
2095
2096void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2097 if (switchCode >= 0 && switchCode < 32) {
2098 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002099 mSwitchValues |= 1 << switchCode;
2100 } else {
2101 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 }
2103 mUpdatedSwitchMask |= 1 << switchCode;
2104 }
2105}
2106
2107void SwitchInputMapper::sync(nsecs_t when) {
2108 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002109 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002110 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 getListener()->notifySwitch(&args);
2112
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113 mUpdatedSwitchMask = 0;
2114 }
2115}
2116
2117int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2118 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2119}
2120
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002121void SwitchInputMapper::dump(std::string& dump) {
2122 dump += INDENT2 "Switch Input Mapper:\n";
2123 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002124}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125
2126// --- VibratorInputMapper ---
2127
2128VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2129 InputMapper(device), mVibrating(false) {
2130}
2131
2132VibratorInputMapper::~VibratorInputMapper() {
2133}
2134
2135uint32_t VibratorInputMapper::getSources() {
2136 return 0;
2137}
2138
2139void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2140 InputMapper::populateDeviceInfo(info);
2141
2142 info->setVibrator(true);
2143}
2144
2145void VibratorInputMapper::process(const RawEvent* rawEvent) {
2146 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2147}
2148
2149void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2150 int32_t token) {
2151#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002152 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002153 for (size_t i = 0; i < patternSize; i++) {
2154 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002155 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002157 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002158 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002159 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002160 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161#endif
2162
2163 mVibrating = true;
2164 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2165 mPatternSize = patternSize;
2166 mRepeat = repeat;
2167 mToken = token;
2168 mIndex = -1;
2169
2170 nextStep();
2171}
2172
2173void VibratorInputMapper::cancelVibrate(int32_t token) {
2174#if DEBUG_VIBRATOR
2175 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2176#endif
2177
2178 if (mVibrating && mToken == token) {
2179 stopVibrating();
2180 }
2181}
2182
2183void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2184 if (mVibrating) {
2185 if (when >= mNextStepTime) {
2186 nextStep();
2187 } else {
2188 getContext()->requestTimeoutAtTime(mNextStepTime);
2189 }
2190 }
2191}
2192
2193void VibratorInputMapper::nextStep() {
2194 mIndex += 1;
2195 if (size_t(mIndex) >= mPatternSize) {
2196 if (mRepeat < 0) {
2197 // We are done.
2198 stopVibrating();
2199 return;
2200 }
2201 mIndex = mRepeat;
2202 }
2203
2204 bool vibratorOn = mIndex & 1;
2205 nsecs_t duration = mPattern[mIndex];
2206 if (vibratorOn) {
2207#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002208 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209#endif
2210 getEventHub()->vibrate(getDeviceId(), duration);
2211 } else {
2212#if DEBUG_VIBRATOR
2213 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2214#endif
2215 getEventHub()->cancelVibrate(getDeviceId());
2216 }
2217 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2218 mNextStepTime = now + duration;
2219 getContext()->requestTimeoutAtTime(mNextStepTime);
2220#if DEBUG_VIBRATOR
2221 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2222#endif
2223}
2224
2225void VibratorInputMapper::stopVibrating() {
2226 mVibrating = false;
2227#if DEBUG_VIBRATOR
2228 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2229#endif
2230 getEventHub()->cancelVibrate(getDeviceId());
2231}
2232
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002233void VibratorInputMapper::dump(std::string& dump) {
2234 dump += INDENT2 "Vibrator Input Mapper:\n";
2235 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236}
2237
2238
2239// --- KeyboardInputMapper ---
2240
2241KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2242 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002243 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244}
2245
2246KeyboardInputMapper::~KeyboardInputMapper() {
2247}
2248
2249uint32_t KeyboardInputMapper::getSources() {
2250 return mSource;
2251}
2252
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002253int32_t KeyboardInputMapper::getOrientation() {
2254 if (mViewport) {
2255 return mViewport->orientation;
2256 }
2257 return DISPLAY_ORIENTATION_0;
2258}
2259
2260int32_t KeyboardInputMapper::getDisplayId() {
2261 if (mViewport) {
2262 return mViewport->displayId;
2263 }
2264 return ADISPLAY_ID_NONE;
2265}
2266
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2268 InputMapper::populateDeviceInfo(info);
2269
2270 info->setKeyboardType(mKeyboardType);
2271 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2272}
2273
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002274void KeyboardInputMapper::dump(std::string& dump) {
2275 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002277 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002278 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002279 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2280 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2281 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282}
2283
2284
2285void KeyboardInputMapper::configure(nsecs_t when,
2286 const InputReaderConfiguration* config, uint32_t changes) {
2287 InputMapper::configure(when, config, changes);
2288
2289 if (!changes) { // first time only
2290 // Configure basic parameters.
2291 configureParameters();
2292 }
2293
2294 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002295 if (mParameters.orientationAware) {
2296 DisplayViewport dvp;
Yi Kong9b14ac62018-07-17 13:48:38 -07002297 config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, nullptr, &dvp);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002298 mViewport = dvp;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002299 }
2300 }
2301}
2302
Ivan Podogovb9afef32017-02-13 15:34:32 +00002303static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2304 int32_t mapped = 0;
2305 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2306 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2307 if (stemKeyRotationMap[i][0] == keyCode) {
2308 stemKeyRotationMap[i][1] = mapped;
2309 return;
2310 }
2311 }
2312 }
2313}
2314
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315void KeyboardInputMapper::configureParameters() {
2316 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002317 const PropertyMap& config = getDevice()->getConfiguration();
2318 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 mParameters.orientationAware);
2320
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002322 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2323 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2324 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2325 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002327
2328 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002329 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002330 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331}
2332
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002333void KeyboardInputMapper::dumpParameters(std::string& dump) {
2334 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002335 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002337 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002338 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339}
2340
2341void KeyboardInputMapper::reset(nsecs_t when) {
2342 mMetaState = AMETA_NONE;
2343 mDownTime = 0;
2344 mKeyDowns.clear();
2345 mCurrentHidUsage = 0;
2346
2347 resetLedState();
2348
2349 InputMapper::reset(when);
2350}
2351
2352void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2353 switch (rawEvent->type) {
2354 case EV_KEY: {
2355 int32_t scanCode = rawEvent->code;
2356 int32_t usageCode = mCurrentHidUsage;
2357 mCurrentHidUsage = 0;
2358
2359 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002360 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361 }
2362 break;
2363 }
2364 case EV_MSC: {
2365 if (rawEvent->code == MSC_SCAN) {
2366 mCurrentHidUsage = rawEvent->value;
2367 }
2368 break;
2369 }
2370 case EV_SYN: {
2371 if (rawEvent->code == SYN_REPORT) {
2372 mCurrentHidUsage = 0;
2373 }
2374 }
2375 }
2376}
2377
2378bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2379 return scanCode < BTN_MOUSE
2380 || scanCode >= KEY_OK
2381 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2382 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2383}
2384
Michael Wright58ba9882017-07-26 16:19:11 +01002385bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2386 switch (keyCode) {
2387 case AKEYCODE_MEDIA_PLAY:
2388 case AKEYCODE_MEDIA_PAUSE:
2389 case AKEYCODE_MEDIA_PLAY_PAUSE:
2390 case AKEYCODE_MUTE:
2391 case AKEYCODE_HEADSETHOOK:
2392 case AKEYCODE_MEDIA_STOP:
2393 case AKEYCODE_MEDIA_NEXT:
2394 case AKEYCODE_MEDIA_PREVIOUS:
2395 case AKEYCODE_MEDIA_REWIND:
2396 case AKEYCODE_MEDIA_RECORD:
2397 case AKEYCODE_MEDIA_FAST_FORWARD:
2398 case AKEYCODE_MEDIA_SKIP_FORWARD:
2399 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2400 case AKEYCODE_MEDIA_STEP_FORWARD:
2401 case AKEYCODE_MEDIA_STEP_BACKWARD:
2402 case AKEYCODE_MEDIA_AUDIO_TRACK:
2403 case AKEYCODE_VOLUME_UP:
2404 case AKEYCODE_VOLUME_DOWN:
2405 case AKEYCODE_VOLUME_MUTE:
2406 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2407 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2408 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2409 return true;
2410 }
2411 return false;
2412}
2413
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002414void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2415 int32_t usageCode) {
2416 int32_t keyCode;
2417 int32_t keyMetaState;
2418 uint32_t policyFlags;
2419
2420 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2421 &keyCode, &keyMetaState, &policyFlags)) {
2422 keyCode = AKEYCODE_UNKNOWN;
2423 keyMetaState = mMetaState;
2424 policyFlags = 0;
2425 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426
2427 if (down) {
2428 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002429 if (mParameters.orientationAware) {
2430 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431 }
2432
2433 // Add key down.
2434 ssize_t keyDownIndex = findKeyDown(scanCode);
2435 if (keyDownIndex >= 0) {
2436 // key repeat, be sure to use same keycode as before in case of rotation
2437 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2438 } else {
2439 // key down
2440 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2441 && mContext->shouldDropVirtualKey(when,
2442 getDevice(), keyCode, scanCode)) {
2443 return;
2444 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002445 if (policyFlags & POLICY_FLAG_GESTURE) {
2446 mDevice->cancelTouch(when);
2447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448
2449 mKeyDowns.push();
2450 KeyDown& keyDown = mKeyDowns.editTop();
2451 keyDown.keyCode = keyCode;
2452 keyDown.scanCode = scanCode;
2453 }
2454
2455 mDownTime = when;
2456 } else {
2457 // Remove key down.
2458 ssize_t keyDownIndex = findKeyDown(scanCode);
2459 if (keyDownIndex >= 0) {
2460 // key up, be sure to use same keycode as before in case of rotation
2461 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2462 mKeyDowns.removeAt(size_t(keyDownIndex));
2463 } else {
2464 // key was not actually down
2465 ALOGI("Dropping key up from device %s because the key was not down. "
2466 "keyCode=%d, scanCode=%d",
2467 getDeviceName().string(), keyCode, scanCode);
2468 return;
2469 }
2470 }
2471
Andrii Kulian763a3a42016-03-08 10:46:16 -08002472 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002473 // If global meta state changed send it along with the key.
2474 // If it has not changed then we'll use what keymap gave us,
2475 // since key replacement logic might temporarily reset a few
2476 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002477 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478 }
2479
2480 nsecs_t downTime = mDownTime;
2481
2482 // Key down on external an keyboard should wake the device.
2483 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2484 // For internal keyboards, the key layout file should specify the policy flags for
2485 // each wake key individually.
2486 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002487 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002488 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489 }
2490
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002491 if (mParameters.handlesKeyRepeat) {
2492 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2493 }
2494
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002495 NotifyKeyArgs args(when, getDeviceId(), mSource, getDisplayId(), policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002497 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002498 getListener()->notifyKey(&args);
2499}
2500
2501ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2502 size_t n = mKeyDowns.size();
2503 for (size_t i = 0; i < n; i++) {
2504 if (mKeyDowns[i].scanCode == scanCode) {
2505 return i;
2506 }
2507 }
2508 return -1;
2509}
2510
2511int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2512 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2513}
2514
2515int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2516 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2517}
2518
2519bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2520 const int32_t* keyCodes, uint8_t* outFlags) {
2521 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2522}
2523
2524int32_t KeyboardInputMapper::getMetaState() {
2525 return mMetaState;
2526}
2527
Andrii Kulian763a3a42016-03-08 10:46:16 -08002528void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2529 updateMetaStateIfNeeded(keyCode, false);
2530}
2531
2532bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2533 int32_t oldMetaState = mMetaState;
2534 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2535 bool metaStateChanged = oldMetaState != newMetaState;
2536 if (metaStateChanged) {
2537 mMetaState = newMetaState;
2538 updateLedState(false);
2539
2540 getContext()->updateGlobalMetaState();
2541 }
2542
2543 return metaStateChanged;
2544}
2545
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546void KeyboardInputMapper::resetLedState() {
2547 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2548 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2549 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2550
2551 updateLedState(true);
2552}
2553
2554void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2555 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2556 ledState.on = false;
2557}
2558
2559void KeyboardInputMapper::updateLedState(bool reset) {
2560 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2561 AMETA_CAPS_LOCK_ON, reset);
2562 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2563 AMETA_NUM_LOCK_ON, reset);
2564 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2565 AMETA_SCROLL_LOCK_ON, reset);
2566}
2567
2568void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2569 int32_t led, int32_t modifier, bool reset) {
2570 if (ledState.avail) {
2571 bool desiredState = (mMetaState & modifier) != 0;
2572 if (reset || ledState.on != desiredState) {
2573 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2574 ledState.on = desiredState;
2575 }
2576 }
2577}
2578
2579
2580// --- CursorInputMapper ---
2581
2582CursorInputMapper::CursorInputMapper(InputDevice* device) :
2583 InputMapper(device) {
2584}
2585
2586CursorInputMapper::~CursorInputMapper() {
2587}
2588
2589uint32_t CursorInputMapper::getSources() {
2590 return mSource;
2591}
2592
2593void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2594 InputMapper::populateDeviceInfo(info);
2595
2596 if (mParameters.mode == Parameters::MODE_POINTER) {
2597 float minX, minY, maxX, maxY;
2598 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2599 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2600 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2601 }
2602 } else {
2603 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2604 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2605 }
2606 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2607
2608 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2609 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2610 }
2611 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2612 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2613 }
2614}
2615
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002616void CursorInputMapper::dump(std::string& dump) {
2617 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002619 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2620 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2621 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2622 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2623 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002625 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002627 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2628 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2629 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2630 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2631 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2632 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633}
2634
2635void CursorInputMapper::configure(nsecs_t when,
2636 const InputReaderConfiguration* config, uint32_t changes) {
2637 InputMapper::configure(when, config, changes);
2638
2639 if (!changes) { // first time only
2640 mCursorScrollAccumulator.configure(getDevice());
2641
2642 // Configure basic parameters.
2643 configureParameters();
2644
2645 // Configure device mode.
2646 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002647 case Parameters::MODE_POINTER_RELATIVE:
2648 // Should not happen during first time configuration.
2649 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2650 mParameters.mode = Parameters::MODE_POINTER;
2651 // fall through.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652 case Parameters::MODE_POINTER:
2653 mSource = AINPUT_SOURCE_MOUSE;
2654 mXPrecision = 1.0f;
2655 mYPrecision = 1.0f;
2656 mXScale = 1.0f;
2657 mYScale = 1.0f;
2658 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2659 break;
2660 case Parameters::MODE_NAVIGATION:
2661 mSource = AINPUT_SOURCE_TRACKBALL;
2662 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2663 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2664 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2665 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2666 break;
2667 }
2668
2669 mVWheelScale = 1.0f;
2670 mHWheelScale = 1.0f;
2671 }
2672
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002673 if ((!changes && config->pointerCapture)
2674 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2675 if (config->pointerCapture) {
2676 if (mParameters.mode == Parameters::MODE_POINTER) {
2677 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2678 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2679 // Keep PointerController around in order to preserve the pointer position.
2680 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2681 } else {
2682 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2683 }
2684 } else {
2685 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2686 mParameters.mode = Parameters::MODE_POINTER;
2687 mSource = AINPUT_SOURCE_MOUSE;
2688 } else {
2689 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2690 }
2691 }
2692 bumpGeneration();
2693 if (changes) {
2694 getDevice()->notifyReset(when);
2695 }
2696 }
2697
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2699 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2700 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2701 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2702 }
2703
2704 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002705 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
2707 DisplayViewport v;
Yi Kong9b14ac62018-07-17 13:48:38 -07002708 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, nullptr, &v)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709 mOrientation = v.orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002711 }
2712 bumpGeneration();
2713 }
2714}
2715
2716void CursorInputMapper::configureParameters() {
2717 mParameters.mode = Parameters::MODE_POINTER;
2718 String8 cursorModeString;
2719 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2720 if (cursorModeString == "navigation") {
2721 mParameters.mode = Parameters::MODE_NAVIGATION;
2722 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2723 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2724 }
2725 }
2726
2727 mParameters.orientationAware = false;
2728 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2729 mParameters.orientationAware);
2730
2731 mParameters.hasAssociatedDisplay = false;
2732 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2733 mParameters.hasAssociatedDisplay = true;
2734 }
2735}
2736
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002737void CursorInputMapper::dumpParameters(std::string& dump) {
2738 dump += INDENT3 "Parameters:\n";
2739 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 toString(mParameters.hasAssociatedDisplay));
2741
2742 switch (mParameters.mode) {
2743 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002744 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002746 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002747 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002748 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002749 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002750 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002751 break;
2752 default:
2753 ALOG_ASSERT(false);
2754 }
2755
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002756 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002757 toString(mParameters.orientationAware));
2758}
2759
2760void CursorInputMapper::reset(nsecs_t when) {
2761 mButtonState = 0;
2762 mDownTime = 0;
2763
2764 mPointerVelocityControl.reset();
2765 mWheelXVelocityControl.reset();
2766 mWheelYVelocityControl.reset();
2767
2768 mCursorButtonAccumulator.reset(getDevice());
2769 mCursorMotionAccumulator.reset(getDevice());
2770 mCursorScrollAccumulator.reset(getDevice());
2771
2772 InputMapper::reset(when);
2773}
2774
2775void CursorInputMapper::process(const RawEvent* rawEvent) {
2776 mCursorButtonAccumulator.process(rawEvent);
2777 mCursorMotionAccumulator.process(rawEvent);
2778 mCursorScrollAccumulator.process(rawEvent);
2779
2780 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2781 sync(rawEvent->when);
2782 }
2783}
2784
2785void CursorInputMapper::sync(nsecs_t when) {
2786 int32_t lastButtonState = mButtonState;
2787 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2788 mButtonState = currentButtonState;
2789
2790 bool wasDown = isPointerDown(lastButtonState);
2791 bool down = isPointerDown(currentButtonState);
2792 bool downChanged;
2793 if (!wasDown && down) {
2794 mDownTime = when;
2795 downChanged = true;
2796 } else if (wasDown && !down) {
2797 downChanged = true;
2798 } else {
2799 downChanged = false;
2800 }
2801 nsecs_t downTime = mDownTime;
2802 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002803 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2804 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805
2806 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2807 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2808 bool moved = deltaX != 0 || deltaY != 0;
2809
2810 // Rotate delta according to orientation if needed.
2811 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2812 && (deltaX != 0.0f || deltaY != 0.0f)) {
2813 rotateDelta(mOrientation, &deltaX, &deltaY);
2814 }
2815
2816 // Move the pointer.
2817 PointerProperties pointerProperties;
2818 pointerProperties.clear();
2819 pointerProperties.id = 0;
2820 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2821
2822 PointerCoords pointerCoords;
2823 pointerCoords.clear();
2824
2825 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2826 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2827 bool scrolled = vscroll != 0 || hscroll != 0;
2828
Yi Kong9b14ac62018-07-17 13:48:38 -07002829 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2830 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002831
2832 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2833
2834 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002835 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002836 if (moved || scrolled || buttonsChanged) {
2837 mPointerController->setPresentation(
2838 PointerControllerInterface::PRESENTATION_POINTER);
2839
2840 if (moved) {
2841 mPointerController->move(deltaX, deltaY);
2842 }
2843
2844 if (buttonsChanged) {
2845 mPointerController->setButtonState(currentButtonState);
2846 }
2847
2848 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2849 }
2850
2851 float x, y;
2852 mPointerController->getPosition(&x, &y);
2853 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2854 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002855 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2856 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857 displayId = ADISPLAY_ID_DEFAULT;
2858 } else {
2859 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2860 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2861 displayId = ADISPLAY_ID_NONE;
2862 }
2863
2864 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2865
2866 // Moving an external trackball or mouse should wake the device.
2867 // We don't do this for internal cursor devices to prevent them from waking up
2868 // the device in your pocket.
2869 // TODO: Use the input device configuration to control this behavior more finely.
2870 uint32_t policyFlags = 0;
2871 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002872 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 }
2874
2875 // Synthesize key down from buttons if needed.
2876 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002877 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878
2879 // Send motion event.
2880 if (downChanged || moved || scrolled || buttonsChanged) {
2881 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002882 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883 int32_t motionEventAction;
2884 if (downChanged) {
2885 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002886 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2888 } else {
2889 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2890 }
2891
Michael Wright7b159c92015-05-14 14:48:03 +01002892 if (buttonsReleased) {
2893 BitSet32 released(buttonsReleased);
2894 while (!released.isEmpty()) {
2895 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2896 buttonState &= ~actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002897 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002898 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2899 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002900 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002901 mXPrecision, mYPrecision, downTime);
2902 getListener()->notifyMotion(&releaseArgs);
2903 }
2904 }
2905
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002906 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002907 motionEventAction, 0, 0, metaState, currentButtonState,
2908 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002909 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910 mXPrecision, mYPrecision, downTime);
2911 getListener()->notifyMotion(&args);
2912
Michael Wright7b159c92015-05-14 14:48:03 +01002913 if (buttonsPressed) {
2914 BitSet32 pressed(buttonsPressed);
2915 while (!pressed.isEmpty()) {
2916 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2917 buttonState |= actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002918 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002919 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2920 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002921 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002922 mXPrecision, mYPrecision, downTime);
2923 getListener()->notifyMotion(&pressArgs);
2924 }
2925 }
2926
2927 ALOG_ASSERT(buttonState == currentButtonState);
2928
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929 // Send hover move after UP to tell the application that the mouse is hovering now.
2930 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002931 && (mSource == AINPUT_SOURCE_MOUSE)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002932 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002933 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002935 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002936 mXPrecision, mYPrecision, downTime);
2937 getListener()->notifyMotion(&hoverArgs);
2938 }
2939
2940 // Send scroll events.
2941 if (scrolled) {
2942 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2943 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2944
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002945 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002946 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002947 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002948 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002949 mXPrecision, mYPrecision, downTime);
2950 getListener()->notifyMotion(&scrollArgs);
2951 }
2952 }
2953
2954 // Synthesize key up from buttons if needed.
2955 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002956 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002957
2958 mCursorMotionAccumulator.finishSync();
2959 mCursorScrollAccumulator.finishSync();
2960}
2961
2962int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2963 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2964 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2965 } else {
2966 return AKEY_STATE_UNKNOWN;
2967 }
2968}
2969
2970void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002971 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002972 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2973 }
2974}
2975
Prashant Malani1941ff52015-08-11 18:29:28 -07002976// --- RotaryEncoderInputMapper ---
2977
2978RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002979 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002980 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2981}
2982
2983RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2984}
2985
2986uint32_t RotaryEncoderInputMapper::getSources() {
2987 return mSource;
2988}
2989
2990void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2991 InputMapper::populateDeviceInfo(info);
2992
2993 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002994 float res = 0.0f;
2995 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2996 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2997 }
2998 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2999 mScalingFactor)) {
3000 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
3001 "default to 1.0!\n");
3002 mScalingFactor = 1.0f;
3003 }
3004 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3005 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003006 }
3007}
3008
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003009void RotaryEncoderInputMapper::dump(std::string& dump) {
3010 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
3011 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07003012 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
3013}
3014
3015void RotaryEncoderInputMapper::configure(nsecs_t when,
3016 const InputReaderConfiguration* config, uint32_t changes) {
3017 InputMapper::configure(when, config, changes);
3018 if (!changes) {
3019 mRotaryEncoderScrollAccumulator.configure(getDevice());
3020 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07003021 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Ivan Podogovad437252016-09-29 16:29:55 +01003022 DisplayViewport v;
Yi Kong9b14ac62018-07-17 13:48:38 -07003023 if (config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, nullptr, &v)) {
Ivan Podogovad437252016-09-29 16:29:55 +01003024 mOrientation = v.orientation;
3025 } else {
3026 mOrientation = DISPLAY_ORIENTATION_0;
3027 }
3028 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003029}
3030
3031void RotaryEncoderInputMapper::reset(nsecs_t when) {
3032 mRotaryEncoderScrollAccumulator.reset(getDevice());
3033
3034 InputMapper::reset(when);
3035}
3036
3037void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3038 mRotaryEncoderScrollAccumulator.process(rawEvent);
3039
3040 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3041 sync(rawEvent->when);
3042 }
3043}
3044
3045void RotaryEncoderInputMapper::sync(nsecs_t when) {
3046 PointerCoords pointerCoords;
3047 pointerCoords.clear();
3048
3049 PointerProperties pointerProperties;
3050 pointerProperties.clear();
3051 pointerProperties.id = 0;
3052 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3053
3054 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3055 bool scrolled = scroll != 0;
3056
3057 // This is not a pointer, so it's not associated with a display.
3058 int32_t displayId = ADISPLAY_ID_NONE;
3059
3060 // Moving the rotary encoder should wake the device (if specified).
3061 uint32_t policyFlags = 0;
3062 if (scrolled && getDevice()->isExternal()) {
3063 policyFlags |= POLICY_FLAG_WAKE;
3064 }
3065
Ivan Podogovad437252016-09-29 16:29:55 +01003066 if (mOrientation == DISPLAY_ORIENTATION_180) {
3067 scroll = -scroll;
3068 }
3069
Prashant Malani1941ff52015-08-11 18:29:28 -07003070 // Send motion event.
3071 if (scrolled) {
3072 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003073 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003074
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003075 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Prashant Malani1941ff52015-08-11 18:29:28 -07003076 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3077 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003078 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Prashant Malani1941ff52015-08-11 18:29:28 -07003079 0, 0, 0);
3080 getListener()->notifyMotion(&scrollArgs);
3081 }
3082
3083 mRotaryEncoderScrollAccumulator.finishSync();
3084}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003085
3086// --- TouchInputMapper ---
3087
3088TouchInputMapper::TouchInputMapper(InputDevice* device) :
3089 InputMapper(device),
3090 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3091 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003092 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3094}
3095
3096TouchInputMapper::~TouchInputMapper() {
3097}
3098
3099uint32_t TouchInputMapper::getSources() {
3100 return mSource;
3101}
3102
3103void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3104 InputMapper::populateDeviceInfo(info);
3105
3106 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3107 info->addMotionRange(mOrientedRanges.x);
3108 info->addMotionRange(mOrientedRanges.y);
3109 info->addMotionRange(mOrientedRanges.pressure);
3110
3111 if (mOrientedRanges.haveSize) {
3112 info->addMotionRange(mOrientedRanges.size);
3113 }
3114
3115 if (mOrientedRanges.haveTouchSize) {
3116 info->addMotionRange(mOrientedRanges.touchMajor);
3117 info->addMotionRange(mOrientedRanges.touchMinor);
3118 }
3119
3120 if (mOrientedRanges.haveToolSize) {
3121 info->addMotionRange(mOrientedRanges.toolMajor);
3122 info->addMotionRange(mOrientedRanges.toolMinor);
3123 }
3124
3125 if (mOrientedRanges.haveOrientation) {
3126 info->addMotionRange(mOrientedRanges.orientation);
3127 }
3128
3129 if (mOrientedRanges.haveDistance) {
3130 info->addMotionRange(mOrientedRanges.distance);
3131 }
3132
3133 if (mOrientedRanges.haveTilt) {
3134 info->addMotionRange(mOrientedRanges.tilt);
3135 }
3136
3137 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3138 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3139 0.0f);
3140 }
3141 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3142 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3143 0.0f);
3144 }
3145 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3146 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3147 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3148 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3149 x.fuzz, x.resolution);
3150 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3151 y.fuzz, y.resolution);
3152 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3153 x.fuzz, x.resolution);
3154 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3155 y.fuzz, y.resolution);
3156 }
3157 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3158 }
3159}
3160
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003161void TouchInputMapper::dump(std::string& dump) {
3162 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163 dumpParameters(dump);
3164 dumpVirtualKeys(dump);
3165 dumpRawPointerAxes(dump);
3166 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003167 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168 dumpSurface(dump);
3169
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003170 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3171 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3172 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3173 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3174 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3175 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3176 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3177 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3178 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3179 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3180 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3181 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3182 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3183 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3184 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3185 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3186 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003188 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3189 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003190 mLastRawState.rawPointerData.pointerCount);
3191 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3192 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003193 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3195 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3196 "toolType=%d, isHovering=%s\n", i,
3197 pointer.id, pointer.x, pointer.y, pointer.pressure,
3198 pointer.touchMajor, pointer.touchMinor,
3199 pointer.toolMajor, pointer.toolMinor,
3200 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3201 pointer.toolType, toString(pointer.isHovering));
3202 }
3203
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003204 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3205 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003206 mLastCookedState.cookedPointerData.pointerCount);
3207 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3208 const PointerProperties& pointerProperties =
3209 mLastCookedState.cookedPointerData.pointerProperties[i];
3210 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003211 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3213 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3214 "toolType=%d, isHovering=%s\n", i,
3215 pointerProperties.id,
3216 pointerCoords.getX(),
3217 pointerCoords.getY(),
3218 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3219 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3220 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3221 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3222 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3223 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3224 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3225 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3226 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003227 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 }
3229
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003230 dump += INDENT3 "Stylus Fusion:\n";
3231 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003232 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003233 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3234 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003235 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003236 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003237 dumpStylusState(dump, mExternalStylusState);
3238
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003240 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3241 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003242 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003243 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003244 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003245 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003247 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003248 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003249 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003250 mPointerGestureMaxSwipeWidth);
3251 }
3252}
3253
Santos Cordonfa5cf462017-04-05 10:37:00 -07003254const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3255 switch (deviceMode) {
3256 case DEVICE_MODE_DISABLED:
3257 return "disabled";
3258 case DEVICE_MODE_DIRECT:
3259 return "direct";
3260 case DEVICE_MODE_UNSCALED:
3261 return "unscaled";
3262 case DEVICE_MODE_NAVIGATION:
3263 return "navigation";
3264 case DEVICE_MODE_POINTER:
3265 return "pointer";
3266 }
3267 return "unknown";
3268}
3269
Michael Wrightd02c5b62014-02-10 15:10:22 -08003270void TouchInputMapper::configure(nsecs_t when,
3271 const InputReaderConfiguration* config, uint32_t changes) {
3272 InputMapper::configure(when, config, changes);
3273
3274 mConfig = *config;
3275
3276 if (!changes) { // first time only
3277 // Configure basic parameters.
3278 configureParameters();
3279
3280 // Configure common accumulators.
3281 mCursorScrollAccumulator.configure(getDevice());
3282 mTouchButtonAccumulator.configure(getDevice());
3283
3284 // Configure absolute axis information.
3285 configureRawPointerAxes();
3286
3287 // Prepare input device calibration.
3288 parseCalibration();
3289 resolveCalibration();
3290 }
3291
Michael Wright842500e2015-03-13 17:32:02 -07003292 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003293 // Update location calibration to reflect current settings
3294 updateAffineTransformation();
3295 }
3296
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3298 // Update pointer speed.
3299 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3300 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3301 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3302 }
3303
3304 bool resetNeeded = false;
3305 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3306 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003307 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3308 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003309 // Configure device sources, surface dimensions, orientation and
3310 // scaling factors.
3311 configureSurface(when, &resetNeeded);
3312 }
3313
3314 if (changes && resetNeeded) {
3315 // Send reset, unless this is the first time the device has been configured,
3316 // in which case the reader will call reset itself after all mappers are ready.
3317 getDevice()->notifyReset(when);
3318 }
3319}
3320
Michael Wright842500e2015-03-13 17:32:02 -07003321void TouchInputMapper::resolveExternalStylusPresence() {
3322 Vector<InputDeviceInfo> devices;
3323 mContext->getExternalStylusDevices(devices);
3324 mExternalStylusConnected = !devices.isEmpty();
3325
3326 if (!mExternalStylusConnected) {
3327 resetExternalStylus();
3328 }
3329}
3330
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331void TouchInputMapper::configureParameters() {
3332 // Use the pointer presentation mode for devices that do not support distinct
3333 // multitouch. The spot-based presentation relies on being able to accurately
3334 // locate two or more fingers on the touch pad.
3335 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003336 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003337
3338 String8 gestureModeString;
3339 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3340 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003341 if (gestureModeString == "single-touch") {
3342 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3343 } else if (gestureModeString == "multi-touch") {
3344 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345 } else if (gestureModeString != "default") {
3346 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3347 }
3348 }
3349
3350 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3351 // The device is a touch screen.
3352 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3353 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3354 // The device is a pointing device like a track pad.
3355 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3356 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3357 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3358 // The device is a cursor device with a touch pad attached.
3359 // By default don't use the touch pad to move the pointer.
3360 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3361 } else {
3362 // The device is a touch pad of unknown purpose.
3363 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3364 }
3365
3366 mParameters.hasButtonUnderPad=
3367 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3368
3369 String8 deviceTypeString;
3370 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3371 deviceTypeString)) {
3372 if (deviceTypeString == "touchScreen") {
3373 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3374 } else if (deviceTypeString == "touchPad") {
3375 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3376 } else if (deviceTypeString == "touchNavigation") {
3377 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3378 } else if (deviceTypeString == "pointer") {
3379 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3380 } else if (deviceTypeString != "default") {
3381 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3382 }
3383 }
3384
3385 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3386 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3387 mParameters.orientationAware);
3388
3389 mParameters.hasAssociatedDisplay = false;
3390 mParameters.associatedDisplayIsExternal = false;
3391 if (mParameters.orientationAware
3392 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3393 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3394 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003395 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3396 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
3397 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
3398 mParameters.uniqueDisplayId);
3399 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003401
3402 // Initial downs on external touch devices should wake the device.
3403 // Normally we don't do this for internal touch screens to prevent them from waking
3404 // up in your pocket but you can enable it using the input device configuration.
3405 mParameters.wake = getDevice()->isExternal();
3406 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3407 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408}
3409
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003410void TouchInputMapper::dumpParameters(std::string& dump) {
3411 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412
3413 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003414 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003415 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003417 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003418 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 break;
3420 default:
3421 assert(false);
3422 }
3423
3424 switch (mParameters.deviceType) {
3425 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003426 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 break;
3428 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003429 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003430 break;
3431 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003432 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 break;
3434 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003435 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 break;
3437 default:
3438 ALOG_ASSERT(false);
3439 }
3440
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003441 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003442 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003443 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003444 toString(mParameters.associatedDisplayIsExternal),
3445 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003446 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003447 toString(mParameters.orientationAware));
3448}
3449
3450void TouchInputMapper::configureRawPointerAxes() {
3451 mRawPointerAxes.clear();
3452}
3453
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003454void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3455 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003456 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3457 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3458 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3459 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3460 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3461 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3462 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3463 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3464 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3465 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3466 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3467 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3468 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3469}
3470
Michael Wright842500e2015-03-13 17:32:02 -07003471bool TouchInputMapper::hasExternalStylus() const {
3472 return mExternalStylusConnected;
3473}
3474
Michael Wrightd02c5b62014-02-10 15:10:22 -08003475void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3476 int32_t oldDeviceMode = mDeviceMode;
3477
Michael Wright842500e2015-03-13 17:32:02 -07003478 resolveExternalStylusPresence();
3479
Michael Wrightd02c5b62014-02-10 15:10:22 -08003480 // Determine device mode.
3481 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3482 && mConfig.pointerGesturesEnabled) {
3483 mSource = AINPUT_SOURCE_MOUSE;
3484 mDeviceMode = DEVICE_MODE_POINTER;
3485 if (hasStylus()) {
3486 mSource |= AINPUT_SOURCE_STYLUS;
3487 }
3488 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3489 && mParameters.hasAssociatedDisplay) {
3490 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3491 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003492 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003493 mSource |= AINPUT_SOURCE_STYLUS;
3494 }
Michael Wright2f78b682015-06-12 15:25:08 +01003495 if (hasExternalStylus()) {
3496 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3497 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003498 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3499 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3500 mDeviceMode = DEVICE_MODE_NAVIGATION;
3501 } else {
3502 mSource = AINPUT_SOURCE_TOUCHPAD;
3503 mDeviceMode = DEVICE_MODE_UNSCALED;
3504 }
3505
3506 // Ensure we have valid X and Y axes.
3507 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3508 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
3509 "The device will be inoperable.", getDeviceName().string());
3510 mDeviceMode = DEVICE_MODE_DISABLED;
3511 return;
3512 }
3513
3514 // Raw width and height in the natural orientation.
3515 int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3516 int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3517
3518 // Get associated display dimensions.
3519 DisplayViewport newViewport;
3520 if (mParameters.hasAssociatedDisplay) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003521 const String8* uniqueDisplayId = nullptr;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003522 ViewportType viewportTypeToUse;
3523
3524 if (mParameters.associatedDisplayIsExternal) {
3525 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3526 } else if (!mParameters.uniqueDisplayId.isEmpty()) {
3527 // If the IDC file specified a unique display Id, then it expects to be linked to a
3528 // virtual display with the same unique ID.
3529 uniqueDisplayId = &mParameters.uniqueDisplayId;
3530 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3531 } else {
3532 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3533 }
3534
3535 if (!mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId, &newViewport)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3537 "display. The device will be inoperable until the display size "
3538 "becomes available.",
3539 getDeviceName().string());
3540 mDeviceMode = DEVICE_MODE_DISABLED;
3541 return;
3542 }
3543 } else {
3544 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3545 }
3546 bool viewportChanged = mViewport != newViewport;
3547 if (viewportChanged) {
3548 mViewport = newViewport;
3549
3550 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3551 // Convert rotated viewport to natural surface coordinates.
3552 int32_t naturalLogicalWidth, naturalLogicalHeight;
3553 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3554 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3555 int32_t naturalDeviceWidth, naturalDeviceHeight;
3556 switch (mViewport.orientation) {
3557 case DISPLAY_ORIENTATION_90:
3558 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3559 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3560 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3561 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3562 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3563 naturalPhysicalTop = mViewport.physicalLeft;
3564 naturalDeviceWidth = mViewport.deviceHeight;
3565 naturalDeviceHeight = mViewport.deviceWidth;
3566 break;
3567 case DISPLAY_ORIENTATION_180:
3568 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3569 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3570 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3571 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3572 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3573 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3574 naturalDeviceWidth = mViewport.deviceWidth;
3575 naturalDeviceHeight = mViewport.deviceHeight;
3576 break;
3577 case DISPLAY_ORIENTATION_270:
3578 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3579 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3580 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3581 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3582 naturalPhysicalLeft = mViewport.physicalTop;
3583 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3584 naturalDeviceWidth = mViewport.deviceHeight;
3585 naturalDeviceHeight = mViewport.deviceWidth;
3586 break;
3587 case DISPLAY_ORIENTATION_0:
3588 default:
3589 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3590 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3591 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3592 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3593 naturalPhysicalLeft = mViewport.physicalLeft;
3594 naturalPhysicalTop = mViewport.physicalTop;
3595 naturalDeviceWidth = mViewport.deviceWidth;
3596 naturalDeviceHeight = mViewport.deviceHeight;
3597 break;
3598 }
3599
Michael Wright358bcc72018-08-21 04:01:07 +01003600 mPhysicalWidth = naturalPhysicalWidth;
3601 mPhysicalHeight = naturalPhysicalHeight;
3602 mPhysicalLeft = naturalPhysicalLeft;
3603 mPhysicalTop = naturalPhysicalTop;
3604
Michael Wrightd02c5b62014-02-10 15:10:22 -08003605 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3606 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3607 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3608 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3609
3610 mSurfaceOrientation = mParameters.orientationAware ?
3611 mViewport.orientation : DISPLAY_ORIENTATION_0;
3612 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003613 mPhysicalWidth = rawWidth;
3614 mPhysicalHeight = rawHeight;
3615 mPhysicalLeft = 0;
3616 mPhysicalTop = 0;
3617
Michael Wrightd02c5b62014-02-10 15:10:22 -08003618 mSurfaceWidth = rawWidth;
3619 mSurfaceHeight = rawHeight;
3620 mSurfaceLeft = 0;
3621 mSurfaceTop = 0;
3622 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3623 }
3624 }
3625
3626 // If moving between pointer modes, need to reset some state.
3627 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3628 if (deviceModeChanged) {
3629 mOrientedRanges.clear();
3630 }
3631
3632 // Create pointer controller if needed.
3633 if (mDeviceMode == DEVICE_MODE_POINTER ||
3634 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003635 if (mPointerController == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3637 }
3638 } else {
3639 mPointerController.clear();
3640 }
3641
3642 if (viewportChanged || deviceModeChanged) {
3643 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3644 "display id %d",
3645 getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight,
3646 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3647
3648 // Configure X and Y factors.
3649 mXScale = float(mSurfaceWidth) / rawWidth;
3650 mYScale = float(mSurfaceHeight) / rawHeight;
3651 mXTranslate = -mSurfaceLeft;
3652 mYTranslate = -mSurfaceTop;
3653 mXPrecision = 1.0f / mXScale;
3654 mYPrecision = 1.0f / mYScale;
3655
3656 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3657 mOrientedRanges.x.source = mSource;
3658 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3659 mOrientedRanges.y.source = mSource;
3660
3661 configureVirtualKeys();
3662
3663 // Scale factor for terms that are not oriented in a particular axis.
3664 // If the pixels are square then xScale == yScale otherwise we fake it
3665 // by choosing an average.
3666 mGeometricScale = avg(mXScale, mYScale);
3667
3668 // Size of diagonal axis.
3669 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3670
3671 // Size factors.
3672 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3673 if (mRawPointerAxes.touchMajor.valid
3674 && mRawPointerAxes.touchMajor.maxValue != 0) {
3675 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3676 } else if (mRawPointerAxes.toolMajor.valid
3677 && mRawPointerAxes.toolMajor.maxValue != 0) {
3678 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3679 } else {
3680 mSizeScale = 0.0f;
3681 }
3682
3683 mOrientedRanges.haveTouchSize = true;
3684 mOrientedRanges.haveToolSize = true;
3685 mOrientedRanges.haveSize = true;
3686
3687 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3688 mOrientedRanges.touchMajor.source = mSource;
3689 mOrientedRanges.touchMajor.min = 0;
3690 mOrientedRanges.touchMajor.max = diagonalSize;
3691 mOrientedRanges.touchMajor.flat = 0;
3692 mOrientedRanges.touchMajor.fuzz = 0;
3693 mOrientedRanges.touchMajor.resolution = 0;
3694
3695 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3696 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3697
3698 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3699 mOrientedRanges.toolMajor.source = mSource;
3700 mOrientedRanges.toolMajor.min = 0;
3701 mOrientedRanges.toolMajor.max = diagonalSize;
3702 mOrientedRanges.toolMajor.flat = 0;
3703 mOrientedRanges.toolMajor.fuzz = 0;
3704 mOrientedRanges.toolMajor.resolution = 0;
3705
3706 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3707 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3708
3709 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3710 mOrientedRanges.size.source = mSource;
3711 mOrientedRanges.size.min = 0;
3712 mOrientedRanges.size.max = 1.0;
3713 mOrientedRanges.size.flat = 0;
3714 mOrientedRanges.size.fuzz = 0;
3715 mOrientedRanges.size.resolution = 0;
3716 } else {
3717 mSizeScale = 0.0f;
3718 }
3719
3720 // Pressure factors.
3721 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003722 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003723 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3724 || mCalibration.pressureCalibration
3725 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3726 if (mCalibration.havePressureScale) {
3727 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003728 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003729 } else if (mRawPointerAxes.pressure.valid
3730 && mRawPointerAxes.pressure.maxValue != 0) {
3731 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3732 }
3733 }
3734
3735 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3736 mOrientedRanges.pressure.source = mSource;
3737 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003738 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003739 mOrientedRanges.pressure.flat = 0;
3740 mOrientedRanges.pressure.fuzz = 0;
3741 mOrientedRanges.pressure.resolution = 0;
3742
3743 // Tilt
3744 mTiltXCenter = 0;
3745 mTiltXScale = 0;
3746 mTiltYCenter = 0;
3747 mTiltYScale = 0;
3748 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3749 if (mHaveTilt) {
3750 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3751 mRawPointerAxes.tiltX.maxValue);
3752 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3753 mRawPointerAxes.tiltY.maxValue);
3754 mTiltXScale = M_PI / 180;
3755 mTiltYScale = M_PI / 180;
3756
3757 mOrientedRanges.haveTilt = true;
3758
3759 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3760 mOrientedRanges.tilt.source = mSource;
3761 mOrientedRanges.tilt.min = 0;
3762 mOrientedRanges.tilt.max = M_PI_2;
3763 mOrientedRanges.tilt.flat = 0;
3764 mOrientedRanges.tilt.fuzz = 0;
3765 mOrientedRanges.tilt.resolution = 0;
3766 }
3767
3768 // Orientation
3769 mOrientationScale = 0;
3770 if (mHaveTilt) {
3771 mOrientedRanges.haveOrientation = true;
3772
3773 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3774 mOrientedRanges.orientation.source = mSource;
3775 mOrientedRanges.orientation.min = -M_PI;
3776 mOrientedRanges.orientation.max = M_PI;
3777 mOrientedRanges.orientation.flat = 0;
3778 mOrientedRanges.orientation.fuzz = 0;
3779 mOrientedRanges.orientation.resolution = 0;
3780 } else if (mCalibration.orientationCalibration !=
3781 Calibration::ORIENTATION_CALIBRATION_NONE) {
3782 if (mCalibration.orientationCalibration
3783 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3784 if (mRawPointerAxes.orientation.valid) {
3785 if (mRawPointerAxes.orientation.maxValue > 0) {
3786 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3787 } else if (mRawPointerAxes.orientation.minValue < 0) {
3788 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3789 } else {
3790 mOrientationScale = 0;
3791 }
3792 }
3793 }
3794
3795 mOrientedRanges.haveOrientation = true;
3796
3797 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3798 mOrientedRanges.orientation.source = mSource;
3799 mOrientedRanges.orientation.min = -M_PI_2;
3800 mOrientedRanges.orientation.max = M_PI_2;
3801 mOrientedRanges.orientation.flat = 0;
3802 mOrientedRanges.orientation.fuzz = 0;
3803 mOrientedRanges.orientation.resolution = 0;
3804 }
3805
3806 // Distance
3807 mDistanceScale = 0;
3808 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3809 if (mCalibration.distanceCalibration
3810 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3811 if (mCalibration.haveDistanceScale) {
3812 mDistanceScale = mCalibration.distanceScale;
3813 } else {
3814 mDistanceScale = 1.0f;
3815 }
3816 }
3817
3818 mOrientedRanges.haveDistance = true;
3819
3820 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3821 mOrientedRanges.distance.source = mSource;
3822 mOrientedRanges.distance.min =
3823 mRawPointerAxes.distance.minValue * mDistanceScale;
3824 mOrientedRanges.distance.max =
3825 mRawPointerAxes.distance.maxValue * mDistanceScale;
3826 mOrientedRanges.distance.flat = 0;
3827 mOrientedRanges.distance.fuzz =
3828 mRawPointerAxes.distance.fuzz * mDistanceScale;
3829 mOrientedRanges.distance.resolution = 0;
3830 }
3831
3832 // Compute oriented precision, scales and ranges.
3833 // Note that the maximum value reported is an inclusive maximum value so it is one
3834 // unit less than the total width or height of surface.
3835 switch (mSurfaceOrientation) {
3836 case DISPLAY_ORIENTATION_90:
3837 case DISPLAY_ORIENTATION_270:
3838 mOrientedXPrecision = mYPrecision;
3839 mOrientedYPrecision = mXPrecision;
3840
3841 mOrientedRanges.x.min = mYTranslate;
3842 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3843 mOrientedRanges.x.flat = 0;
3844 mOrientedRanges.x.fuzz = 0;
3845 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3846
3847 mOrientedRanges.y.min = mXTranslate;
3848 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3849 mOrientedRanges.y.flat = 0;
3850 mOrientedRanges.y.fuzz = 0;
3851 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3852 break;
3853
3854 default:
3855 mOrientedXPrecision = mXPrecision;
3856 mOrientedYPrecision = mYPrecision;
3857
3858 mOrientedRanges.x.min = mXTranslate;
3859 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3860 mOrientedRanges.x.flat = 0;
3861 mOrientedRanges.x.fuzz = 0;
3862 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3863
3864 mOrientedRanges.y.min = mYTranslate;
3865 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3866 mOrientedRanges.y.flat = 0;
3867 mOrientedRanges.y.fuzz = 0;
3868 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3869 break;
3870 }
3871
Jason Gerecke71b16e82014-03-10 09:47:59 -07003872 // Location
3873 updateAffineTransformation();
3874
Michael Wrightd02c5b62014-02-10 15:10:22 -08003875 if (mDeviceMode == DEVICE_MODE_POINTER) {
3876 // Compute pointer gesture detection parameters.
3877 float rawDiagonal = hypotf(rawWidth, rawHeight);
3878 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3879
3880 // Scale movements such that one whole swipe of the touch pad covers a
3881 // given area relative to the diagonal size of the display when no acceleration
3882 // is applied.
3883 // Assume that the touch pad has a square aspect ratio such that movements in
3884 // X and Y of the same number of raw units cover the same physical distance.
3885 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3886 * displayDiagonal / rawDiagonal;
3887 mPointerYMovementScale = mPointerXMovementScale;
3888
3889 // Scale zooms to cover a smaller range of the display than movements do.
3890 // This value determines the area around the pointer that is affected by freeform
3891 // pointer gestures.
3892 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3893 * displayDiagonal / rawDiagonal;
3894 mPointerYZoomScale = mPointerXZoomScale;
3895
3896 // Max width between pointers to detect a swipe gesture is more than some fraction
3897 // of the diagonal axis of the touch pad. Touches that are wider than this are
3898 // translated into freeform gestures.
3899 mPointerGestureMaxSwipeWidth =
3900 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3901
3902 // Abort current pointer usages because the state has changed.
3903 abortPointerUsage(when, 0 /*policyFlags*/);
3904 }
3905
3906 // Inform the dispatcher about the changes.
3907 *outResetNeeded = true;
3908 bumpGeneration();
3909 }
3910}
3911
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003912void TouchInputMapper::dumpSurface(std::string& dump) {
3913 dump += StringPrintf(INDENT3 "Viewport: displayId=%d, orientation=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914 "logicalFrame=[%d, %d, %d, %d], "
3915 "physicalFrame=[%d, %d, %d, %d], "
3916 "deviceSize=[%d, %d]\n",
3917 mViewport.displayId, mViewport.orientation,
3918 mViewport.logicalLeft, mViewport.logicalTop,
3919 mViewport.logicalRight, mViewport.logicalBottom,
3920 mViewport.physicalLeft, mViewport.physicalTop,
3921 mViewport.physicalRight, mViewport.physicalBottom,
3922 mViewport.deviceWidth, mViewport.deviceHeight);
3923
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003924 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3925 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3926 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3927 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003928 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3929 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3930 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3931 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003932 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933}
3934
3935void TouchInputMapper::configureVirtualKeys() {
3936 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3937 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3938
3939 mVirtualKeys.clear();
3940
3941 if (virtualKeyDefinitions.size() == 0) {
3942 return;
3943 }
3944
3945 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3946
3947 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3948 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
3949 int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1;
3950 int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1;
3951
3952 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3953 const VirtualKeyDefinition& virtualKeyDefinition =
3954 virtualKeyDefinitions[i];
3955
3956 mVirtualKeys.add();
3957 VirtualKey& virtualKey = mVirtualKeys.editTop();
3958
3959 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3960 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003961 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003963 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3964 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3966 virtualKey.scanCode);
3967 mVirtualKeys.pop(); // drop the key
3968 continue;
3969 }
3970
3971 virtualKey.keyCode = keyCode;
3972 virtualKey.flags = flags;
3973
3974 // convert the key definition's display coordinates into touch coordinates for a hit box
3975 int32_t halfWidth = virtualKeyDefinition.width / 2;
3976 int32_t halfHeight = virtualKeyDefinition.height / 2;
3977
3978 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3979 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3980 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3981 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3982 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3983 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3984 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3985 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3986 }
3987}
3988
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003989void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003990 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003991 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992
3993 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3994 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003995 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3997 i, virtualKey.scanCode, virtualKey.keyCode,
3998 virtualKey.hitLeft, virtualKey.hitRight,
3999 virtualKey.hitTop, virtualKey.hitBottom);
4000 }
4001 }
4002}
4003
4004void TouchInputMapper::parseCalibration() {
4005 const PropertyMap& in = getDevice()->getConfiguration();
4006 Calibration& out = mCalibration;
4007
4008 // Size
4009 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4010 String8 sizeCalibrationString;
4011 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4012 if (sizeCalibrationString == "none") {
4013 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4014 } else if (sizeCalibrationString == "geometric") {
4015 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4016 } else if (sizeCalibrationString == "diameter") {
4017 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4018 } else if (sizeCalibrationString == "box") {
4019 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4020 } else if (sizeCalibrationString == "area") {
4021 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4022 } else if (sizeCalibrationString != "default") {
4023 ALOGW("Invalid value for touch.size.calibration: '%s'",
4024 sizeCalibrationString.string());
4025 }
4026 }
4027
4028 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4029 out.sizeScale);
4030 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4031 out.sizeBias);
4032 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4033 out.sizeIsSummed);
4034
4035 // Pressure
4036 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4037 String8 pressureCalibrationString;
4038 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4039 if (pressureCalibrationString == "none") {
4040 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4041 } else if (pressureCalibrationString == "physical") {
4042 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4043 } else if (pressureCalibrationString == "amplitude") {
4044 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4045 } else if (pressureCalibrationString != "default") {
4046 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4047 pressureCalibrationString.string());
4048 }
4049 }
4050
4051 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4052 out.pressureScale);
4053
4054 // Orientation
4055 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4056 String8 orientationCalibrationString;
4057 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4058 if (orientationCalibrationString == "none") {
4059 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4060 } else if (orientationCalibrationString == "interpolated") {
4061 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4062 } else if (orientationCalibrationString == "vector") {
4063 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4064 } else if (orientationCalibrationString != "default") {
4065 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4066 orientationCalibrationString.string());
4067 }
4068 }
4069
4070 // Distance
4071 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4072 String8 distanceCalibrationString;
4073 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4074 if (distanceCalibrationString == "none") {
4075 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4076 } else if (distanceCalibrationString == "scaled") {
4077 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4078 } else if (distanceCalibrationString != "default") {
4079 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4080 distanceCalibrationString.string());
4081 }
4082 }
4083
4084 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4085 out.distanceScale);
4086
4087 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4088 String8 coverageCalibrationString;
4089 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4090 if (coverageCalibrationString == "none") {
4091 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4092 } else if (coverageCalibrationString == "box") {
4093 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4094 } else if (coverageCalibrationString != "default") {
4095 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4096 coverageCalibrationString.string());
4097 }
4098 }
4099}
4100
4101void TouchInputMapper::resolveCalibration() {
4102 // Size
4103 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4104 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4105 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4106 }
4107 } else {
4108 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4109 }
4110
4111 // Pressure
4112 if (mRawPointerAxes.pressure.valid) {
4113 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4114 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4115 }
4116 } else {
4117 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4118 }
4119
4120 // Orientation
4121 if (mRawPointerAxes.orientation.valid) {
4122 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4123 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4124 }
4125 } else {
4126 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4127 }
4128
4129 // Distance
4130 if (mRawPointerAxes.distance.valid) {
4131 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4132 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4133 }
4134 } else {
4135 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4136 }
4137
4138 // Coverage
4139 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4140 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4141 }
4142}
4143
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004144void TouchInputMapper::dumpCalibration(std::string& dump) {
4145 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146
4147 // Size
4148 switch (mCalibration.sizeCalibration) {
4149 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004150 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 break;
4152 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004153 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 break;
4155 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 break;
4158 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004159 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 break;
4161 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004162 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 break;
4164 default:
4165 ALOG_ASSERT(false);
4166 }
4167
4168 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004169 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 mCalibration.sizeScale);
4171 }
4172
4173 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004174 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 mCalibration.sizeBias);
4176 }
4177
4178 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004179 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 toString(mCalibration.sizeIsSummed));
4181 }
4182
4183 // Pressure
4184 switch (mCalibration.pressureCalibration) {
4185 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004186 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 break;
4188 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004189 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 break;
4191 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 break;
4194 default:
4195 ALOG_ASSERT(false);
4196 }
4197
4198 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004199 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 mCalibration.pressureScale);
4201 }
4202
4203 // Orientation
4204 switch (mCalibration.orientationCalibration) {
4205 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004206 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 break;
4208 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004209 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 break;
4211 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 break;
4214 default:
4215 ALOG_ASSERT(false);
4216 }
4217
4218 // Distance
4219 switch (mCalibration.distanceCalibration) {
4220 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004221 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 break;
4223 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004224 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 break;
4226 default:
4227 ALOG_ASSERT(false);
4228 }
4229
4230 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004231 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 mCalibration.distanceScale);
4233 }
4234
4235 switch (mCalibration.coverageCalibration) {
4236 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004237 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 break;
4239 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004240 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 break;
4242 default:
4243 ALOG_ASSERT(false);
4244 }
4245}
4246
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004247void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4248 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004249
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004250 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4251 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4252 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4253 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4254 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4255 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004256}
4257
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004258void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004259 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4260 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004261}
4262
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263void TouchInputMapper::reset(nsecs_t when) {
4264 mCursorButtonAccumulator.reset(getDevice());
4265 mCursorScrollAccumulator.reset(getDevice());
4266 mTouchButtonAccumulator.reset(getDevice());
4267
4268 mPointerVelocityControl.reset();
4269 mWheelXVelocityControl.reset();
4270 mWheelYVelocityControl.reset();
4271
Michael Wright842500e2015-03-13 17:32:02 -07004272 mRawStatesPending.clear();
4273 mCurrentRawState.clear();
4274 mCurrentCookedState.clear();
4275 mLastRawState.clear();
4276 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 mPointerUsage = POINTER_USAGE_NONE;
4278 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004279 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004280 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004281 mDownTime = 0;
4282
4283 mCurrentVirtualKey.down = false;
4284
4285 mPointerGesture.reset();
4286 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004287 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288
Yi Kong9b14ac62018-07-17 13:48:38 -07004289 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4291 mPointerController->clearSpots();
4292 }
4293
4294 InputMapper::reset(when);
4295}
4296
Michael Wright842500e2015-03-13 17:32:02 -07004297void TouchInputMapper::resetExternalStylus() {
4298 mExternalStylusState.clear();
4299 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004300 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004301 mExternalStylusDataPending = false;
4302}
4303
Michael Wright43fd19f2015-04-21 19:02:58 +01004304void TouchInputMapper::clearStylusDataPendingFlags() {
4305 mExternalStylusDataPending = false;
4306 mExternalStylusFusionTimeout = LLONG_MAX;
4307}
4308
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309void TouchInputMapper::process(const RawEvent* rawEvent) {
4310 mCursorButtonAccumulator.process(rawEvent);
4311 mCursorScrollAccumulator.process(rawEvent);
4312 mTouchButtonAccumulator.process(rawEvent);
4313
4314 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4315 sync(rawEvent->when);
4316 }
4317}
4318
4319void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004320 const RawState* last = mRawStatesPending.isEmpty() ?
4321 &mCurrentRawState : &mRawStatesPending.top();
4322
4323 // Push a new state.
4324 mRawStatesPending.push();
4325 RawState* next = &mRawStatesPending.editTop();
4326 next->clear();
4327 next->when = when;
4328
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004330 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004331 | mCursorButtonAccumulator.getButtonState();
4332
Michael Wright842500e2015-03-13 17:32:02 -07004333 // Sync scroll
4334 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4335 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 mCursorScrollAccumulator.finishSync();
4337
Michael Wright842500e2015-03-13 17:32:02 -07004338 // Sync touch
4339 syncTouch(when, next);
4340
4341 // Assign pointer ids.
4342 if (!mHavePointerIds) {
4343 assignPointerIds(last, next);
4344 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345
4346#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004347 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4348 "hovering ids 0x%08x -> 0x%08x",
4349 last->rawPointerData.pointerCount,
4350 next->rawPointerData.pointerCount,
4351 last->rawPointerData.touchingIdBits.value,
4352 next->rawPointerData.touchingIdBits.value,
4353 last->rawPointerData.hoveringIdBits.value,
4354 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355#endif
4356
Michael Wright842500e2015-03-13 17:32:02 -07004357 processRawTouches(false /*timeout*/);
4358}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359
Michael Wright842500e2015-03-13 17:32:02 -07004360void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4362 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004363 mCurrentRawState.clear();
4364 mRawStatesPending.clear();
4365 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 }
4367
Michael Wright842500e2015-03-13 17:32:02 -07004368 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4369 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4370 // touching the current state will only observe the events that have been dispatched to the
4371 // rest of the pipeline.
4372 const size_t N = mRawStatesPending.size();
4373 size_t count;
4374 for(count = 0; count < N; count++) {
4375 const RawState& next = mRawStatesPending[count];
4376
4377 // A failure to assign the stylus id means that we're waiting on stylus data
4378 // and so should defer the rest of the pipeline.
4379 if (assignExternalStylusId(next, timeout)) {
4380 break;
4381 }
4382
4383 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004384 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004385 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004386 if (mCurrentRawState.when < mLastRawState.when) {
4387 mCurrentRawState.when = mLastRawState.when;
4388 }
Michael Wright842500e2015-03-13 17:32:02 -07004389 cookAndDispatch(mCurrentRawState.when);
4390 }
4391 if (count != 0) {
4392 mRawStatesPending.removeItemsAt(0, count);
4393 }
4394
Michael Wright842500e2015-03-13 17:32:02 -07004395 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004396 if (timeout) {
4397 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4398 clearStylusDataPendingFlags();
4399 mCurrentRawState.copyFrom(mLastRawState);
4400#if DEBUG_STYLUS_FUSION
4401 ALOGD("Timeout expired, synthesizing event with new stylus data");
4402#endif
4403 cookAndDispatch(when);
4404 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4405 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4406 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4407 }
Michael Wright842500e2015-03-13 17:32:02 -07004408 }
4409}
4410
4411void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4412 // Always start with a clean state.
4413 mCurrentCookedState.clear();
4414
4415 // Apply stylus buttons to current raw state.
4416 applyExternalStylusButtonState(when);
4417
4418 // Handle policy on initial down or hover events.
4419 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4420 && mCurrentRawState.rawPointerData.pointerCount != 0;
4421
4422 uint32_t policyFlags = 0;
4423 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4424 if (initialDown || buttonsPressed) {
4425 // If this is a touch screen, hide the pointer on an initial down.
4426 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4427 getContext()->fadePointer();
4428 }
4429
4430 if (mParameters.wake) {
4431 policyFlags |= POLICY_FLAG_WAKE;
4432 }
4433 }
4434
4435 // Consume raw off-screen touches before cooking pointer data.
4436 // If touches are consumed, subsequent code will not receive any pointer data.
4437 if (consumeRawTouches(when, policyFlags)) {
4438 mCurrentRawState.rawPointerData.clear();
4439 }
4440
4441 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4442 // with cooked pointer data that has the same ids and indices as the raw data.
4443 // The following code can use either the raw or cooked data, as needed.
4444 cookPointerData();
4445
4446 // Apply stylus pressure to current cooked state.
4447 applyExternalStylusTouchState(when);
4448
4449 // Synthesize key down from raw buttons if needed.
4450 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004451 mViewport.displayId, policyFlags,
4452 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004453
4454 // Dispatch the touches either directly or by translation through a pointer on screen.
4455 if (mDeviceMode == DEVICE_MODE_POINTER) {
4456 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4457 !idBits.isEmpty(); ) {
4458 uint32_t id = idBits.clearFirstMarkedBit();
4459 const RawPointerData::Pointer& pointer =
4460 mCurrentRawState.rawPointerData.pointerForId(id);
4461 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4462 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4463 mCurrentCookedState.stylusIdBits.markBit(id);
4464 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4465 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4466 mCurrentCookedState.fingerIdBits.markBit(id);
4467 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4468 mCurrentCookedState.mouseIdBits.markBit(id);
4469 }
4470 }
4471 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4472 !idBits.isEmpty(); ) {
4473 uint32_t id = idBits.clearFirstMarkedBit();
4474 const RawPointerData::Pointer& pointer =
4475 mCurrentRawState.rawPointerData.pointerForId(id);
4476 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4477 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4478 mCurrentCookedState.stylusIdBits.markBit(id);
4479 }
4480 }
4481
4482 // Stylus takes precedence over all tools, then mouse, then finger.
4483 PointerUsage pointerUsage = mPointerUsage;
4484 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4485 mCurrentCookedState.mouseIdBits.clear();
4486 mCurrentCookedState.fingerIdBits.clear();
4487 pointerUsage = POINTER_USAGE_STYLUS;
4488 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4489 mCurrentCookedState.fingerIdBits.clear();
4490 pointerUsage = POINTER_USAGE_MOUSE;
4491 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4492 isPointerDown(mCurrentRawState.buttonState)) {
4493 pointerUsage = POINTER_USAGE_GESTURES;
4494 }
4495
4496 dispatchPointerUsage(when, policyFlags, pointerUsage);
4497 } else {
4498 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004499 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004500 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4501 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4502
4503 mPointerController->setButtonState(mCurrentRawState.buttonState);
4504 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4505 mCurrentCookedState.cookedPointerData.idToIndex,
4506 mCurrentCookedState.cookedPointerData.touchingIdBits);
4507 }
4508
Michael Wright8e812822015-06-22 16:18:21 +01004509 if (!mCurrentMotionAborted) {
4510 dispatchButtonRelease(when, policyFlags);
4511 dispatchHoverExit(when, policyFlags);
4512 dispatchTouches(when, policyFlags);
4513 dispatchHoverEnterAndMove(when, policyFlags);
4514 dispatchButtonPress(when, policyFlags);
4515 }
4516
4517 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4518 mCurrentMotionAborted = false;
4519 }
Michael Wright842500e2015-03-13 17:32:02 -07004520 }
4521
4522 // Synthesize key up from raw buttons if needed.
4523 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004524 mViewport.displayId, policyFlags,
4525 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004526
4527 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004528 mCurrentRawState.rawVScroll = 0;
4529 mCurrentRawState.rawHScroll = 0;
4530
4531 // Copy current touch to last touch in preparation for the next cycle.
4532 mLastRawState.copyFrom(mCurrentRawState);
4533 mLastCookedState.copyFrom(mCurrentCookedState);
4534}
4535
4536void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004537 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004538 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4539 }
4540}
4541
4542void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004543 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4544 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004545
Michael Wright53dca3a2015-04-23 17:39:53 +01004546 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4547 float pressure = mExternalStylusState.pressure;
4548 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4549 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4550 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4551 }
4552 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4553 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4554
4555 PointerProperties& properties =
4556 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004557 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4558 properties.toolType = mExternalStylusState.toolType;
4559 }
4560 }
4561}
4562
4563bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4564 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4565 return false;
4566 }
4567
4568 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4569 && state.rawPointerData.pointerCount != 0;
4570 if (initialDown) {
4571 if (mExternalStylusState.pressure != 0.0f) {
4572#if DEBUG_STYLUS_FUSION
4573 ALOGD("Have both stylus and touch data, beginning fusion");
4574#endif
4575 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4576 } else if (timeout) {
4577#if DEBUG_STYLUS_FUSION
4578 ALOGD("Timeout expired, assuming touch is not a stylus.");
4579#endif
4580 resetExternalStylus();
4581 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004582 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4583 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004584 }
4585#if DEBUG_STYLUS_FUSION
4586 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004587 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004588#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004589 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004590 return true;
4591 }
4592 }
4593
4594 // Check if the stylus pointer has gone up.
4595 if (mExternalStylusId != -1 &&
4596 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4597#if DEBUG_STYLUS_FUSION
4598 ALOGD("Stylus pointer is going up");
4599#endif
4600 mExternalStylusId = -1;
4601 }
4602
4603 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004604}
4605
4606void TouchInputMapper::timeoutExpired(nsecs_t when) {
4607 if (mDeviceMode == DEVICE_MODE_POINTER) {
4608 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4609 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4610 }
Michael Wright842500e2015-03-13 17:32:02 -07004611 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004612 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004613 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004614 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4615 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004616 }
4617 }
4618}
4619
4620void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004621 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004622 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004623 // We're either in the middle of a fused stream of data or we're waiting on data before
4624 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4625 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004626 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004627 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 }
4629}
4630
4631bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4632 // Check for release of a virtual key.
4633 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004634 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635 // Pointer went up while virtual key was down.
4636 mCurrentVirtualKey.down = false;
4637 if (!mCurrentVirtualKey.ignored) {
4638#if DEBUG_VIRTUAL_KEYS
4639 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4640 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4641#endif
4642 dispatchVirtualKey(when, policyFlags,
4643 AKEY_EVENT_ACTION_UP,
4644 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4645 }
4646 return true;
4647 }
4648
Michael Wright842500e2015-03-13 17:32:02 -07004649 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4650 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4651 const RawPointerData::Pointer& pointer =
4652 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4654 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4655 // Pointer is still within the space of the virtual key.
4656 return true;
4657 }
4658 }
4659
4660 // Pointer left virtual key area or another pointer also went down.
4661 // Send key cancellation but do not consume the touch yet.
4662 // This is useful when the user swipes through from the virtual key area
4663 // into the main display surface.
4664 mCurrentVirtualKey.down = false;
4665 if (!mCurrentVirtualKey.ignored) {
4666#if DEBUG_VIRTUAL_KEYS
4667 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4668 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4669#endif
4670 dispatchVirtualKey(when, policyFlags,
4671 AKEY_EVENT_ACTION_UP,
4672 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4673 | AKEY_EVENT_FLAG_CANCELED);
4674 }
4675 }
4676
Michael Wright842500e2015-03-13 17:32:02 -07004677 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4678 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004679 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004680 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4681 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4683 // If exactly one pointer went down, check for virtual key hit.
4684 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004685 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4687 if (virtualKey) {
4688 mCurrentVirtualKey.down = true;
4689 mCurrentVirtualKey.downTime = when;
4690 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4691 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4692 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4693 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4694
4695 if (!mCurrentVirtualKey.ignored) {
4696#if DEBUG_VIRTUAL_KEYS
4697 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4698 mCurrentVirtualKey.keyCode,
4699 mCurrentVirtualKey.scanCode);
4700#endif
4701 dispatchVirtualKey(when, policyFlags,
4702 AKEY_EVENT_ACTION_DOWN,
4703 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4704 }
4705 }
4706 }
4707 return true;
4708 }
4709 }
4710
4711 // Disable all virtual key touches that happen within a short time interval of the
4712 // most recent touch within the screen area. The idea is to filter out stray
4713 // virtual key presses when interacting with the touch screen.
4714 //
4715 // Problems we're trying to solve:
4716 //
4717 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4718 // virtual key area that is implemented by a separate touch panel and accidentally
4719 // triggers a virtual key.
4720 //
4721 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4722 // area and accidentally triggers a virtual key. This often happens when virtual keys
4723 // are layed out below the screen near to where the on screen keyboard's space bar
4724 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004725 if (mConfig.virtualKeyQuietTime > 0 &&
4726 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4728 }
4729 return false;
4730}
4731
4732void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4733 int32_t keyEventAction, int32_t keyEventFlags) {
4734 int32_t keyCode = mCurrentVirtualKey.keyCode;
4735 int32_t scanCode = mCurrentVirtualKey.scanCode;
4736 nsecs_t downTime = mCurrentVirtualKey.downTime;
4737 int32_t metaState = mContext->getGlobalMetaState();
4738 policyFlags |= POLICY_FLAG_VIRTUAL;
4739
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004740 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId,
4741 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 getListener()->notifyKey(&args);
4743}
4744
Michael Wright8e812822015-06-22 16:18:21 +01004745void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4746 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4747 if (!currentIdBits.isEmpty()) {
4748 int32_t metaState = getContext()->getGlobalMetaState();
4749 int32_t buttonState = mCurrentCookedState.buttonState;
4750 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4751 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004752 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004753 mCurrentCookedState.cookedPointerData.pointerProperties,
4754 mCurrentCookedState.cookedPointerData.pointerCoords,
4755 mCurrentCookedState.cookedPointerData.idToIndex,
4756 currentIdBits, -1,
4757 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4758 mCurrentMotionAborted = true;
4759 }
4760}
4761
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004763 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4764 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004766 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767
4768 if (currentIdBits == lastIdBits) {
4769 if (!currentIdBits.isEmpty()) {
4770 // No pointer id changes so this is a move event.
4771 // The listener takes care of batching moves so we don't have to deal with that here.
4772 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004773 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004774 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004775 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004776 mCurrentCookedState.cookedPointerData.pointerProperties,
4777 mCurrentCookedState.cookedPointerData.pointerCoords,
4778 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004779 currentIdBits, -1,
4780 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4781 }
4782 } else {
4783 // There may be pointers going up and pointers going down and pointers moving
4784 // all at the same time.
4785 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4786 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4787 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4788 BitSet32 dispatchedIdBits(lastIdBits.value);
4789
4790 // Update last coordinates of pointers that have moved so that we observe the new
4791 // pointer positions at the same time as other pointers that have just gone up.
4792 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004793 mCurrentCookedState.cookedPointerData.pointerProperties,
4794 mCurrentCookedState.cookedPointerData.pointerCoords,
4795 mCurrentCookedState.cookedPointerData.idToIndex,
4796 mLastCookedState.cookedPointerData.pointerProperties,
4797 mLastCookedState.cookedPointerData.pointerCoords,
4798 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004800 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 moveNeeded = true;
4802 }
4803
4804 // Dispatch pointer up events.
4805 while (!upIdBits.isEmpty()) {
4806 uint32_t upId = upIdBits.clearFirstMarkedBit();
4807
4808 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004809 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004810 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004811 mLastCookedState.cookedPointerData.pointerProperties,
4812 mLastCookedState.cookedPointerData.pointerCoords,
4813 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004814 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 dispatchedIdBits.clearBit(upId);
4816 }
4817
4818 // Dispatch move events if any of the remaining pointers moved from their old locations.
4819 // Although applications receive new locations as part of individual pointer up
4820 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004821 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4823 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004824 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004825 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004826 mCurrentCookedState.cookedPointerData.pointerProperties,
4827 mCurrentCookedState.cookedPointerData.pointerCoords,
4828 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004829 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 }
4831
4832 // Dispatch pointer down events using the new pointer locations.
4833 while (!downIdBits.isEmpty()) {
4834 uint32_t downId = downIdBits.clearFirstMarkedBit();
4835 dispatchedIdBits.markBit(downId);
4836
4837 if (dispatchedIdBits.count() == 1) {
4838 // First pointer is going down. Set down time.
4839 mDownTime = when;
4840 }
4841
4842 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004843 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004844 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004845 mCurrentCookedState.cookedPointerData.pointerProperties,
4846 mCurrentCookedState.cookedPointerData.pointerCoords,
4847 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004848 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 }
4850 }
4851}
4852
4853void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4854 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004855 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4856 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 int32_t metaState = getContext()->getGlobalMetaState();
4858 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004859 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004860 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004861 mLastCookedState.cookedPointerData.pointerProperties,
4862 mLastCookedState.cookedPointerData.pointerCoords,
4863 mLastCookedState.cookedPointerData.idToIndex,
4864 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4866 mSentHoverEnter = false;
4867 }
4868}
4869
4870void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004871 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4872 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 int32_t metaState = getContext()->getGlobalMetaState();
4874 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004875 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004876 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004877 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004878 mCurrentCookedState.cookedPointerData.pointerProperties,
4879 mCurrentCookedState.cookedPointerData.pointerCoords,
4880 mCurrentCookedState.cookedPointerData.idToIndex,
4881 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4883 mSentHoverEnter = true;
4884 }
4885
4886 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004887 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004888 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004889 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004890 mCurrentCookedState.cookedPointerData.pointerProperties,
4891 mCurrentCookedState.cookedPointerData.pointerCoords,
4892 mCurrentCookedState.cookedPointerData.idToIndex,
4893 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4895 }
4896}
4897
Michael Wright7b159c92015-05-14 14:48:03 +01004898void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4899 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4900 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4901 const int32_t metaState = getContext()->getGlobalMetaState();
4902 int32_t buttonState = mLastCookedState.buttonState;
4903 while (!releasedButtons.isEmpty()) {
4904 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4905 buttonState &= ~actionButton;
4906 dispatchMotion(when, policyFlags, mSource,
4907 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4908 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004909 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004910 mCurrentCookedState.cookedPointerData.pointerProperties,
4911 mCurrentCookedState.cookedPointerData.pointerCoords,
4912 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4913 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4914 }
4915}
4916
4917void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4918 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4919 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4920 const int32_t metaState = getContext()->getGlobalMetaState();
4921 int32_t buttonState = mLastCookedState.buttonState;
4922 while (!pressedButtons.isEmpty()) {
4923 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4924 buttonState |= actionButton;
4925 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4926 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004927 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004928 mCurrentCookedState.cookedPointerData.pointerProperties,
4929 mCurrentCookedState.cookedPointerData.pointerCoords,
4930 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4931 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4932 }
4933}
4934
4935const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4936 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4937 return cookedPointerData.touchingIdBits;
4938 }
4939 return cookedPointerData.hoveringIdBits;
4940}
4941
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004943 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944
Michael Wright842500e2015-03-13 17:32:02 -07004945 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004946 mCurrentCookedState.deviceTimestamp =
4947 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004948 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4949 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4950 mCurrentRawState.rawPointerData.hoveringIdBits;
4951 mCurrentCookedState.cookedPointerData.touchingIdBits =
4952 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953
Michael Wright7b159c92015-05-14 14:48:03 +01004954 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4955 mCurrentCookedState.buttonState = 0;
4956 } else {
4957 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4958 }
4959
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960 // Walk through the the active pointers and map device coordinates onto
4961 // surface coordinates and adjust for display orientation.
4962 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004963 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964
4965 // Size
4966 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4967 switch (mCalibration.sizeCalibration) {
4968 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4969 case Calibration::SIZE_CALIBRATION_DIAMETER:
4970 case Calibration::SIZE_CALIBRATION_BOX:
4971 case Calibration::SIZE_CALIBRATION_AREA:
4972 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4973 touchMajor = in.touchMajor;
4974 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4975 toolMajor = in.toolMajor;
4976 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4977 size = mRawPointerAxes.touchMinor.valid
4978 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4979 } else if (mRawPointerAxes.touchMajor.valid) {
4980 toolMajor = touchMajor = in.touchMajor;
4981 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4982 ? in.touchMinor : in.touchMajor;
4983 size = mRawPointerAxes.touchMinor.valid
4984 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4985 } else if (mRawPointerAxes.toolMajor.valid) {
4986 touchMajor = toolMajor = in.toolMajor;
4987 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4988 ? in.toolMinor : in.toolMajor;
4989 size = mRawPointerAxes.toolMinor.valid
4990 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4991 } else {
4992 ALOG_ASSERT(false, "No touch or tool axes. "
4993 "Size calibration should have been resolved to NONE.");
4994 touchMajor = 0;
4995 touchMinor = 0;
4996 toolMajor = 0;
4997 toolMinor = 0;
4998 size = 0;
4999 }
5000
5001 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005002 uint32_t touchingCount =
5003 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004 if (touchingCount > 1) {
5005 touchMajor /= touchingCount;
5006 touchMinor /= touchingCount;
5007 toolMajor /= touchingCount;
5008 toolMinor /= touchingCount;
5009 size /= touchingCount;
5010 }
5011 }
5012
5013 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5014 touchMajor *= mGeometricScale;
5015 touchMinor *= mGeometricScale;
5016 toolMajor *= mGeometricScale;
5017 toolMinor *= mGeometricScale;
5018 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5019 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5020 touchMinor = touchMajor;
5021 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5022 toolMinor = toolMajor;
5023 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5024 touchMinor = touchMajor;
5025 toolMinor = toolMajor;
5026 }
5027
5028 mCalibration.applySizeScaleAndBias(&touchMajor);
5029 mCalibration.applySizeScaleAndBias(&touchMinor);
5030 mCalibration.applySizeScaleAndBias(&toolMajor);
5031 mCalibration.applySizeScaleAndBias(&toolMinor);
5032 size *= mSizeScale;
5033 break;
5034 default:
5035 touchMajor = 0;
5036 touchMinor = 0;
5037 toolMajor = 0;
5038 toolMinor = 0;
5039 size = 0;
5040 break;
5041 }
5042
5043 // Pressure
5044 float pressure;
5045 switch (mCalibration.pressureCalibration) {
5046 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5047 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5048 pressure = in.pressure * mPressureScale;
5049 break;
5050 default:
5051 pressure = in.isHovering ? 0 : 1;
5052 break;
5053 }
5054
5055 // Tilt and Orientation
5056 float tilt;
5057 float orientation;
5058 if (mHaveTilt) {
5059 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5060 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5061 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5062 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5063 } else {
5064 tilt = 0;
5065
5066 switch (mCalibration.orientationCalibration) {
5067 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5068 orientation = in.orientation * mOrientationScale;
5069 break;
5070 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5071 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5072 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5073 if (c1 != 0 || c2 != 0) {
5074 orientation = atan2f(c1, c2) * 0.5f;
5075 float confidence = hypotf(c1, c2);
5076 float scale = 1.0f + confidence / 16.0f;
5077 touchMajor *= scale;
5078 touchMinor /= scale;
5079 toolMajor *= scale;
5080 toolMinor /= scale;
5081 } else {
5082 orientation = 0;
5083 }
5084 break;
5085 }
5086 default:
5087 orientation = 0;
5088 }
5089 }
5090
5091 // Distance
5092 float distance;
5093 switch (mCalibration.distanceCalibration) {
5094 case Calibration::DISTANCE_CALIBRATION_SCALED:
5095 distance = in.distance * mDistanceScale;
5096 break;
5097 default:
5098 distance = 0;
5099 }
5100
5101 // Coverage
5102 int32_t rawLeft, rawTop, rawRight, rawBottom;
5103 switch (mCalibration.coverageCalibration) {
5104 case Calibration::COVERAGE_CALIBRATION_BOX:
5105 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5106 rawRight = in.toolMinor & 0x0000ffff;
5107 rawBottom = in.toolMajor & 0x0000ffff;
5108 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5109 break;
5110 default:
5111 rawLeft = rawTop = rawRight = rawBottom = 0;
5112 break;
5113 }
5114
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005115 // Adjust X,Y coords for device calibration
5116 // TODO: Adjust coverage coords?
5117 float xTransformed = in.x, yTransformed = in.y;
5118 mAffineTransform.applyTo(xTransformed, yTransformed);
5119
5120 // Adjust X, Y, and coverage coords for surface orientation.
5121 float x, y;
5122 float left, top, right, bottom;
5123
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 switch (mSurfaceOrientation) {
5125 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005126 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5127 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5129 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5130 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5131 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5132 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005133 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5135 }
5136 break;
5137 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005138 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005139 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005140 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5141 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5143 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5144 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005145 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5147 }
5148 break;
5149 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005150 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005151 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005152 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5153 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5155 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5156 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005157 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5159 }
5160 break;
5161 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005162 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5163 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5165 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5166 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5167 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5168 break;
5169 }
5170
5171 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005172 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 out.clear();
5174 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5175 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5176 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5177 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5178 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5179 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5180 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5181 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5182 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5183 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5184 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5185 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5186 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5187 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5188 } else {
5189 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5190 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5191 }
5192
5193 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005194 PointerProperties& properties =
5195 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196 uint32_t id = in.id;
5197 properties.clear();
5198 properties.id = id;
5199 properties.toolType = in.toolType;
5200
5201 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005202 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 }
5204}
5205
5206void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5207 PointerUsage pointerUsage) {
5208 if (pointerUsage != mPointerUsage) {
5209 abortPointerUsage(when, policyFlags);
5210 mPointerUsage = pointerUsage;
5211 }
5212
5213 switch (mPointerUsage) {
5214 case POINTER_USAGE_GESTURES:
5215 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5216 break;
5217 case POINTER_USAGE_STYLUS:
5218 dispatchPointerStylus(when, policyFlags);
5219 break;
5220 case POINTER_USAGE_MOUSE:
5221 dispatchPointerMouse(when, policyFlags);
5222 break;
5223 default:
5224 break;
5225 }
5226}
5227
5228void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5229 switch (mPointerUsage) {
5230 case POINTER_USAGE_GESTURES:
5231 abortPointerGestures(when, policyFlags);
5232 break;
5233 case POINTER_USAGE_STYLUS:
5234 abortPointerStylus(when, policyFlags);
5235 break;
5236 case POINTER_USAGE_MOUSE:
5237 abortPointerMouse(when, policyFlags);
5238 break;
5239 default:
5240 break;
5241 }
5242
5243 mPointerUsage = POINTER_USAGE_NONE;
5244}
5245
5246void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5247 bool isTimeout) {
5248 // Update current gesture coordinates.
5249 bool cancelPreviousGesture, finishPreviousGesture;
5250 bool sendEvents = preparePointerGestures(when,
5251 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5252 if (!sendEvents) {
5253 return;
5254 }
5255 if (finishPreviousGesture) {
5256 cancelPreviousGesture = false;
5257 }
5258
5259 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005260 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5261 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 if (finishPreviousGesture || cancelPreviousGesture) {
5263 mPointerController->clearSpots();
5264 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005265
5266 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5267 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5268 mPointerGesture.currentGestureIdToIndex,
5269 mPointerGesture.currentGestureIdBits);
5270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271 } else {
5272 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5273 }
5274
5275 // Show or hide the pointer if needed.
5276 switch (mPointerGesture.currentGestureMode) {
5277 case PointerGesture::NEUTRAL:
5278 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005279 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5280 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281 // Remind the user of where the pointer is after finishing a gesture with spots.
5282 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5283 }
5284 break;
5285 case PointerGesture::TAP:
5286 case PointerGesture::TAP_DRAG:
5287 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5288 case PointerGesture::HOVER:
5289 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005290 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291 // Unfade the pointer when the current gesture manipulates the
5292 // area directly under the pointer.
5293 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5294 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005295 case PointerGesture::FREEFORM:
5296 // Fade the pointer when the current gesture manipulates a different
5297 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005298 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5300 } else {
5301 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5302 }
5303 break;
5304 }
5305
5306 // Send events!
5307 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005308 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309
5310 // Update last coordinates of pointers that have moved so that we observe the new
5311 // pointer positions at the same time as other pointers that have just gone up.
5312 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5313 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5314 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5315 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5316 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5317 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5318 bool moveNeeded = false;
5319 if (down && !cancelPreviousGesture && !finishPreviousGesture
5320 && !mPointerGesture.lastGestureIdBits.isEmpty()
5321 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5322 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5323 & mPointerGesture.lastGestureIdBits.value);
5324 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5325 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5326 mPointerGesture.lastGestureProperties,
5327 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5328 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005329 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 moveNeeded = true;
5331 }
5332 }
5333
5334 // Send motion events for all pointers that went up or were canceled.
5335 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5336 if (!dispatchedGestureIdBits.isEmpty()) {
5337 if (cancelPreviousGesture) {
5338 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005339 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005340 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 mPointerGesture.lastGestureProperties,
5342 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005343 dispatchedGestureIdBits, -1, 0,
5344 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345
5346 dispatchedGestureIdBits.clear();
5347 } else {
5348 BitSet32 upGestureIdBits;
5349 if (finishPreviousGesture) {
5350 upGestureIdBits = dispatchedGestureIdBits;
5351 } else {
5352 upGestureIdBits.value = dispatchedGestureIdBits.value
5353 & ~mPointerGesture.currentGestureIdBits.value;
5354 }
5355 while (!upGestureIdBits.isEmpty()) {
5356 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5357
5358 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005359 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005361 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005362 mPointerGesture.lastGestureProperties,
5363 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5364 dispatchedGestureIdBits, id,
5365 0, 0, mPointerGesture.downTime);
5366
5367 dispatchedGestureIdBits.clearBit(id);
5368 }
5369 }
5370 }
5371
5372 // Send motion events for all pointers that moved.
5373 if (moveNeeded) {
5374 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005375 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005376 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377 mPointerGesture.currentGestureProperties,
5378 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5379 dispatchedGestureIdBits, -1,
5380 0, 0, mPointerGesture.downTime);
5381 }
5382
5383 // Send motion events for all pointers that went down.
5384 if (down) {
5385 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5386 & ~dispatchedGestureIdBits.value);
5387 while (!downGestureIdBits.isEmpty()) {
5388 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5389 dispatchedGestureIdBits.markBit(id);
5390
5391 if (dispatchedGestureIdBits.count() == 1) {
5392 mPointerGesture.downTime = when;
5393 }
5394
5395 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005396 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005397 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005398 mPointerGesture.currentGestureProperties,
5399 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5400 dispatchedGestureIdBits, id,
5401 0, 0, mPointerGesture.downTime);
5402 }
5403 }
5404
5405 // Send motion events for hover.
5406 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5407 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005408 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005409 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 mPointerGesture.currentGestureProperties,
5411 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5412 mPointerGesture.currentGestureIdBits, -1,
5413 0, 0, mPointerGesture.downTime);
5414 } else if (dispatchedGestureIdBits.isEmpty()
5415 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5416 // Synthesize a hover move event after all pointers go up to indicate that
5417 // the pointer is hovering again even if the user is not currently touching
5418 // the touch pad. This ensures that a view will receive a fresh hover enter
5419 // event after a tap.
5420 float x, y;
5421 mPointerController->getPosition(&x, &y);
5422
5423 PointerProperties pointerProperties;
5424 pointerProperties.clear();
5425 pointerProperties.id = 0;
5426 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5427
5428 PointerCoords pointerCoords;
5429 pointerCoords.clear();
5430 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5431 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5432
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005433 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005434 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005435 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005436 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005437 0, 0, mPointerGesture.downTime);
5438 getListener()->notifyMotion(&args);
5439 }
5440
5441 // Update state.
5442 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5443 if (!down) {
5444 mPointerGesture.lastGestureIdBits.clear();
5445 } else {
5446 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5447 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5448 uint32_t id = idBits.clearFirstMarkedBit();
5449 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5450 mPointerGesture.lastGestureProperties[index].copyFrom(
5451 mPointerGesture.currentGestureProperties[index]);
5452 mPointerGesture.lastGestureCoords[index].copyFrom(
5453 mPointerGesture.currentGestureCoords[index]);
5454 mPointerGesture.lastGestureIdToIndex[id] = index;
5455 }
5456 }
5457}
5458
5459void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5460 // Cancel previously dispatches pointers.
5461 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5462 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005463 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005464 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005465 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005466 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 mPointerGesture.lastGestureProperties,
5468 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5469 mPointerGesture.lastGestureIdBits, -1,
5470 0, 0, mPointerGesture.downTime);
5471 }
5472
5473 // Reset the current pointer gesture.
5474 mPointerGesture.reset();
5475 mPointerVelocityControl.reset();
5476
5477 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005478 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5480 mPointerController->clearSpots();
5481 }
5482}
5483
5484bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5485 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5486 *outCancelPreviousGesture = false;
5487 *outFinishPreviousGesture = false;
5488
5489 // Handle TAP timeout.
5490 if (isTimeout) {
5491#if DEBUG_GESTURES
5492 ALOGD("Gestures: Processing timeout");
5493#endif
5494
5495 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5496 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5497 // The tap/drag timeout has not yet expired.
5498 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5499 + mConfig.pointerGestureTapDragInterval);
5500 } else {
5501 // The tap is finished.
5502#if DEBUG_GESTURES
5503 ALOGD("Gestures: TAP finished");
5504#endif
5505 *outFinishPreviousGesture = true;
5506
5507 mPointerGesture.activeGestureId = -1;
5508 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5509 mPointerGesture.currentGestureIdBits.clear();
5510
5511 mPointerVelocityControl.reset();
5512 return true;
5513 }
5514 }
5515
5516 // We did not handle this timeout.
5517 return false;
5518 }
5519
Michael Wright842500e2015-03-13 17:32:02 -07005520 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5521 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005522
5523 // Update the velocity tracker.
5524 {
5525 VelocityTracker::Position positions[MAX_POINTERS];
5526 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005527 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005529 const RawPointerData::Pointer& pointer =
5530 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005531 positions[count].x = pointer.x * mPointerXMovementScale;
5532 positions[count].y = pointer.y * mPointerYMovementScale;
5533 }
5534 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005535 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 }
5537
5538 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5539 // to NEUTRAL, then we should not generate tap event.
5540 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5541 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5542 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5543 mPointerGesture.resetTap();
5544 }
5545
5546 // Pick a new active touch id if needed.
5547 // Choose an arbitrary pointer that just went down, if there is one.
5548 // Otherwise choose an arbitrary remaining pointer.
5549 // This guarantees we always have an active touch id when there is at least one pointer.
5550 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5552 int32_t activeTouchId = lastActiveTouchId;
5553 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005554 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005555 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005556 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 mPointerGesture.firstTouchTime = when;
5558 }
Michael Wright842500e2015-03-13 17:32:02 -07005559 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005560 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005561 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005562 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563 } else {
5564 activeTouchId = mPointerGesture.activeTouchId = -1;
5565 }
5566 }
5567
5568 // Determine whether we are in quiet time.
5569 bool isQuietTime = false;
5570 if (activeTouchId < 0) {
5571 mPointerGesture.resetQuietTime();
5572 } else {
5573 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5574 if (!isQuietTime) {
5575 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5576 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5577 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5578 && currentFingerCount < 2) {
5579 // Enter quiet time when exiting swipe or freeform state.
5580 // This is to prevent accidentally entering the hover state and flinging the
5581 // pointer when finishing a swipe and there is still one pointer left onscreen.
5582 isQuietTime = true;
5583 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5584 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005585 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586 // Enter quiet time when releasing the button and there are still two or more
5587 // fingers down. This may indicate that one finger was used to press the button
5588 // but it has not gone up yet.
5589 isQuietTime = true;
5590 }
5591 if (isQuietTime) {
5592 mPointerGesture.quietTime = when;
5593 }
5594 }
5595 }
5596
5597 // Switch states based on button and pointer state.
5598 if (isQuietTime) {
5599 // Case 1: Quiet time. (QUIET)
5600#if DEBUG_GESTURES
5601 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5602 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5603#endif
5604 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5605 *outFinishPreviousGesture = true;
5606 }
5607
5608 mPointerGesture.activeGestureId = -1;
5609 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5610 mPointerGesture.currentGestureIdBits.clear();
5611
5612 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005613 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005614 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5615 // The pointer follows the active touch point.
5616 // Emit DOWN, MOVE, UP events at the pointer location.
5617 //
5618 // Only the active touch matters; other fingers are ignored. This policy helps
5619 // to handle the case where the user places a second finger on the touch pad
5620 // to apply the necessary force to depress an integrated button below the surface.
5621 // We don't want the second finger to be delivered to applications.
5622 //
5623 // For this to work well, we need to make sure to track the pointer that is really
5624 // active. If the user first puts one finger down to click then adds another
5625 // finger to drag then the active pointer should switch to the finger that is
5626 // being dragged.
5627#if DEBUG_GESTURES
5628 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5629 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5630#endif
5631 // Reset state when just starting.
5632 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5633 *outFinishPreviousGesture = true;
5634 mPointerGesture.activeGestureId = 0;
5635 }
5636
5637 // Switch pointers if needed.
5638 // Find the fastest pointer and follow it.
5639 if (activeTouchId >= 0 && currentFingerCount > 1) {
5640 int32_t bestId = -1;
5641 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005642 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005643 uint32_t id = idBits.clearFirstMarkedBit();
5644 float vx, vy;
5645 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5646 float speed = hypotf(vx, vy);
5647 if (speed > bestSpeed) {
5648 bestId = id;
5649 bestSpeed = speed;
5650 }
5651 }
5652 }
5653 if (bestId >= 0 && bestId != activeTouchId) {
5654 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005655#if DEBUG_GESTURES
5656 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5657 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5658#endif
5659 }
5660 }
5661
Jun Mukaifa1706a2015-12-03 01:14:46 -08005662 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005663 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005665 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005666 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005667 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005668 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5669 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670
5671 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5672 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5673
5674 // Move the pointer using a relative motion.
5675 // When using spots, the click will occur at the position of the anchor
5676 // spot and all other spots will move there.
5677 mPointerController->move(deltaX, deltaY);
5678 } else {
5679 mPointerVelocityControl.reset();
5680 }
5681
5682 float x, y;
5683 mPointerController->getPosition(&x, &y);
5684
5685 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5686 mPointerGesture.currentGestureIdBits.clear();
5687 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5688 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5689 mPointerGesture.currentGestureProperties[0].clear();
5690 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5691 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5692 mPointerGesture.currentGestureCoords[0].clear();
5693 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5694 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5695 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5696 } else if (currentFingerCount == 0) {
5697 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5698 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5699 *outFinishPreviousGesture = true;
5700 }
5701
5702 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5703 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5704 bool tapped = false;
5705 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5706 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5707 && lastFingerCount == 1) {
5708 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5709 float x, y;
5710 mPointerController->getPosition(&x, &y);
5711 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5712 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5713#if DEBUG_GESTURES
5714 ALOGD("Gestures: TAP");
5715#endif
5716
5717 mPointerGesture.tapUpTime = when;
5718 getContext()->requestTimeoutAtTime(when
5719 + mConfig.pointerGestureTapDragInterval);
5720
5721 mPointerGesture.activeGestureId = 0;
5722 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5723 mPointerGesture.currentGestureIdBits.clear();
5724 mPointerGesture.currentGestureIdBits.markBit(
5725 mPointerGesture.activeGestureId);
5726 mPointerGesture.currentGestureIdToIndex[
5727 mPointerGesture.activeGestureId] = 0;
5728 mPointerGesture.currentGestureProperties[0].clear();
5729 mPointerGesture.currentGestureProperties[0].id =
5730 mPointerGesture.activeGestureId;
5731 mPointerGesture.currentGestureProperties[0].toolType =
5732 AMOTION_EVENT_TOOL_TYPE_FINGER;
5733 mPointerGesture.currentGestureCoords[0].clear();
5734 mPointerGesture.currentGestureCoords[0].setAxisValue(
5735 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5736 mPointerGesture.currentGestureCoords[0].setAxisValue(
5737 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5738 mPointerGesture.currentGestureCoords[0].setAxisValue(
5739 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5740
5741 tapped = true;
5742 } else {
5743#if DEBUG_GESTURES
5744 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5745 x - mPointerGesture.tapX,
5746 y - mPointerGesture.tapY);
5747#endif
5748 }
5749 } else {
5750#if DEBUG_GESTURES
5751 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5752 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5753 (when - mPointerGesture.tapDownTime) * 0.000001f);
5754 } else {
5755 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5756 }
5757#endif
5758 }
5759 }
5760
5761 mPointerVelocityControl.reset();
5762
5763 if (!tapped) {
5764#if DEBUG_GESTURES
5765 ALOGD("Gestures: NEUTRAL");
5766#endif
5767 mPointerGesture.activeGestureId = -1;
5768 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5769 mPointerGesture.currentGestureIdBits.clear();
5770 }
5771 } else if (currentFingerCount == 1) {
5772 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5773 // The pointer follows the active touch point.
5774 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5775 // When in TAP_DRAG, emit MOVE events at the pointer location.
5776 ALOG_ASSERT(activeTouchId >= 0);
5777
5778 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5779 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5780 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5781 float x, y;
5782 mPointerController->getPosition(&x, &y);
5783 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5784 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5785 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5786 } else {
5787#if DEBUG_GESTURES
5788 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5789 x - mPointerGesture.tapX,
5790 y - mPointerGesture.tapY);
5791#endif
5792 }
5793 } else {
5794#if DEBUG_GESTURES
5795 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5796 (when - mPointerGesture.tapUpTime) * 0.000001f);
5797#endif
5798 }
5799 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5800 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5801 }
5802
Jun Mukaifa1706a2015-12-03 01:14:46 -08005803 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005804 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005805 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005806 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005807 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005808 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005809 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5810 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005811
5812 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5813 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5814
5815 // Move the pointer using a relative motion.
5816 // When using spots, the hover or drag will occur at the position of the anchor spot.
5817 mPointerController->move(deltaX, deltaY);
5818 } else {
5819 mPointerVelocityControl.reset();
5820 }
5821
5822 bool down;
5823 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5824#if DEBUG_GESTURES
5825 ALOGD("Gestures: TAP_DRAG");
5826#endif
5827 down = true;
5828 } else {
5829#if DEBUG_GESTURES
5830 ALOGD("Gestures: HOVER");
5831#endif
5832 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5833 *outFinishPreviousGesture = true;
5834 }
5835 mPointerGesture.activeGestureId = 0;
5836 down = false;
5837 }
5838
5839 float x, y;
5840 mPointerController->getPosition(&x, &y);
5841
5842 mPointerGesture.currentGestureIdBits.clear();
5843 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5844 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5845 mPointerGesture.currentGestureProperties[0].clear();
5846 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5847 mPointerGesture.currentGestureProperties[0].toolType =
5848 AMOTION_EVENT_TOOL_TYPE_FINGER;
5849 mPointerGesture.currentGestureCoords[0].clear();
5850 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5851 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5852 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5853 down ? 1.0f : 0.0f);
5854
5855 if (lastFingerCount == 0 && currentFingerCount != 0) {
5856 mPointerGesture.resetTap();
5857 mPointerGesture.tapDownTime = when;
5858 mPointerGesture.tapX = x;
5859 mPointerGesture.tapY = y;
5860 }
5861 } else {
5862 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5863 // We need to provide feedback for each finger that goes down so we cannot wait
5864 // for the fingers to move before deciding what to do.
5865 //
5866 // The ambiguous case is deciding what to do when there are two fingers down but they
5867 // have not moved enough to determine whether they are part of a drag or part of a
5868 // freeform gesture, or just a press or long-press at the pointer location.
5869 //
5870 // When there are two fingers we start with the PRESS hypothesis and we generate a
5871 // down at the pointer location.
5872 //
5873 // When the two fingers move enough or when additional fingers are added, we make
5874 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5875 ALOG_ASSERT(activeTouchId >= 0);
5876
5877 bool settled = when >= mPointerGesture.firstTouchTime
5878 + mConfig.pointerGestureMultitouchSettleInterval;
5879 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5880 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5881 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5882 *outFinishPreviousGesture = true;
5883 } else if (!settled && currentFingerCount > lastFingerCount) {
5884 // Additional pointers have gone down but not yet settled.
5885 // Reset the gesture.
5886#if DEBUG_GESTURES
5887 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5888 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5889 + mConfig.pointerGestureMultitouchSettleInterval - when)
5890 * 0.000001f);
5891#endif
5892 *outCancelPreviousGesture = true;
5893 } else {
5894 // Continue previous gesture.
5895 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5896 }
5897
5898 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5899 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5900 mPointerGesture.activeGestureId = 0;
5901 mPointerGesture.referenceIdBits.clear();
5902 mPointerVelocityControl.reset();
5903
5904 // Use the centroid and pointer location as the reference points for the gesture.
5905#if DEBUG_GESTURES
5906 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5907 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5908 + mConfig.pointerGestureMultitouchSettleInterval - when)
5909 * 0.000001f);
5910#endif
Michael Wright842500e2015-03-13 17:32:02 -07005911 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005912 &mPointerGesture.referenceTouchX,
5913 &mPointerGesture.referenceTouchY);
5914 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5915 &mPointerGesture.referenceGestureY);
5916 }
5917
5918 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005919 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005920 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5921 uint32_t id = idBits.clearFirstMarkedBit();
5922 mPointerGesture.referenceDeltas[id].dx = 0;
5923 mPointerGesture.referenceDeltas[id].dy = 0;
5924 }
Michael Wright842500e2015-03-13 17:32:02 -07005925 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005926
5927 // Add delta for all fingers and calculate a common movement delta.
5928 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005929 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5930 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5932 bool first = (idBits == commonIdBits);
5933 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005934 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5935 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5937 delta.dx += cpd.x - lpd.x;
5938 delta.dy += cpd.y - lpd.y;
5939
5940 if (first) {
5941 commonDeltaX = delta.dx;
5942 commonDeltaY = delta.dy;
5943 } else {
5944 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5945 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5946 }
5947 }
5948
5949 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5950 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5951 float dist[MAX_POINTER_ID + 1];
5952 int32_t distOverThreshold = 0;
5953 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5954 uint32_t id = idBits.clearFirstMarkedBit();
5955 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5956 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5957 delta.dy * mPointerYZoomScale);
5958 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5959 distOverThreshold += 1;
5960 }
5961 }
5962
5963 // Only transition when at least two pointers have moved further than
5964 // the minimum distance threshold.
5965 if (distOverThreshold >= 2) {
5966 if (currentFingerCount > 2) {
5967 // There are more than two pointers, switch to FREEFORM.
5968#if DEBUG_GESTURES
5969 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5970 currentFingerCount);
5971#endif
5972 *outCancelPreviousGesture = true;
5973 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5974 } else {
5975 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005976 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005977 uint32_t id1 = idBits.clearFirstMarkedBit();
5978 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005979 const RawPointerData::Pointer& p1 =
5980 mCurrentRawState.rawPointerData.pointerForId(id1);
5981 const RawPointerData::Pointer& p2 =
5982 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005983 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5984 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5985 // There are two pointers but they are too far apart for a SWIPE,
5986 // switch to FREEFORM.
5987#if DEBUG_GESTURES
5988 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5989 mutualDistance, mPointerGestureMaxSwipeWidth);
5990#endif
5991 *outCancelPreviousGesture = true;
5992 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5993 } else {
5994 // There are two pointers. Wait for both pointers to start moving
5995 // before deciding whether this is a SWIPE or FREEFORM gesture.
5996 float dist1 = dist[id1];
5997 float dist2 = dist[id2];
5998 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5999 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6000 // Calculate the dot product of the displacement vectors.
6001 // When the vectors are oriented in approximately the same direction,
6002 // the angle betweeen them is near zero and the cosine of the angle
6003 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6004 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6005 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6006 float dx1 = delta1.dx * mPointerXZoomScale;
6007 float dy1 = delta1.dy * mPointerYZoomScale;
6008 float dx2 = delta2.dx * mPointerXZoomScale;
6009 float dy2 = delta2.dy * mPointerYZoomScale;
6010 float dot = dx1 * dx2 + dy1 * dy2;
6011 float cosine = dot / (dist1 * dist2); // denominator always > 0
6012 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6013 // Pointers are moving in the same direction. Switch to SWIPE.
6014#if DEBUG_GESTURES
6015 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6016 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6017 "cosine %0.3f >= %0.3f",
6018 dist1, mConfig.pointerGestureMultitouchMinDistance,
6019 dist2, mConfig.pointerGestureMultitouchMinDistance,
6020 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6021#endif
6022 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6023 } else {
6024 // Pointers are moving in different directions. Switch to FREEFORM.
6025#if DEBUG_GESTURES
6026 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6027 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6028 "cosine %0.3f < %0.3f",
6029 dist1, mConfig.pointerGestureMultitouchMinDistance,
6030 dist2, mConfig.pointerGestureMultitouchMinDistance,
6031 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6032#endif
6033 *outCancelPreviousGesture = true;
6034 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6035 }
6036 }
6037 }
6038 }
6039 }
6040 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6041 // Switch from SWIPE to FREEFORM if additional pointers go down.
6042 // Cancel previous gesture.
6043 if (currentFingerCount > 2) {
6044#if DEBUG_GESTURES
6045 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6046 currentFingerCount);
6047#endif
6048 *outCancelPreviousGesture = true;
6049 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6050 }
6051 }
6052
6053 // Move the reference points based on the overall group motion of the fingers
6054 // except in PRESS mode while waiting for a transition to occur.
6055 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6056 && (commonDeltaX || commonDeltaY)) {
6057 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6058 uint32_t id = idBits.clearFirstMarkedBit();
6059 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6060 delta.dx = 0;
6061 delta.dy = 0;
6062 }
6063
6064 mPointerGesture.referenceTouchX += commonDeltaX;
6065 mPointerGesture.referenceTouchY += commonDeltaY;
6066
6067 commonDeltaX *= mPointerXMovementScale;
6068 commonDeltaY *= mPointerYMovementScale;
6069
6070 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6071 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6072
6073 mPointerGesture.referenceGestureX += commonDeltaX;
6074 mPointerGesture.referenceGestureY += commonDeltaY;
6075 }
6076
6077 // Report gestures.
6078 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6079 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6080 // PRESS or SWIPE mode.
6081#if DEBUG_GESTURES
6082 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6083 "activeGestureId=%d, currentTouchPointerCount=%d",
6084 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6085#endif
6086 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6087
6088 mPointerGesture.currentGestureIdBits.clear();
6089 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6090 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6091 mPointerGesture.currentGestureProperties[0].clear();
6092 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6093 mPointerGesture.currentGestureProperties[0].toolType =
6094 AMOTION_EVENT_TOOL_TYPE_FINGER;
6095 mPointerGesture.currentGestureCoords[0].clear();
6096 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6097 mPointerGesture.referenceGestureX);
6098 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6099 mPointerGesture.referenceGestureY);
6100 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6101 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6102 // FREEFORM mode.
6103#if DEBUG_GESTURES
6104 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6105 "activeGestureId=%d, currentTouchPointerCount=%d",
6106 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6107#endif
6108 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6109
6110 mPointerGesture.currentGestureIdBits.clear();
6111
6112 BitSet32 mappedTouchIdBits;
6113 BitSet32 usedGestureIdBits;
6114 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6115 // Initially, assign the active gesture id to the active touch point
6116 // if there is one. No other touch id bits are mapped yet.
6117 if (!*outCancelPreviousGesture) {
6118 mappedTouchIdBits.markBit(activeTouchId);
6119 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6120 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6121 mPointerGesture.activeGestureId;
6122 } else {
6123 mPointerGesture.activeGestureId = -1;
6124 }
6125 } else {
6126 // Otherwise, assume we mapped all touches from the previous frame.
6127 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006128 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6129 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006130 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6131
6132 // Check whether we need to choose a new active gesture id because the
6133 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006134 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6135 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006136 !upTouchIdBits.isEmpty(); ) {
6137 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6138 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6139 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6140 mPointerGesture.activeGestureId = -1;
6141 break;
6142 }
6143 }
6144 }
6145
6146#if DEBUG_GESTURES
6147 ALOGD("Gestures: FREEFORM follow up "
6148 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6149 "activeGestureId=%d",
6150 mappedTouchIdBits.value, usedGestureIdBits.value,
6151 mPointerGesture.activeGestureId);
6152#endif
6153
Michael Wright842500e2015-03-13 17:32:02 -07006154 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006155 for (uint32_t i = 0; i < currentFingerCount; i++) {
6156 uint32_t touchId = idBits.clearFirstMarkedBit();
6157 uint32_t gestureId;
6158 if (!mappedTouchIdBits.hasBit(touchId)) {
6159 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6160 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6161#if DEBUG_GESTURES
6162 ALOGD("Gestures: FREEFORM "
6163 "new mapping for touch id %d -> gesture id %d",
6164 touchId, gestureId);
6165#endif
6166 } else {
6167 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6168#if DEBUG_GESTURES
6169 ALOGD("Gestures: FREEFORM "
6170 "existing mapping for touch id %d -> gesture id %d",
6171 touchId, gestureId);
6172#endif
6173 }
6174 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6175 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6176
6177 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006178 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006179 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6180 * mPointerXZoomScale;
6181 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6182 * mPointerYZoomScale;
6183 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6184
6185 mPointerGesture.currentGestureProperties[i].clear();
6186 mPointerGesture.currentGestureProperties[i].id = gestureId;
6187 mPointerGesture.currentGestureProperties[i].toolType =
6188 AMOTION_EVENT_TOOL_TYPE_FINGER;
6189 mPointerGesture.currentGestureCoords[i].clear();
6190 mPointerGesture.currentGestureCoords[i].setAxisValue(
6191 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6192 mPointerGesture.currentGestureCoords[i].setAxisValue(
6193 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6194 mPointerGesture.currentGestureCoords[i].setAxisValue(
6195 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6196 }
6197
6198 if (mPointerGesture.activeGestureId < 0) {
6199 mPointerGesture.activeGestureId =
6200 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6201#if DEBUG_GESTURES
6202 ALOGD("Gestures: FREEFORM new "
6203 "activeGestureId=%d", mPointerGesture.activeGestureId);
6204#endif
6205 }
6206 }
6207 }
6208
Michael Wright842500e2015-03-13 17:32:02 -07006209 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006210
6211#if DEBUG_GESTURES
6212 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6213 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6214 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6215 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6216 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6217 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6218 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6219 uint32_t id = idBits.clearFirstMarkedBit();
6220 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6221 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6222 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6223 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6224 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6225 id, index, properties.toolType,
6226 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6227 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6228 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6229 }
6230 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6231 uint32_t id = idBits.clearFirstMarkedBit();
6232 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6233 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6234 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6235 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6236 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6237 id, index, properties.toolType,
6238 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6239 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6240 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6241 }
6242#endif
6243 return true;
6244}
6245
6246void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6247 mPointerSimple.currentCoords.clear();
6248 mPointerSimple.currentProperties.clear();
6249
6250 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006251 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6252 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6253 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6254 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6255 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256 mPointerController->setPosition(x, y);
6257
Michael Wright842500e2015-03-13 17:32:02 -07006258 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006259 down = !hovering;
6260
6261 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006262 mPointerSimple.currentCoords.copyFrom(
6263 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006264 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6265 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6266 mPointerSimple.currentProperties.id = 0;
6267 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006268 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006269 } else {
6270 down = false;
6271 hovering = false;
6272 }
6273
6274 dispatchPointerSimple(when, policyFlags, down, hovering);
6275}
6276
6277void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6278 abortPointerSimple(when, policyFlags);
6279}
6280
6281void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6282 mPointerSimple.currentCoords.clear();
6283 mPointerSimple.currentProperties.clear();
6284
6285 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006286 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6287 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6288 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006289 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006290 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6291 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006292 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006293 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006294 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006295 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006296 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006297 * mPointerYMovementScale;
6298
6299 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6300 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6301
6302 mPointerController->move(deltaX, deltaY);
6303 } else {
6304 mPointerVelocityControl.reset();
6305 }
6306
Michael Wright842500e2015-03-13 17:32:02 -07006307 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308 hovering = !down;
6309
6310 float x, y;
6311 mPointerController->getPosition(&x, &y);
6312 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006313 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6315 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6316 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6317 hovering ? 0.0f : 1.0f);
6318 mPointerSimple.currentProperties.id = 0;
6319 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006320 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006321 } else {
6322 mPointerVelocityControl.reset();
6323
6324 down = false;
6325 hovering = false;
6326 }
6327
6328 dispatchPointerSimple(when, policyFlags, down, hovering);
6329}
6330
6331void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6332 abortPointerSimple(when, policyFlags);
6333
6334 mPointerVelocityControl.reset();
6335}
6336
6337void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6338 bool down, bool hovering) {
6339 int32_t metaState = getContext()->getGlobalMetaState();
6340
Yi Kong9b14ac62018-07-17 13:48:38 -07006341 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006342 if (down || hovering) {
6343 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6344 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006345 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006346 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6347 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6348 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6349 }
6350 }
6351
6352 if (mPointerSimple.down && !down) {
6353 mPointerSimple.down = false;
6354
6355 // Send up.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006356 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006357 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006358 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006359 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6360 mOrientedXPrecision, mOrientedYPrecision,
6361 mPointerSimple.downTime);
6362 getListener()->notifyMotion(&args);
6363 }
6364
6365 if (mPointerSimple.hovering && !hovering) {
6366 mPointerSimple.hovering = false;
6367
6368 // Send hover exit.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006369 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006370 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006371 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006372 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6373 mOrientedXPrecision, mOrientedYPrecision,
6374 mPointerSimple.downTime);
6375 getListener()->notifyMotion(&args);
6376 }
6377
6378 if (down) {
6379 if (!mPointerSimple.down) {
6380 mPointerSimple.down = true;
6381 mPointerSimple.downTime = when;
6382
6383 // Send down.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006384 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006385 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006386 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006387 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6388 mOrientedXPrecision, mOrientedYPrecision,
6389 mPointerSimple.downTime);
6390 getListener()->notifyMotion(&args);
6391 }
6392
6393 // Send move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006394 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006395 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006396 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006397 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6398 mOrientedXPrecision, mOrientedYPrecision,
6399 mPointerSimple.downTime);
6400 getListener()->notifyMotion(&args);
6401 }
6402
6403 if (hovering) {
6404 if (!mPointerSimple.hovering) {
6405 mPointerSimple.hovering = true;
6406
6407 // Send hover enter.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006408 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006409 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006410 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006411 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6413 mOrientedXPrecision, mOrientedYPrecision,
6414 mPointerSimple.downTime);
6415 getListener()->notifyMotion(&args);
6416 }
6417
6418 // Send hover move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006419 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006420 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006421 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006422 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006423 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6424 mOrientedXPrecision, mOrientedYPrecision,
6425 mPointerSimple.downTime);
6426 getListener()->notifyMotion(&args);
6427 }
6428
Michael Wright842500e2015-03-13 17:32:02 -07006429 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6430 float vscroll = mCurrentRawState.rawVScroll;
6431 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006432 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6433 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006434
6435 // Send scroll.
6436 PointerCoords pointerCoords;
6437 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6438 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6439 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6440
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006441 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006442 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006443 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006444 1, &mPointerSimple.currentProperties, &pointerCoords,
6445 mOrientedXPrecision, mOrientedYPrecision,
6446 mPointerSimple.downTime);
6447 getListener()->notifyMotion(&args);
6448 }
6449
6450 // Save state.
6451 if (down || hovering) {
6452 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6453 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6454 } else {
6455 mPointerSimple.reset();
6456 }
6457}
6458
6459void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6460 mPointerSimple.currentCoords.clear();
6461 mPointerSimple.currentProperties.clear();
6462
6463 dispatchPointerSimple(when, policyFlags, false, false);
6464}
6465
6466void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006467 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006468 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006469 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006470 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6471 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006472 PointerCoords pointerCoords[MAX_POINTERS];
6473 PointerProperties pointerProperties[MAX_POINTERS];
6474 uint32_t pointerCount = 0;
6475 while (!idBits.isEmpty()) {
6476 uint32_t id = idBits.clearFirstMarkedBit();
6477 uint32_t index = idToIndex[id];
6478 pointerProperties[pointerCount].copyFrom(properties[index]);
6479 pointerCoords[pointerCount].copyFrom(coords[index]);
6480
6481 if (changedId >= 0 && id == uint32_t(changedId)) {
6482 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6483 }
6484
6485 pointerCount += 1;
6486 }
6487
6488 ALOG_ASSERT(pointerCount != 0);
6489
6490 if (changedId >= 0 && pointerCount == 1) {
6491 // Replace initial down and final up action.
6492 // We can compare the action without masking off the changed pointer index
6493 // because we know the index is 0.
6494 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6495 action = AMOTION_EVENT_ACTION_DOWN;
6496 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6497 action = AMOTION_EVENT_ACTION_UP;
6498 } else {
6499 // Can't happen.
6500 ALOG_ASSERT(false);
6501 }
6502 }
6503
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006504 NotifyMotionArgs args(when, getDeviceId(), source, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006505 action, actionButton, flags, metaState, buttonState, edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006506 deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006507 xPrecision, yPrecision, downTime);
6508 getListener()->notifyMotion(&args);
6509}
6510
6511bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6512 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6513 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6514 BitSet32 idBits) const {
6515 bool changed = false;
6516 while (!idBits.isEmpty()) {
6517 uint32_t id = idBits.clearFirstMarkedBit();
6518 uint32_t inIndex = inIdToIndex[id];
6519 uint32_t outIndex = outIdToIndex[id];
6520
6521 const PointerProperties& curInProperties = inProperties[inIndex];
6522 const PointerCoords& curInCoords = inCoords[inIndex];
6523 PointerProperties& curOutProperties = outProperties[outIndex];
6524 PointerCoords& curOutCoords = outCoords[outIndex];
6525
6526 if (curInProperties != curOutProperties) {
6527 curOutProperties.copyFrom(curInProperties);
6528 changed = true;
6529 }
6530
6531 if (curInCoords != curOutCoords) {
6532 curOutCoords.copyFrom(curInCoords);
6533 changed = true;
6534 }
6535 }
6536 return changed;
6537}
6538
6539void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006540 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006541 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6542 }
6543}
6544
Jeff Brownc9aa6282015-02-11 19:03:28 -08006545void TouchInputMapper::cancelTouch(nsecs_t when) {
6546 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006547 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006548}
6549
Michael Wrightd02c5b62014-02-10 15:10:22 -08006550bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006551 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006552 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006553 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006554 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6555 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6556 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006557}
6558
6559const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6560 int32_t x, int32_t y) {
6561 size_t numVirtualKeys = mVirtualKeys.size();
6562 for (size_t i = 0; i < numVirtualKeys; i++) {
6563 const VirtualKey& virtualKey = mVirtualKeys[i];
6564
6565#if DEBUG_VIRTUAL_KEYS
6566 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6567 "left=%d, top=%d, right=%d, bottom=%d",
6568 x, y,
6569 virtualKey.keyCode, virtualKey.scanCode,
6570 virtualKey.hitLeft, virtualKey.hitTop,
6571 virtualKey.hitRight, virtualKey.hitBottom);
6572#endif
6573
6574 if (virtualKey.isHit(x, y)) {
6575 return & virtualKey;
6576 }
6577 }
6578
Yi Kong9b14ac62018-07-17 13:48:38 -07006579 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006580}
6581
Michael Wright842500e2015-03-13 17:32:02 -07006582void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6583 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6584 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006585
Michael Wright842500e2015-03-13 17:32:02 -07006586 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006587
6588 if (currentPointerCount == 0) {
6589 // No pointers to assign.
6590 return;
6591 }
6592
6593 if (lastPointerCount == 0) {
6594 // All pointers are new.
6595 for (uint32_t i = 0; i < currentPointerCount; i++) {
6596 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006597 current->rawPointerData.pointers[i].id = id;
6598 current->rawPointerData.idToIndex[id] = i;
6599 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006600 }
6601 return;
6602 }
6603
6604 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006605 && current->rawPointerData.pointers[0].toolType
6606 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006607 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006608 uint32_t id = last->rawPointerData.pointers[0].id;
6609 current->rawPointerData.pointers[0].id = id;
6610 current->rawPointerData.idToIndex[id] = 0;
6611 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006612 return;
6613 }
6614
6615 // General case.
6616 // We build a heap of squared euclidean distances between current and last pointers
6617 // associated with the current and last pointer indices. Then, we find the best
6618 // match (by distance) for each current pointer.
6619 // The pointers must have the same tool type but it is possible for them to
6620 // transition from hovering to touching or vice-versa while retaining the same id.
6621 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6622
6623 uint32_t heapSize = 0;
6624 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6625 currentPointerIndex++) {
6626 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6627 lastPointerIndex++) {
6628 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006629 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006630 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006631 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006632 if (currentPointer.toolType == lastPointer.toolType) {
6633 int64_t deltaX = currentPointer.x - lastPointer.x;
6634 int64_t deltaY = currentPointer.y - lastPointer.y;
6635
6636 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6637
6638 // Insert new element into the heap (sift up).
6639 heap[heapSize].currentPointerIndex = currentPointerIndex;
6640 heap[heapSize].lastPointerIndex = lastPointerIndex;
6641 heap[heapSize].distance = distance;
6642 heapSize += 1;
6643 }
6644 }
6645 }
6646
6647 // Heapify
6648 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6649 startIndex -= 1;
6650 for (uint32_t parentIndex = startIndex; ;) {
6651 uint32_t childIndex = parentIndex * 2 + 1;
6652 if (childIndex >= heapSize) {
6653 break;
6654 }
6655
6656 if (childIndex + 1 < heapSize
6657 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6658 childIndex += 1;
6659 }
6660
6661 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6662 break;
6663 }
6664
6665 swap(heap[parentIndex], heap[childIndex]);
6666 parentIndex = childIndex;
6667 }
6668 }
6669
6670#if DEBUG_POINTER_ASSIGNMENT
6671 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6672 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006673 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006674 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6675 heap[i].distance);
6676 }
6677#endif
6678
6679 // Pull matches out by increasing order of distance.
6680 // To avoid reassigning pointers that have already been matched, the loop keeps track
6681 // of which last and current pointers have been matched using the matchedXXXBits variables.
6682 // It also tracks the used pointer id bits.
6683 BitSet32 matchedLastBits(0);
6684 BitSet32 matchedCurrentBits(0);
6685 BitSet32 usedIdBits(0);
6686 bool first = true;
6687 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6688 while (heapSize > 0) {
6689 if (first) {
6690 // The first time through the loop, we just consume the root element of
6691 // the heap (the one with smallest distance).
6692 first = false;
6693 } else {
6694 // Previous iterations consumed the root element of the heap.
6695 // Pop root element off of the heap (sift down).
6696 heap[0] = heap[heapSize];
6697 for (uint32_t parentIndex = 0; ;) {
6698 uint32_t childIndex = parentIndex * 2 + 1;
6699 if (childIndex >= heapSize) {
6700 break;
6701 }
6702
6703 if (childIndex + 1 < heapSize
6704 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6705 childIndex += 1;
6706 }
6707
6708 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6709 break;
6710 }
6711
6712 swap(heap[parentIndex], heap[childIndex]);
6713 parentIndex = childIndex;
6714 }
6715
6716#if DEBUG_POINTER_ASSIGNMENT
6717 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6718 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006719 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006720 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6721 heap[i].distance);
6722 }
6723#endif
6724 }
6725
6726 heapSize -= 1;
6727
6728 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6729 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6730
6731 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6732 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6733
6734 matchedCurrentBits.markBit(currentPointerIndex);
6735 matchedLastBits.markBit(lastPointerIndex);
6736
Michael Wright842500e2015-03-13 17:32:02 -07006737 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6738 current->rawPointerData.pointers[currentPointerIndex].id = id;
6739 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6740 current->rawPointerData.markIdBit(id,
6741 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006742 usedIdBits.markBit(id);
6743
6744#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006745 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6746 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006747 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6748#endif
6749 break;
6750 }
6751 }
6752
6753 // Assign fresh ids to pointers that were not matched in the process.
6754 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6755 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6756 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6757
Michael Wright842500e2015-03-13 17:32:02 -07006758 current->rawPointerData.pointers[currentPointerIndex].id = id;
6759 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6760 current->rawPointerData.markIdBit(id,
6761 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006762
6763#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006764 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006765#endif
6766 }
6767}
6768
6769int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6770 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6771 return AKEY_STATE_VIRTUAL;
6772 }
6773
6774 size_t numVirtualKeys = mVirtualKeys.size();
6775 for (size_t i = 0; i < numVirtualKeys; i++) {
6776 const VirtualKey& virtualKey = mVirtualKeys[i];
6777 if (virtualKey.keyCode == keyCode) {
6778 return AKEY_STATE_UP;
6779 }
6780 }
6781
6782 return AKEY_STATE_UNKNOWN;
6783}
6784
6785int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6786 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6787 return AKEY_STATE_VIRTUAL;
6788 }
6789
6790 size_t numVirtualKeys = mVirtualKeys.size();
6791 for (size_t i = 0; i < numVirtualKeys; i++) {
6792 const VirtualKey& virtualKey = mVirtualKeys[i];
6793 if (virtualKey.scanCode == scanCode) {
6794 return AKEY_STATE_UP;
6795 }
6796 }
6797
6798 return AKEY_STATE_UNKNOWN;
6799}
6800
6801bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6802 const int32_t* keyCodes, uint8_t* outFlags) {
6803 size_t numVirtualKeys = mVirtualKeys.size();
6804 for (size_t i = 0; i < numVirtualKeys; i++) {
6805 const VirtualKey& virtualKey = mVirtualKeys[i];
6806
6807 for (size_t i = 0; i < numCodes; i++) {
6808 if (virtualKey.keyCode == keyCodes[i]) {
6809 outFlags[i] = 1;
6810 }
6811 }
6812 }
6813
6814 return true;
6815}
6816
6817
6818// --- SingleTouchInputMapper ---
6819
6820SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6821 TouchInputMapper(device) {
6822}
6823
6824SingleTouchInputMapper::~SingleTouchInputMapper() {
6825}
6826
6827void SingleTouchInputMapper::reset(nsecs_t when) {
6828 mSingleTouchMotionAccumulator.reset(getDevice());
6829
6830 TouchInputMapper::reset(when);
6831}
6832
6833void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6834 TouchInputMapper::process(rawEvent);
6835
6836 mSingleTouchMotionAccumulator.process(rawEvent);
6837}
6838
Michael Wright842500e2015-03-13 17:32:02 -07006839void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006840 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006841 outState->rawPointerData.pointerCount = 1;
6842 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006843
6844 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6845 && (mTouchButtonAccumulator.isHovering()
6846 || (mRawPointerAxes.pressure.valid
6847 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006848 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006849
Michael Wright842500e2015-03-13 17:32:02 -07006850 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006851 outPointer.id = 0;
6852 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6853 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6854 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6855 outPointer.touchMajor = 0;
6856 outPointer.touchMinor = 0;
6857 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6858 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6859 outPointer.orientation = 0;
6860 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6861 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6862 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6863 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6864 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6865 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6866 }
6867 outPointer.isHovering = isHovering;
6868 }
6869}
6870
6871void SingleTouchInputMapper::configureRawPointerAxes() {
6872 TouchInputMapper::configureRawPointerAxes();
6873
6874 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6875 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6876 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6877 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6878 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6879 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6880 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6881}
6882
6883bool SingleTouchInputMapper::hasStylus() const {
6884 return mTouchButtonAccumulator.hasStylus();
6885}
6886
6887
6888// --- MultiTouchInputMapper ---
6889
6890MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6891 TouchInputMapper(device) {
6892}
6893
6894MultiTouchInputMapper::~MultiTouchInputMapper() {
6895}
6896
6897void MultiTouchInputMapper::reset(nsecs_t when) {
6898 mMultiTouchMotionAccumulator.reset(getDevice());
6899
6900 mPointerIdBits.clear();
6901
6902 TouchInputMapper::reset(when);
6903}
6904
6905void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6906 TouchInputMapper::process(rawEvent);
6907
6908 mMultiTouchMotionAccumulator.process(rawEvent);
6909}
6910
Michael Wright842500e2015-03-13 17:32:02 -07006911void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006912 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6913 size_t outCount = 0;
6914 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006915 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006916
6917 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6918 const MultiTouchMotionAccumulator::Slot* inSlot =
6919 mMultiTouchMotionAccumulator.getSlot(inIndex);
6920 if (!inSlot->isInUse()) {
6921 continue;
6922 }
6923
6924 if (outCount >= MAX_POINTERS) {
6925#if DEBUG_POINTERS
6926 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6927 "ignoring the rest.",
6928 getDeviceName().string(), MAX_POINTERS);
6929#endif
6930 break; // too many fingers!
6931 }
6932
Michael Wright842500e2015-03-13 17:32:02 -07006933 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006934 outPointer.x = inSlot->getX();
6935 outPointer.y = inSlot->getY();
6936 outPointer.pressure = inSlot->getPressure();
6937 outPointer.touchMajor = inSlot->getTouchMajor();
6938 outPointer.touchMinor = inSlot->getTouchMinor();
6939 outPointer.toolMajor = inSlot->getToolMajor();
6940 outPointer.toolMinor = inSlot->getToolMinor();
6941 outPointer.orientation = inSlot->getOrientation();
6942 outPointer.distance = inSlot->getDistance();
6943 outPointer.tiltX = 0;
6944 outPointer.tiltY = 0;
6945
6946 outPointer.toolType = inSlot->getToolType();
6947 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6948 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6949 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6950 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6951 }
6952 }
6953
6954 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6955 && (mTouchButtonAccumulator.isHovering()
6956 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6957 outPointer.isHovering = isHovering;
6958
6959 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006960 if (mHavePointerIds) {
6961 int32_t trackingId = inSlot->getTrackingId();
6962 int32_t id = -1;
6963 if (trackingId >= 0) {
6964 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6965 uint32_t n = idBits.clearFirstMarkedBit();
6966 if (mPointerTrackingIdMap[n] == trackingId) {
6967 id = n;
6968 }
6969 }
6970
6971 if (id < 0 && !mPointerIdBits.isFull()) {
6972 id = mPointerIdBits.markFirstUnmarkedBit();
6973 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006974 }
Michael Wright842500e2015-03-13 17:32:02 -07006975 }
gaoshang1a632de2016-08-24 10:23:50 +08006976 if (id < 0) {
6977 mHavePointerIds = false;
6978 outState->rawPointerData.clearIdBits();
6979 newPointerIdBits.clear();
6980 } else {
6981 outPointer.id = id;
6982 outState->rawPointerData.idToIndex[id] = outCount;
6983 outState->rawPointerData.markIdBit(id, isHovering);
6984 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006985 }
Michael Wright842500e2015-03-13 17:32:02 -07006986 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006987 outCount += 1;
6988 }
6989
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006990 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006991 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006992 mPointerIdBits = newPointerIdBits;
6993
6994 mMultiTouchMotionAccumulator.finishSync();
6995}
6996
6997void MultiTouchInputMapper::configureRawPointerAxes() {
6998 TouchInputMapper::configureRawPointerAxes();
6999
7000 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7001 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7002 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7003 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7004 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7005 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7006 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7007 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7008 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7009 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7010 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7011
7012 if (mRawPointerAxes.trackingId.valid
7013 && mRawPointerAxes.slot.valid
7014 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7015 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7016 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007017 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7018 "only supports a maximum of %zu slots at this time.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007019 getDeviceName().string(), slotCount, MAX_SLOTS);
7020 slotCount = MAX_SLOTS;
7021 }
7022 mMultiTouchMotionAccumulator.configure(getDevice(),
7023 slotCount, true /*usingSlotsProtocol*/);
7024 } else {
7025 mMultiTouchMotionAccumulator.configure(getDevice(),
7026 MAX_POINTERS, false /*usingSlotsProtocol*/);
7027 }
7028}
7029
7030bool MultiTouchInputMapper::hasStylus() const {
7031 return mMultiTouchMotionAccumulator.hasStylus()
7032 || mTouchButtonAccumulator.hasStylus();
7033}
7034
Michael Wright842500e2015-03-13 17:32:02 -07007035// --- ExternalStylusInputMapper
7036
7037ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7038 InputMapper(device) {
7039
7040}
7041
7042uint32_t ExternalStylusInputMapper::getSources() {
7043 return AINPUT_SOURCE_STYLUS;
7044}
7045
7046void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7047 InputMapper::populateDeviceInfo(info);
7048 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7049 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7050}
7051
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007052void ExternalStylusInputMapper::dump(std::string& dump) {
7053 dump += INDENT2 "External Stylus Input Mapper:\n";
7054 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007055 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007056 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007057 dumpStylusState(dump, mStylusState);
7058}
7059
7060void ExternalStylusInputMapper::configure(nsecs_t when,
7061 const InputReaderConfiguration* config, uint32_t changes) {
7062 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7063 mTouchButtonAccumulator.configure(getDevice());
7064}
7065
7066void ExternalStylusInputMapper::reset(nsecs_t when) {
7067 InputDevice* device = getDevice();
7068 mSingleTouchMotionAccumulator.reset(device);
7069 mTouchButtonAccumulator.reset(device);
7070 InputMapper::reset(when);
7071}
7072
7073void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7074 mSingleTouchMotionAccumulator.process(rawEvent);
7075 mTouchButtonAccumulator.process(rawEvent);
7076
7077 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7078 sync(rawEvent->when);
7079 }
7080}
7081
7082void ExternalStylusInputMapper::sync(nsecs_t when) {
7083 mStylusState.clear();
7084
7085 mStylusState.when = when;
7086
Michael Wright45ccacf2015-04-21 19:01:58 +01007087 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7088 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7089 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7090 }
7091
Michael Wright842500e2015-03-13 17:32:02 -07007092 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7093 if (mRawPressureAxis.valid) {
7094 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7095 } else if (mTouchButtonAccumulator.isToolActive()) {
7096 mStylusState.pressure = 1.0f;
7097 } else {
7098 mStylusState.pressure = 0.0f;
7099 }
7100
7101 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007102
7103 mContext->dispatchExternalStylusState(mStylusState);
7104}
7105
Michael Wrightd02c5b62014-02-10 15:10:22 -08007106
7107// --- JoystickInputMapper ---
7108
7109JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7110 InputMapper(device) {
7111}
7112
7113JoystickInputMapper::~JoystickInputMapper() {
7114}
7115
7116uint32_t JoystickInputMapper::getSources() {
7117 return AINPUT_SOURCE_JOYSTICK;
7118}
7119
7120void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7121 InputMapper::populateDeviceInfo(info);
7122
7123 for (size_t i = 0; i < mAxes.size(); i++) {
7124 const Axis& axis = mAxes.valueAt(i);
7125 addMotionRange(axis.axisInfo.axis, axis, info);
7126
7127 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7128 addMotionRange(axis.axisInfo.highAxis, axis, info);
7129
7130 }
7131 }
7132}
7133
7134void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7135 InputDeviceInfo* info) {
7136 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7137 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7138 /* In order to ease the transition for developers from using the old axes
7139 * to the newer, more semantically correct axes, we'll continue to register
7140 * the old axes as duplicates of their corresponding new ones. */
7141 int32_t compatAxis = getCompatAxis(axisId);
7142 if (compatAxis >= 0) {
7143 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7144 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7145 }
7146}
7147
7148/* A mapping from axes the joystick actually has to the axes that should be
7149 * artificially created for compatibility purposes.
7150 * Returns -1 if no compatibility axis is needed. */
7151int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7152 switch(axis) {
7153 case AMOTION_EVENT_AXIS_LTRIGGER:
7154 return AMOTION_EVENT_AXIS_BRAKE;
7155 case AMOTION_EVENT_AXIS_RTRIGGER:
7156 return AMOTION_EVENT_AXIS_GAS;
7157 }
7158 return -1;
7159}
7160
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007161void JoystickInputMapper::dump(std::string& dump) {
7162 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007163
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007164 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007165 size_t numAxes = mAxes.size();
7166 for (size_t i = 0; i < numAxes; i++) {
7167 const Axis& axis = mAxes.valueAt(i);
7168 const char* label = getAxisLabel(axis.axisInfo.axis);
7169 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007170 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007171 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007172 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007173 }
7174 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7175 label = getAxisLabel(axis.axisInfo.highAxis);
7176 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007177 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007178 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007179 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007180 axis.axisInfo.splitValue);
7181 }
7182 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007183 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007184 }
7185
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007186 dump += StringPrintf(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007187 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007188 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007189 "highScale=%0.5f, highOffset=%0.5f\n",
7190 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007191 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007192 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7193 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7194 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7195 }
7196}
7197
7198void JoystickInputMapper::configure(nsecs_t when,
7199 const InputReaderConfiguration* config, uint32_t changes) {
7200 InputMapper::configure(when, config, changes);
7201
7202 if (!changes) { // first time only
7203 // Collect all axes.
7204 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7205 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7206 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7207 continue; // axis must be claimed by a different device
7208 }
7209
7210 RawAbsoluteAxisInfo rawAxisInfo;
7211 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7212 if (rawAxisInfo.valid) {
7213 // Map axis.
7214 AxisInfo axisInfo;
7215 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7216 if (!explicitlyMapped) {
7217 // Axis is not explicitly mapped, will choose a generic axis later.
7218 axisInfo.mode = AxisInfo::MODE_NORMAL;
7219 axisInfo.axis = -1;
7220 }
7221
7222 // Apply flat override.
7223 int32_t rawFlat = axisInfo.flatOverride < 0
7224 ? rawAxisInfo.flat : axisInfo.flatOverride;
7225
7226 // Calculate scaling factors and limits.
7227 Axis axis;
7228 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7229 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7230 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7231 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7232 scale, 0.0f, highScale, 0.0f,
7233 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7234 rawAxisInfo.resolution * scale);
7235 } else if (isCenteredAxis(axisInfo.axis)) {
7236 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7237 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7238 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7239 scale, offset, scale, offset,
7240 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7241 rawAxisInfo.resolution * scale);
7242 } else {
7243 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7244 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7245 scale, 0.0f, scale, 0.0f,
7246 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7247 rawAxisInfo.resolution * scale);
7248 }
7249
7250 // To eliminate noise while the joystick is at rest, filter out small variations
7251 // in axis values up front.
7252 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7253
7254 mAxes.add(abs, axis);
7255 }
7256 }
7257
7258 // If there are too many axes, start dropping them.
7259 // Prefer to keep explicitly mapped axes.
7260 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007261 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08007262 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
7263 pruneAxes(true);
7264 pruneAxes(false);
7265 }
7266
7267 // Assign generic axis ids to remaining axes.
7268 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7269 size_t numAxes = mAxes.size();
7270 for (size_t i = 0; i < numAxes; i++) {
7271 Axis& axis = mAxes.editValueAt(i);
7272 if (axis.axisInfo.axis < 0) {
7273 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7274 && haveAxis(nextGenericAxisId)) {
7275 nextGenericAxisId += 1;
7276 }
7277
7278 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7279 axis.axisInfo.axis = nextGenericAxisId;
7280 nextGenericAxisId += 1;
7281 } else {
7282 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7283 "have already been assigned to other axes.",
7284 getDeviceName().string(), mAxes.keyAt(i));
7285 mAxes.removeItemsAt(i--);
7286 numAxes -= 1;
7287 }
7288 }
7289 }
7290 }
7291}
7292
7293bool JoystickInputMapper::haveAxis(int32_t axisId) {
7294 size_t numAxes = mAxes.size();
7295 for (size_t i = 0; i < numAxes; i++) {
7296 const Axis& axis = mAxes.valueAt(i);
7297 if (axis.axisInfo.axis == axisId
7298 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7299 && axis.axisInfo.highAxis == axisId)) {
7300 return true;
7301 }
7302 }
7303 return false;
7304}
7305
7306void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7307 size_t i = mAxes.size();
7308 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7309 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7310 continue;
7311 }
7312 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
7313 getDeviceName().string(), mAxes.keyAt(i));
7314 mAxes.removeItemsAt(i);
7315 }
7316}
7317
7318bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7319 switch (axis) {
7320 case AMOTION_EVENT_AXIS_X:
7321 case AMOTION_EVENT_AXIS_Y:
7322 case AMOTION_EVENT_AXIS_Z:
7323 case AMOTION_EVENT_AXIS_RX:
7324 case AMOTION_EVENT_AXIS_RY:
7325 case AMOTION_EVENT_AXIS_RZ:
7326 case AMOTION_EVENT_AXIS_HAT_X:
7327 case AMOTION_EVENT_AXIS_HAT_Y:
7328 case AMOTION_EVENT_AXIS_ORIENTATION:
7329 case AMOTION_EVENT_AXIS_RUDDER:
7330 case AMOTION_EVENT_AXIS_WHEEL:
7331 return true;
7332 default:
7333 return false;
7334 }
7335}
7336
7337void JoystickInputMapper::reset(nsecs_t when) {
7338 // Recenter all axes.
7339 size_t numAxes = mAxes.size();
7340 for (size_t i = 0; i < numAxes; i++) {
7341 Axis& axis = mAxes.editValueAt(i);
7342 axis.resetValue();
7343 }
7344
7345 InputMapper::reset(when);
7346}
7347
7348void JoystickInputMapper::process(const RawEvent* rawEvent) {
7349 switch (rawEvent->type) {
7350 case EV_ABS: {
7351 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7352 if (index >= 0) {
7353 Axis& axis = mAxes.editValueAt(index);
7354 float newValue, highNewValue;
7355 switch (axis.axisInfo.mode) {
7356 case AxisInfo::MODE_INVERT:
7357 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7358 * axis.scale + axis.offset;
7359 highNewValue = 0.0f;
7360 break;
7361 case AxisInfo::MODE_SPLIT:
7362 if (rawEvent->value < axis.axisInfo.splitValue) {
7363 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7364 * axis.scale + axis.offset;
7365 highNewValue = 0.0f;
7366 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7367 newValue = 0.0f;
7368 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7369 * axis.highScale + axis.highOffset;
7370 } else {
7371 newValue = 0.0f;
7372 highNewValue = 0.0f;
7373 }
7374 break;
7375 default:
7376 newValue = rawEvent->value * axis.scale + axis.offset;
7377 highNewValue = 0.0f;
7378 break;
7379 }
7380 axis.newValue = newValue;
7381 axis.highNewValue = highNewValue;
7382 }
7383 break;
7384 }
7385
7386 case EV_SYN:
7387 switch (rawEvent->code) {
7388 case SYN_REPORT:
7389 sync(rawEvent->when, false /*force*/);
7390 break;
7391 }
7392 break;
7393 }
7394}
7395
7396void JoystickInputMapper::sync(nsecs_t when, bool force) {
7397 if (!filterAxes(force)) {
7398 return;
7399 }
7400
7401 int32_t metaState = mContext->getGlobalMetaState();
7402 int32_t buttonState = 0;
7403
7404 PointerProperties pointerProperties;
7405 pointerProperties.clear();
7406 pointerProperties.id = 0;
7407 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7408
7409 PointerCoords pointerCoords;
7410 pointerCoords.clear();
7411
7412 size_t numAxes = mAxes.size();
7413 for (size_t i = 0; i < numAxes; i++) {
7414 const Axis& axis = mAxes.valueAt(i);
7415 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7416 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7417 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7418 axis.highCurrentValue);
7419 }
7420 }
7421
7422 // Moving a joystick axis should not wake the device because joysticks can
7423 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7424 // button will likely wake the device.
7425 // TODO: Use the input device configuration to control this behavior more finely.
7426 uint32_t policyFlags = 0;
7427
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007428 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE,
7429 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007430 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007431 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007432 0, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007433 getListener()->notifyMotion(&args);
7434}
7435
7436void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7437 int32_t axis, float value) {
7438 pointerCoords->setAxisValue(axis, value);
7439 /* In order to ease the transition for developers from using the old axes
7440 * to the newer, more semantically correct axes, we'll continue to produce
7441 * values for the old axes as mirrors of the value of their corresponding
7442 * new axes. */
7443 int32_t compatAxis = getCompatAxis(axis);
7444 if (compatAxis >= 0) {
7445 pointerCoords->setAxisValue(compatAxis, value);
7446 }
7447}
7448
7449bool JoystickInputMapper::filterAxes(bool force) {
7450 bool atLeastOneSignificantChange = force;
7451 size_t numAxes = mAxes.size();
7452 for (size_t i = 0; i < numAxes; i++) {
7453 Axis& axis = mAxes.editValueAt(i);
7454 if (force || hasValueChangedSignificantly(axis.filter,
7455 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7456 axis.currentValue = axis.newValue;
7457 atLeastOneSignificantChange = true;
7458 }
7459 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7460 if (force || hasValueChangedSignificantly(axis.filter,
7461 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7462 axis.highCurrentValue = axis.highNewValue;
7463 atLeastOneSignificantChange = true;
7464 }
7465 }
7466 }
7467 return atLeastOneSignificantChange;
7468}
7469
7470bool JoystickInputMapper::hasValueChangedSignificantly(
7471 float filter, float newValue, float currentValue, float min, float max) {
7472 if (newValue != currentValue) {
7473 // Filter out small changes in value unless the value is converging on the axis
7474 // bounds or center point. This is intended to reduce the amount of information
7475 // sent to applications by particularly noisy joysticks (such as PS3).
7476 if (fabs(newValue - currentValue) > filter
7477 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7478 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7479 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7480 return true;
7481 }
7482 }
7483 return false;
7484}
7485
7486bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7487 float filter, float newValue, float currentValue, float thresholdValue) {
7488 float newDistance = fabs(newValue - thresholdValue);
7489 if (newDistance < filter) {
7490 float oldDistance = fabs(currentValue - thresholdValue);
7491 if (newDistance < oldDistance) {
7492 return true;
7493 }
7494 }
7495 return false;
7496}
7497
7498} // namespace android