blob: 592939f2ba6b238f4667fc12801ed190ef7ba1b2 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -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
Jeff Brown46b9ac02010-04-22 18:58:52 -070017#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.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_HACKS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070026
27// Log debug messages about virtual key processing.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_VIRTUAL_KEYS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070029
30// Log debug messages about pointers.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_POINTERS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070032
Jeff Brown5c225b12010-06-16 01:53:36 -070033// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
Jeff Brown96ad3972011-03-09 17:39:48 -080036// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
Jeff Brownefd32662011-03-08 15:13:06 -080039
Jeff Brownb4ff35d2011-01-02 16:37:43 -080040#include "InputReader.h"
41
Jeff Brown46b9ac02010-04-22 18:58:52 -070042#include <cutils/log.h>
Jeff Brown6b53e8d2010-11-10 16:03:06 -080043#include <ui/Keyboard.h>
Jeff Brown90655042010-12-02 13:50:46 -080044#include <ui/VirtualKeyMap.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070045
46#include <stddef.h>
Jeff Brown8d608662010-08-30 03:02:23 -070047#include <stdlib.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070048#include <unistd.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070049#include <errno.h>
50#include <limits.h>
Jeff Brownc5ed5912010-07-14 18:48:53 -070051#include <math.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070052
Jeff Brown8d608662010-08-30 03:02:23 -070053#define INDENT " "
Jeff Brownef3d7e82010-09-30 14:33:04 -070054#define INDENT2 " "
55#define INDENT3 " "
56#define INDENT4 " "
Jeff Brown8d608662010-08-30 03:02:23 -070057
Jeff Brown46b9ac02010-04-22 18:58:52 -070058namespace android {
59
Jeff Brown96ad3972011-03-09 17:39:48 -080060// --- Constants ---
61
62// Quiet time between certain gesture transitions.
63// Time to allow for all fingers or buttons to settle into a stable state before
64// starting a new gesture.
65static const nsecs_t QUIET_INTERVAL = 100 * 1000000; // 100 ms
66
67// The minimum speed that a pointer must travel for us to consider switching the active
68// touch pointer to it during a drag. This threshold is set to avoid switching due
69// to noise from a finger resting on the touch pad (perhaps just pressing it down).
70static const float DRAG_MIN_SWITCH_SPEED = 50.0f; // pixels per second
71
72// Tap gesture delay time.
73// The time between down and up must be less than this to be considered a tap.
74static const nsecs_t TAP_INTERVAL = 100 * 1000000; // 100 ms
75
76// The distance in pixels that the pointer is allowed to move from initial down
77// to up and still be called a tap.
78static const float TAP_SLOP = 5.0f; // 5 pixels
79
80// The transition from INDETERMINATE_MULTITOUCH to SWIPE or FREEFORM gesture mode is made when
81// all of the pointers have traveled this number of pixels from the start point.
82static const float MULTITOUCH_MIN_TRAVEL = 5.0f;
83
84// The transition from INDETERMINATE_MULTITOUCH to SWIPE gesture mode can only occur when the
85// cosine of the angle between the two vectors is greater than or equal to than this value
86// which indicates that the vectors are oriented in the same direction.
87// When the vectors are oriented in the exactly same direction, the cosine is 1.0.
88// (In exactly opposite directions, the cosine is -1.0.)
89static const float SWIPE_TRANSITION_ANGLE_COSINE = 0.5f; // cosine of 45 degrees
90
91
Jeff Brown46b9ac02010-04-22 18:58:52 -070092// --- Static Functions ---
93
94template<typename T>
95inline static T abs(const T& value) {
96 return value < 0 ? - value : value;
97}
98
99template<typename T>
100inline static T min(const T& a, const T& b) {
101 return a < b ? a : b;
102}
103
Jeff Brown5c225b12010-06-16 01:53:36 -0700104template<typename T>
105inline static void swap(T& a, T& b) {
106 T temp = a;
107 a = b;
108 b = temp;
109}
110
Jeff Brown8d608662010-08-30 03:02:23 -0700111inline static float avg(float x, float y) {
112 return (x + y) / 2;
113}
114
115inline static float pythag(float x, float y) {
116 return sqrtf(x * x + y * y);
117}
118
Jeff Brown96ad3972011-03-09 17:39:48 -0800119inline static int32_t distanceSquared(int32_t x1, int32_t y1, int32_t x2, int32_t y2) {
120 int32_t dx = x1 - x2;
121 int32_t dy = y1 - y2;
122 return dx * dx + dy * dy;
123}
124
Jeff Brown517bb4c2011-01-14 19:09:23 -0800125inline static int32_t signExtendNybble(int32_t value) {
126 return value >= 8 ? value - 16 : value;
127}
128
Jeff Brownef3d7e82010-09-30 14:33:04 -0700129static inline const char* toString(bool value) {
130 return value ? "true" : "false";
131}
132
Jeff Brown9626b142011-03-03 02:09:54 -0800133static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
134 const int32_t map[][4], size_t mapSize) {
135 if (orientation != DISPLAY_ORIENTATION_0) {
136 for (size_t i = 0; i < mapSize; i++) {
137 if (value == map[i][0]) {
138 return map[i][orientation];
139 }
140 }
141 }
142 return value;
143}
144
Jeff Brown46b9ac02010-04-22 18:58:52 -0700145static const int32_t keyCodeRotationMap[][4] = {
146 // key codes enumerated counter-clockwise with the original (unrotated) key first
147 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
Jeff Brownfd035822010-06-30 16:10:35 -0700148 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
149 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
150 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
151 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jeff Brown46b9ac02010-04-22 18:58:52 -0700152};
Jeff Brown9626b142011-03-03 02:09:54 -0800153static const size_t keyCodeRotationMapSize =
Jeff Brown46b9ac02010-04-22 18:58:52 -0700154 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
155
156int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Jeff Brown9626b142011-03-03 02:09:54 -0800157 return rotateValueUsingRotationMap(keyCode, orientation,
158 keyCodeRotationMap, keyCodeRotationMapSize);
159}
160
161static const int32_t edgeFlagRotationMap[][4] = {
162 // edge flags enumerated counter-clockwise with the original (unrotated) edge flag first
163 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
164 { AMOTION_EVENT_EDGE_FLAG_BOTTOM, AMOTION_EVENT_EDGE_FLAG_RIGHT,
165 AMOTION_EVENT_EDGE_FLAG_TOP, AMOTION_EVENT_EDGE_FLAG_LEFT },
166 { AMOTION_EVENT_EDGE_FLAG_RIGHT, AMOTION_EVENT_EDGE_FLAG_TOP,
167 AMOTION_EVENT_EDGE_FLAG_LEFT, AMOTION_EVENT_EDGE_FLAG_BOTTOM },
168 { AMOTION_EVENT_EDGE_FLAG_TOP, AMOTION_EVENT_EDGE_FLAG_LEFT,
169 AMOTION_EVENT_EDGE_FLAG_BOTTOM, AMOTION_EVENT_EDGE_FLAG_RIGHT },
170 { AMOTION_EVENT_EDGE_FLAG_LEFT, AMOTION_EVENT_EDGE_FLAG_BOTTOM,
171 AMOTION_EVENT_EDGE_FLAG_RIGHT, AMOTION_EVENT_EDGE_FLAG_TOP },
172};
173static const size_t edgeFlagRotationMapSize =
174 sizeof(edgeFlagRotationMap) / sizeof(edgeFlagRotationMap[0]);
175
176static int32_t rotateEdgeFlag(int32_t edgeFlag, int32_t orientation) {
177 return rotateValueUsingRotationMap(edgeFlag, orientation,
178 edgeFlagRotationMap, edgeFlagRotationMapSize);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700179}
180
Jeff Brown6d0fec22010-07-23 21:28:06 -0700181static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
182 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
183}
184
Jeff Brownefd32662011-03-08 15:13:06 -0800185static uint32_t getButtonStateForScanCode(int32_t scanCode) {
186 // Currently all buttons are mapped to the primary button.
187 switch (scanCode) {
188 case BTN_LEFT:
189 case BTN_RIGHT:
190 case BTN_MIDDLE:
191 case BTN_SIDE:
192 case BTN_EXTRA:
193 case BTN_FORWARD:
194 case BTN_BACK:
195 case BTN_TASK:
196 return BUTTON_STATE_PRIMARY;
197 default:
198 return 0;
199 }
200}
201
202// Returns true if the pointer should be reported as being down given the specified
203// button states.
204static bool isPointerDown(uint32_t buttonState) {
205 return buttonState & BUTTON_STATE_PRIMARY;
206}
207
208static int32_t calculateEdgeFlagsUsingPointerBounds(
209 const sp<PointerControllerInterface>& pointerController, float x, float y) {
210 int32_t edgeFlags = 0;
211 float minX, minY, maxX, maxY;
212 if (pointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
213 if (x <= minX) {
214 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_LEFT;
215 } else if (x >= maxX) {
216 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_RIGHT;
217 }
218 if (y <= minY) {
219 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_TOP;
220 } else if (y >= maxY) {
221 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_BOTTOM;
222 }
223 }
224 return edgeFlags;
225}
226
Jeff Brown46b9ac02010-04-22 18:58:52 -0700227
Jeff Brown46b9ac02010-04-22 18:58:52 -0700228// --- InputReader ---
229
230InputReader::InputReader(const sp<EventHubInterface>& eventHub,
Jeff Brown9c3cda02010-06-15 01:31:58 -0700231 const sp<InputReaderPolicyInterface>& policy,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700232 const sp<InputDispatcherInterface>& dispatcher) :
Jeff Brown6d0fec22010-07-23 21:28:06 -0700233 mEventHub(eventHub), mPolicy(policy), mDispatcher(dispatcher),
Jeff Brownfe508922011-01-18 15:10:10 -0800234 mGlobalMetaState(0), mDisableVirtualKeysTimeout(-1) {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700235 configureExcludedDevices();
Jeff Brown6d0fec22010-07-23 21:28:06 -0700236 updateGlobalMetaState();
237 updateInputConfiguration();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700238}
239
240InputReader::~InputReader() {
241 for (size_t i = 0; i < mDevices.size(); i++) {
242 delete mDevices.valueAt(i);
243 }
244}
245
246void InputReader::loopOnce() {
247 RawEvent rawEvent;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700248 mEventHub->getEvent(& rawEvent);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700249
250#if DEBUG_RAW_EVENTS
Jeff Brown96ad3972011-03-09 17:39:48 -0800251 LOGD("Input event: device=%d type=0x%04x scancode=0x%04x keycode=0x%04x value=0x%04x",
Jeff Brown46b9ac02010-04-22 18:58:52 -0700252 rawEvent.deviceId, rawEvent.type, rawEvent.scanCode, rawEvent.keyCode,
253 rawEvent.value);
254#endif
255
256 process(& rawEvent);
257}
258
259void InputReader::process(const RawEvent* rawEvent) {
260 switch (rawEvent->type) {
261 case EventHubInterface::DEVICE_ADDED:
Jeff Brown7342bb92010-10-01 18:55:43 -0700262 addDevice(rawEvent->deviceId);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700263 break;
264
265 case EventHubInterface::DEVICE_REMOVED:
Jeff Brown7342bb92010-10-01 18:55:43 -0700266 removeDevice(rawEvent->deviceId);
267 break;
268
269 case EventHubInterface::FINISHED_DEVICE_SCAN:
Jeff Brownc3db8582010-10-20 15:33:38 -0700270 handleConfigurationChanged(rawEvent->when);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700271 break;
272
Jeff Brown6d0fec22010-07-23 21:28:06 -0700273 default:
274 consumeEvent(rawEvent);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700275 break;
276 }
277}
278
Jeff Brown7342bb92010-10-01 18:55:43 -0700279void InputReader::addDevice(int32_t deviceId) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700280 String8 name = mEventHub->getDeviceName(deviceId);
281 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
282
283 InputDevice* device = createDevice(deviceId, name, classes);
284 device->configure();
285
Jeff Brown8d608662010-08-30 03:02:23 -0700286 if (device->isIgnored()) {
Jeff Brown90655042010-12-02 13:50:46 -0800287 LOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, name.string());
Jeff Brown8d608662010-08-30 03:02:23 -0700288 } else {
Jeff Brown90655042010-12-02 13:50:46 -0800289 LOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, name.string(),
Jeff Brownef3d7e82010-09-30 14:33:04 -0700290 device->getSources());
Jeff Brown8d608662010-08-30 03:02:23 -0700291 }
292
Jeff Brown6d0fec22010-07-23 21:28:06 -0700293 bool added = false;
294 { // acquire device registry writer lock
295 RWLock::AutoWLock _wl(mDeviceRegistryLock);
296
297 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
298 if (deviceIndex < 0) {
299 mDevices.add(deviceId, device);
300 added = true;
301 }
302 } // release device registry writer lock
303
304 if (! added) {
305 LOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
306 delete device;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700307 return;
308 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700309}
310
Jeff Brown7342bb92010-10-01 18:55:43 -0700311void InputReader::removeDevice(int32_t deviceId) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700312 bool removed = false;
313 InputDevice* device = NULL;
314 { // acquire device registry writer lock
315 RWLock::AutoWLock _wl(mDeviceRegistryLock);
316
317 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
318 if (deviceIndex >= 0) {
319 device = mDevices.valueAt(deviceIndex);
320 mDevices.removeItemsAt(deviceIndex, 1);
321 removed = true;
322 }
323 } // release device registry writer lock
324
325 if (! removed) {
326 LOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700327 return;
328 }
329
Jeff Brown6d0fec22010-07-23 21:28:06 -0700330 if (device->isIgnored()) {
Jeff Brown90655042010-12-02 13:50:46 -0800331 LOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Jeff Brown6d0fec22010-07-23 21:28:06 -0700332 device->getId(), device->getName().string());
333 } else {
Jeff Brown90655042010-12-02 13:50:46 -0800334 LOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Jeff Brown6d0fec22010-07-23 21:28:06 -0700335 device->getId(), device->getName().string(), device->getSources());
336 }
337
Jeff Brown8d608662010-08-30 03:02:23 -0700338 device->reset();
339
Jeff Brown6d0fec22010-07-23 21:28:06 -0700340 delete device;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700341}
342
Jeff Brown6d0fec22010-07-23 21:28:06 -0700343InputDevice* InputReader::createDevice(int32_t deviceId, const String8& name, uint32_t classes) {
344 InputDevice* device = new InputDevice(this, deviceId, name);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700345
Jeff Brown56194eb2011-03-02 19:23:13 -0800346 // External devices.
347 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
348 device->setExternal(true);
349 }
350
Jeff Brown6d0fec22010-07-23 21:28:06 -0700351 // Switch-like devices.
352 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
353 device->addMapper(new SwitchInputMapper(device));
354 }
355
356 // Keyboard-like devices.
Jeff Brownefd32662011-03-08 15:13:06 -0800357 uint32_t keyboardSource = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700358 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
359 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800360 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700361 }
362 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
363 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
364 }
365 if (classes & INPUT_DEVICE_CLASS_DPAD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800366 keyboardSource |= AINPUT_SOURCE_DPAD;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700367 }
Jeff Browncb1404e2011-01-15 18:14:15 -0800368 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800369 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
Jeff Browncb1404e2011-01-15 18:14:15 -0800370 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700371
Jeff Brownefd32662011-03-08 15:13:06 -0800372 if (keyboardSource != 0) {
373 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700374 }
375
Jeff Brown83c09682010-12-23 17:50:18 -0800376 // Cursor-like devices.
377 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
378 device->addMapper(new CursorInputMapper(device));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700379 }
380
Jeff Brown58a2da82011-01-25 16:02:22 -0800381 // Touchscreens and touchpad devices.
382 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800383 device->addMapper(new MultiTouchInputMapper(device));
Jeff Brown58a2da82011-01-25 16:02:22 -0800384 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800385 device->addMapper(new SingleTouchInputMapper(device));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700386 }
387
Jeff Browncb1404e2011-01-15 18:14:15 -0800388 // Joystick-like devices.
389 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
390 device->addMapper(new JoystickInputMapper(device));
391 }
392
Jeff Brown6d0fec22010-07-23 21:28:06 -0700393 return device;
394}
395
396void InputReader::consumeEvent(const RawEvent* rawEvent) {
397 int32_t deviceId = rawEvent->deviceId;
398
399 { // acquire device registry reader lock
400 RWLock::AutoRLock _rl(mDeviceRegistryLock);
401
402 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
403 if (deviceIndex < 0) {
404 LOGW("Discarding event for unknown deviceId %d.", deviceId);
405 return;
406 }
407
408 InputDevice* device = mDevices.valueAt(deviceIndex);
409 if (device->isIgnored()) {
410 //LOGD("Discarding event for ignored deviceId %d.", deviceId);
411 return;
412 }
413
414 device->process(rawEvent);
415 } // release device registry reader lock
416}
417
Jeff Brownc3db8582010-10-20 15:33:38 -0700418void InputReader::handleConfigurationChanged(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700419 // Reset global meta state because it depends on the list of all configured devices.
420 updateGlobalMetaState();
421
422 // Update input configuration.
423 updateInputConfiguration();
424
425 // Enqueue configuration changed.
426 mDispatcher->notifyConfigurationChanged(when);
427}
428
429void InputReader::configureExcludedDevices() {
430 Vector<String8> excludedDeviceNames;
431 mPolicy->getExcludedDeviceNames(excludedDeviceNames);
432
433 for (size_t i = 0; i < excludedDeviceNames.size(); i++) {
434 mEventHub->addExcludedDevice(excludedDeviceNames[i]);
435 }
436}
437
438void InputReader::updateGlobalMetaState() {
439 { // acquire state lock
440 AutoMutex _l(mStateLock);
441
442 mGlobalMetaState = 0;
443
444 { // acquire device registry reader lock
445 RWLock::AutoRLock _rl(mDeviceRegistryLock);
446
447 for (size_t i = 0; i < mDevices.size(); i++) {
448 InputDevice* device = mDevices.valueAt(i);
449 mGlobalMetaState |= device->getMetaState();
450 }
451 } // release device registry reader lock
452 } // release state lock
453}
454
455int32_t InputReader::getGlobalMetaState() {
456 { // acquire state lock
457 AutoMutex _l(mStateLock);
458
459 return mGlobalMetaState;
460 } // release state lock
461}
462
463void InputReader::updateInputConfiguration() {
464 { // acquire state lock
465 AutoMutex _l(mStateLock);
466
467 int32_t touchScreenConfig = InputConfiguration::TOUCHSCREEN_NOTOUCH;
468 int32_t keyboardConfig = InputConfiguration::KEYBOARD_NOKEYS;
469 int32_t navigationConfig = InputConfiguration::NAVIGATION_NONAV;
470 { // acquire device registry reader lock
471 RWLock::AutoRLock _rl(mDeviceRegistryLock);
472
473 InputDeviceInfo deviceInfo;
474 for (size_t i = 0; i < mDevices.size(); i++) {
475 InputDevice* device = mDevices.valueAt(i);
476 device->getDeviceInfo(& deviceInfo);
477 uint32_t sources = deviceInfo.getSources();
478
479 if ((sources & AINPUT_SOURCE_TOUCHSCREEN) == AINPUT_SOURCE_TOUCHSCREEN) {
480 touchScreenConfig = InputConfiguration::TOUCHSCREEN_FINGER;
481 }
482 if ((sources & AINPUT_SOURCE_TRACKBALL) == AINPUT_SOURCE_TRACKBALL) {
483 navigationConfig = InputConfiguration::NAVIGATION_TRACKBALL;
484 } else if ((sources & AINPUT_SOURCE_DPAD) == AINPUT_SOURCE_DPAD) {
485 navigationConfig = InputConfiguration::NAVIGATION_DPAD;
486 }
487 if (deviceInfo.getKeyboardType() == AINPUT_KEYBOARD_TYPE_ALPHABETIC) {
488 keyboardConfig = InputConfiguration::KEYBOARD_QWERTY;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700489 }
490 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700491 } // release device registry reader lock
Jeff Brown46b9ac02010-04-22 18:58:52 -0700492
Jeff Brown6d0fec22010-07-23 21:28:06 -0700493 mInputConfiguration.touchScreen = touchScreenConfig;
494 mInputConfiguration.keyboard = keyboardConfig;
495 mInputConfiguration.navigation = navigationConfig;
496 } // release state lock
497}
498
Jeff Brownfe508922011-01-18 15:10:10 -0800499void InputReader::disableVirtualKeysUntil(nsecs_t time) {
500 mDisableVirtualKeysTimeout = time;
501}
502
503bool InputReader::shouldDropVirtualKey(nsecs_t now,
504 InputDevice* device, int32_t keyCode, int32_t scanCode) {
505 if (now < mDisableVirtualKeysTimeout) {
506 LOGI("Dropping virtual key from device %s because virtual keys are "
507 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
508 device->getName().string(),
509 (mDisableVirtualKeysTimeout - now) * 0.000001,
510 keyCode, scanCode);
511 return true;
512 } else {
513 return false;
514 }
515}
516
Jeff Brown05dc66a2011-03-02 14:41:58 -0800517void InputReader::fadePointer() {
518 { // acquire device registry reader lock
519 RWLock::AutoRLock _rl(mDeviceRegistryLock);
520
521 for (size_t i = 0; i < mDevices.size(); i++) {
522 InputDevice* device = mDevices.valueAt(i);
523 device->fadePointer();
524 }
525 } // release device registry reader lock
526}
527
Jeff Brown6d0fec22010-07-23 21:28:06 -0700528void InputReader::getInputConfiguration(InputConfiguration* outConfiguration) {
529 { // acquire state lock
530 AutoMutex _l(mStateLock);
531
532 *outConfiguration = mInputConfiguration;
533 } // release state lock
534}
535
536status_t InputReader::getInputDeviceInfo(int32_t deviceId, InputDeviceInfo* outDeviceInfo) {
537 { // acquire device registry reader lock
538 RWLock::AutoRLock _rl(mDeviceRegistryLock);
539
540 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
541 if (deviceIndex < 0) {
542 return NAME_NOT_FOUND;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700543 }
544
Jeff Brown6d0fec22010-07-23 21:28:06 -0700545 InputDevice* device = mDevices.valueAt(deviceIndex);
546 if (device->isIgnored()) {
547 return NAME_NOT_FOUND;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700548 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700549
550 device->getDeviceInfo(outDeviceInfo);
551 return OK;
552 } // release device registy reader lock
553}
554
555void InputReader::getInputDeviceIds(Vector<int32_t>& outDeviceIds) {
556 outDeviceIds.clear();
557
558 { // acquire device registry reader lock
559 RWLock::AutoRLock _rl(mDeviceRegistryLock);
560
561 size_t numDevices = mDevices.size();
562 for (size_t i = 0; i < numDevices; i++) {
563 InputDevice* device = mDevices.valueAt(i);
564 if (! device->isIgnored()) {
565 outDeviceIds.add(device->getId());
566 }
567 }
568 } // release device registy reader lock
569}
570
571int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
572 int32_t keyCode) {
573 return getState(deviceId, sourceMask, keyCode, & InputDevice::getKeyCodeState);
574}
575
576int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
577 int32_t scanCode) {
578 return getState(deviceId, sourceMask, scanCode, & InputDevice::getScanCodeState);
579}
580
581int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
582 return getState(deviceId, sourceMask, switchCode, & InputDevice::getSwitchState);
583}
584
585int32_t InputReader::getState(int32_t deviceId, uint32_t sourceMask, int32_t code,
586 GetStateFunc getStateFunc) {
587 { // acquire device registry reader lock
588 RWLock::AutoRLock _rl(mDeviceRegistryLock);
589
590 int32_t result = AKEY_STATE_UNKNOWN;
591 if (deviceId >= 0) {
592 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
593 if (deviceIndex >= 0) {
594 InputDevice* device = mDevices.valueAt(deviceIndex);
595 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
596 result = (device->*getStateFunc)(sourceMask, code);
597 }
598 }
599 } else {
600 size_t numDevices = mDevices.size();
601 for (size_t i = 0; i < numDevices; i++) {
602 InputDevice* device = mDevices.valueAt(i);
603 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
604 result = (device->*getStateFunc)(sourceMask, code);
605 if (result >= AKEY_STATE_DOWN) {
606 return result;
607 }
608 }
609 }
610 }
611 return result;
612 } // release device registy reader lock
613}
614
615bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
616 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
617 memset(outFlags, 0, numCodes);
618 return markSupportedKeyCodes(deviceId, sourceMask, numCodes, keyCodes, outFlags);
619}
620
621bool InputReader::markSupportedKeyCodes(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
622 const int32_t* keyCodes, uint8_t* outFlags) {
623 { // acquire device registry reader lock
624 RWLock::AutoRLock _rl(mDeviceRegistryLock);
625 bool result = false;
626 if (deviceId >= 0) {
627 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
628 if (deviceIndex >= 0) {
629 InputDevice* device = mDevices.valueAt(deviceIndex);
630 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
631 result = device->markSupportedKeyCodes(sourceMask,
632 numCodes, keyCodes, outFlags);
633 }
634 }
635 } else {
636 size_t numDevices = mDevices.size();
637 for (size_t i = 0; i < numDevices; i++) {
638 InputDevice* device = mDevices.valueAt(i);
639 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
640 result |= device->markSupportedKeyCodes(sourceMask,
641 numCodes, keyCodes, outFlags);
642 }
643 }
644 }
645 return result;
646 } // release device registy reader lock
647}
648
Jeff Brownb88102f2010-09-08 11:49:43 -0700649void InputReader::dump(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -0700650 mEventHub->dump(dump);
651 dump.append("\n");
652
653 dump.append("Input Reader State:\n");
654
Jeff Brownef3d7e82010-09-30 14:33:04 -0700655 { // acquire device registry reader lock
656 RWLock::AutoRLock _rl(mDeviceRegistryLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700657
Jeff Brownef3d7e82010-09-30 14:33:04 -0700658 for (size_t i = 0; i < mDevices.size(); i++) {
659 mDevices.valueAt(i)->dump(dump);
Jeff Brownb88102f2010-09-08 11:49:43 -0700660 }
Jeff Brownef3d7e82010-09-30 14:33:04 -0700661 } // release device registy reader lock
Jeff Brownb88102f2010-09-08 11:49:43 -0700662}
663
Jeff Brown6d0fec22010-07-23 21:28:06 -0700664
665// --- InputReaderThread ---
666
667InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
668 Thread(/*canCallJava*/ true), mReader(reader) {
669}
670
671InputReaderThread::~InputReaderThread() {
672}
673
674bool InputReaderThread::threadLoop() {
675 mReader->loopOnce();
676 return true;
677}
678
679
680// --- InputDevice ---
681
682InputDevice::InputDevice(InputReaderContext* context, int32_t id, const String8& name) :
Jeff Brown56194eb2011-03-02 19:23:13 -0800683 mContext(context), mId(id), mName(name), mSources(0), mIsExternal(false) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700684}
685
686InputDevice::~InputDevice() {
687 size_t numMappers = mMappers.size();
688 for (size_t i = 0; i < numMappers; i++) {
689 delete mMappers[i];
690 }
691 mMappers.clear();
692}
693
Jeff Brownef3d7e82010-09-30 14:33:04 -0700694void InputDevice::dump(String8& dump) {
695 InputDeviceInfo deviceInfo;
696 getDeviceInfo(& deviceInfo);
697
Jeff Brown90655042010-12-02 13:50:46 -0800698 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
Jeff Brownef3d7e82010-09-30 14:33:04 -0700699 deviceInfo.getName().string());
Jeff Brown56194eb2011-03-02 19:23:13 -0800700 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Jeff Brownef3d7e82010-09-30 14:33:04 -0700701 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
702 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Jeff Browncc0c1592011-02-19 05:07:28 -0800703
Jeff Brownefd32662011-03-08 15:13:06 -0800704 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
Jeff Browncc0c1592011-02-19 05:07:28 -0800705 if (!ranges.isEmpty()) {
Jeff Brownef3d7e82010-09-30 14:33:04 -0700706 dump.append(INDENT2 "Motion Ranges:\n");
Jeff Browncc0c1592011-02-19 05:07:28 -0800707 for (size_t i = 0; i < ranges.size(); i++) {
Jeff Brownefd32662011-03-08 15:13:06 -0800708 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
709 const char* label = getAxisLabel(range.axis);
Jeff Browncc0c1592011-02-19 05:07:28 -0800710 char name[32];
711 if (label) {
712 strncpy(name, label, sizeof(name));
713 name[sizeof(name) - 1] = '\0';
714 } else {
Jeff Brownefd32662011-03-08 15:13:06 -0800715 snprintf(name, sizeof(name), "%d", range.axis);
Jeff Browncc0c1592011-02-19 05:07:28 -0800716 }
Jeff Brownefd32662011-03-08 15:13:06 -0800717 dump.appendFormat(INDENT3 "%s: source=0x%08x, "
718 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f\n",
719 name, range.source, range.min, range.max, range.flat, range.fuzz);
Jeff Browncc0c1592011-02-19 05:07:28 -0800720 }
Jeff Brownef3d7e82010-09-30 14:33:04 -0700721 }
722
723 size_t numMappers = mMappers.size();
724 for (size_t i = 0; i < numMappers; i++) {
725 InputMapper* mapper = mMappers[i];
726 mapper->dump(dump);
727 }
728}
729
Jeff Brown6d0fec22010-07-23 21:28:06 -0700730void InputDevice::addMapper(InputMapper* mapper) {
731 mMappers.add(mapper);
732}
733
734void InputDevice::configure() {
Jeff Brown8d608662010-08-30 03:02:23 -0700735 if (! isIgnored()) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800736 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
Jeff Brown8d608662010-08-30 03:02:23 -0700737 }
738
Jeff Brown6d0fec22010-07-23 21:28:06 -0700739 mSources = 0;
740
741 size_t numMappers = mMappers.size();
742 for (size_t i = 0; i < numMappers; i++) {
743 InputMapper* mapper = mMappers[i];
744 mapper->configure();
745 mSources |= mapper->getSources();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700746 }
747}
748
Jeff Brown6d0fec22010-07-23 21:28:06 -0700749void InputDevice::reset() {
750 size_t numMappers = mMappers.size();
751 for (size_t i = 0; i < numMappers; i++) {
752 InputMapper* mapper = mMappers[i];
753 mapper->reset();
754 }
755}
Jeff Brown46b9ac02010-04-22 18:58:52 -0700756
Jeff Brown6d0fec22010-07-23 21:28:06 -0700757void InputDevice::process(const RawEvent* rawEvent) {
758 size_t numMappers = mMappers.size();
759 for (size_t i = 0; i < numMappers; i++) {
760 InputMapper* mapper = mMappers[i];
761 mapper->process(rawEvent);
762 }
763}
Jeff Brown46b9ac02010-04-22 18:58:52 -0700764
Jeff Brown6d0fec22010-07-23 21:28:06 -0700765void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
766 outDeviceInfo->initialize(mId, mName);
767
768 size_t numMappers = mMappers.size();
769 for (size_t i = 0; i < numMappers; i++) {
770 InputMapper* mapper = mMappers[i];
771 mapper->populateDeviceInfo(outDeviceInfo);
772 }
773}
774
775int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
776 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
777}
778
779int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
780 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
781}
782
783int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
784 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
785}
786
787int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
788 int32_t result = AKEY_STATE_UNKNOWN;
789 size_t numMappers = mMappers.size();
790 for (size_t i = 0; i < numMappers; i++) {
791 InputMapper* mapper = mMappers[i];
792 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
793 result = (mapper->*getStateFunc)(sourceMask, code);
794 if (result >= AKEY_STATE_DOWN) {
795 return result;
796 }
797 }
798 }
799 return result;
800}
801
802bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
803 const int32_t* keyCodes, uint8_t* outFlags) {
804 bool result = false;
805 size_t numMappers = mMappers.size();
806 for (size_t i = 0; i < numMappers; i++) {
807 InputMapper* mapper = mMappers[i];
808 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
809 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
810 }
811 }
812 return result;
813}
814
815int32_t InputDevice::getMetaState() {
816 int32_t result = 0;
817 size_t numMappers = mMappers.size();
818 for (size_t i = 0; i < numMappers; i++) {
819 InputMapper* mapper = mMappers[i];
820 result |= mapper->getMetaState();
821 }
822 return result;
823}
824
Jeff Brown05dc66a2011-03-02 14:41:58 -0800825void InputDevice::fadePointer() {
826 size_t numMappers = mMappers.size();
827 for (size_t i = 0; i < numMappers; i++) {
828 InputMapper* mapper = mMappers[i];
829 mapper->fadePointer();
830 }
831}
832
Jeff Brown6d0fec22010-07-23 21:28:06 -0700833
834// --- InputMapper ---
835
836InputMapper::InputMapper(InputDevice* device) :
837 mDevice(device), mContext(device->getContext()) {
838}
839
840InputMapper::~InputMapper() {
841}
842
843void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
844 info->addSource(getSources());
845}
846
Jeff Brownef3d7e82010-09-30 14:33:04 -0700847void InputMapper::dump(String8& dump) {
848}
849
Jeff Brown6d0fec22010-07-23 21:28:06 -0700850void InputMapper::configure() {
851}
852
853void InputMapper::reset() {
854}
855
856int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
857 return AKEY_STATE_UNKNOWN;
858}
859
860int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
861 return AKEY_STATE_UNKNOWN;
862}
863
864int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
865 return AKEY_STATE_UNKNOWN;
866}
867
868bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
869 const int32_t* keyCodes, uint8_t* outFlags) {
870 return false;
871}
872
873int32_t InputMapper::getMetaState() {
874 return 0;
875}
876
Jeff Brown05dc66a2011-03-02 14:41:58 -0800877void InputMapper::fadePointer() {
878}
879
Jeff Browncb1404e2011-01-15 18:14:15 -0800880void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
881 const RawAbsoluteAxisInfo& axis, const char* name) {
882 if (axis.valid) {
883 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d\n",
884 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz);
885 } else {
886 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
887 }
888}
889
Jeff Brown6d0fec22010-07-23 21:28:06 -0700890
891// --- SwitchInputMapper ---
892
893SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
894 InputMapper(device) {
895}
896
897SwitchInputMapper::~SwitchInputMapper() {
898}
899
900uint32_t SwitchInputMapper::getSources() {
Jeff Brown89de57a2011-01-19 18:41:38 -0800901 return AINPUT_SOURCE_SWITCH;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700902}
903
904void SwitchInputMapper::process(const RawEvent* rawEvent) {
905 switch (rawEvent->type) {
906 case EV_SW:
907 processSwitch(rawEvent->when, rawEvent->scanCode, rawEvent->value);
908 break;
909 }
910}
911
912void SwitchInputMapper::processSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue) {
Jeff Brownb6997262010-10-08 22:31:17 -0700913 getDispatcher()->notifySwitch(when, switchCode, switchValue, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -0700914}
915
916int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
917 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
918}
919
920
921// --- KeyboardInputMapper ---
922
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800923KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
Jeff Brownefd32662011-03-08 15:13:06 -0800924 uint32_t source, int32_t keyboardType) :
925 InputMapper(device), mSource(source),
Jeff Brown6d0fec22010-07-23 21:28:06 -0700926 mKeyboardType(keyboardType) {
Jeff Brown6328cdc2010-07-29 18:18:33 -0700927 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -0700928}
929
930KeyboardInputMapper::~KeyboardInputMapper() {
931}
932
Jeff Brown6328cdc2010-07-29 18:18:33 -0700933void KeyboardInputMapper::initializeLocked() {
934 mLocked.metaState = AMETA_NONE;
935 mLocked.downTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700936}
937
938uint32_t KeyboardInputMapper::getSources() {
Jeff Brownefd32662011-03-08 15:13:06 -0800939 return mSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700940}
941
942void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
943 InputMapper::populateDeviceInfo(info);
944
945 info->setKeyboardType(mKeyboardType);
946}
947
Jeff Brownef3d7e82010-09-30 14:33:04 -0700948void KeyboardInputMapper::dump(String8& dump) {
949 { // acquire lock
950 AutoMutex _l(mLock);
951 dump.append(INDENT2 "Keyboard Input Mapper:\n");
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800952 dumpParameters(dump);
Jeff Brownef3d7e82010-09-30 14:33:04 -0700953 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
954 dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mLocked.keyDowns.size());
955 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mLocked.metaState);
956 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
957 } // release lock
958}
959
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800960
961void KeyboardInputMapper::configure() {
962 InputMapper::configure();
963
964 // Configure basic parameters.
965 configureParameters();
Jeff Brown49ed71d2010-12-06 17:13:33 -0800966
967 // Reset LEDs.
968 {
969 AutoMutex _l(mLock);
970 resetLedStateLocked();
971 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800972}
973
974void KeyboardInputMapper::configureParameters() {
975 mParameters.orientationAware = false;
976 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
977 mParameters.orientationAware);
978
979 mParameters.associatedDisplayId = mParameters.orientationAware ? 0 : -1;
980}
981
982void KeyboardInputMapper::dumpParameters(String8& dump) {
983 dump.append(INDENT3 "Parameters:\n");
984 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
985 mParameters.associatedDisplayId);
986 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
987 toString(mParameters.orientationAware));
988}
989
Jeff Brown6d0fec22010-07-23 21:28:06 -0700990void KeyboardInputMapper::reset() {
Jeff Brown6328cdc2010-07-29 18:18:33 -0700991 for (;;) {
992 int32_t keyCode, scanCode;
993 { // acquire lock
994 AutoMutex _l(mLock);
995
996 // Synthesize key up event on reset if keys are currently down.
997 if (mLocked.keyDowns.isEmpty()) {
998 initializeLocked();
Jeff Brown49ed71d2010-12-06 17:13:33 -0800999 resetLedStateLocked();
Jeff Brown6328cdc2010-07-29 18:18:33 -07001000 break; // done
1001 }
1002
1003 const KeyDown& keyDown = mLocked.keyDowns.top();
1004 keyCode = keyDown.keyCode;
1005 scanCode = keyDown.scanCode;
1006 } // release lock
1007
Jeff Brown6d0fec22010-07-23 21:28:06 -07001008 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown6328cdc2010-07-29 18:18:33 -07001009 processKey(when, false, keyCode, scanCode, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001010 }
1011
1012 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001013 getContext()->updateGlobalMetaState();
1014}
1015
1016void KeyboardInputMapper::process(const RawEvent* rawEvent) {
1017 switch (rawEvent->type) {
1018 case EV_KEY: {
1019 int32_t scanCode = rawEvent->scanCode;
1020 if (isKeyboardOrGamepadKey(scanCode)) {
1021 processKey(rawEvent->when, rawEvent->value != 0, rawEvent->keyCode, scanCode,
1022 rawEvent->flags);
1023 }
1024 break;
1025 }
1026 }
1027}
1028
1029bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
1030 return scanCode < BTN_MOUSE
1031 || scanCode >= KEY_OK
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001032 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
Jeff Browncb1404e2011-01-15 18:14:15 -08001033 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001034}
1035
Jeff Brown6328cdc2010-07-29 18:18:33 -07001036void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode,
1037 int32_t scanCode, uint32_t policyFlags) {
1038 int32_t newMetaState;
1039 nsecs_t downTime;
1040 bool metaStateChanged = false;
1041
1042 { // acquire lock
1043 AutoMutex _l(mLock);
1044
1045 if (down) {
1046 // Rotate key codes according to orientation if needed.
1047 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001048 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001049 int32_t orientation;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001050 if (!getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1051 NULL, NULL, & orientation)) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001052 orientation = DISPLAY_ORIENTATION_0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001053 }
1054
1055 keyCode = rotateKeyCode(keyCode, orientation);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001056 }
1057
Jeff Brown6328cdc2010-07-29 18:18:33 -07001058 // Add key down.
1059 ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1060 if (keyDownIndex >= 0) {
1061 // key repeat, be sure to use same keycode as before in case of rotation
Jeff Brown6b53e8d2010-11-10 16:03:06 -08001062 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001063 } else {
1064 // key down
Jeff Brownfe508922011-01-18 15:10:10 -08001065 if ((policyFlags & POLICY_FLAG_VIRTUAL)
1066 && mContext->shouldDropVirtualKey(when,
1067 getDevice(), keyCode, scanCode)) {
1068 return;
1069 }
1070
Jeff Brown6328cdc2010-07-29 18:18:33 -07001071 mLocked.keyDowns.push();
1072 KeyDown& keyDown = mLocked.keyDowns.editTop();
1073 keyDown.keyCode = keyCode;
1074 keyDown.scanCode = scanCode;
1075 }
1076
1077 mLocked.downTime = when;
1078 } else {
1079 // Remove key down.
1080 ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1081 if (keyDownIndex >= 0) {
1082 // key up, be sure to use same keycode as before in case of rotation
Jeff Brown6b53e8d2010-11-10 16:03:06 -08001083 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001084 mLocked.keyDowns.removeAt(size_t(keyDownIndex));
1085 } else {
1086 // key was not actually down
1087 LOGI("Dropping key up from device %s because the key was not down. "
1088 "keyCode=%d, scanCode=%d",
1089 getDeviceName().string(), keyCode, scanCode);
1090 return;
1091 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001092 }
1093
Jeff Brown6328cdc2010-07-29 18:18:33 -07001094 int32_t oldMetaState = mLocked.metaState;
1095 newMetaState = updateMetaState(keyCode, down, oldMetaState);
1096 if (oldMetaState != newMetaState) {
1097 mLocked.metaState = newMetaState;
1098 metaStateChanged = true;
Jeff Brown497a92c2010-09-12 17:55:08 -07001099 updateLedStateLocked(false);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001100 }
Jeff Brownfd035822010-06-30 16:10:35 -07001101
Jeff Brown6328cdc2010-07-29 18:18:33 -07001102 downTime = mLocked.downTime;
1103 } // release lock
1104
Jeff Brown56194eb2011-03-02 19:23:13 -08001105 // Key down on external an keyboard should wake the device.
1106 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
1107 // For internal keyboards, the key layout file should specify the policy flags for
1108 // each wake key individually.
1109 // TODO: Use the input device configuration to control this behavior more finely.
1110 if (down && getDevice()->isExternal()
1111 && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) {
1112 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1113 }
1114
Jeff Brown6328cdc2010-07-29 18:18:33 -07001115 if (metaStateChanged) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001116 getContext()->updateGlobalMetaState();
Jeff Brown46b9ac02010-04-22 18:58:52 -07001117 }
1118
Jeff Brown05dc66a2011-03-02 14:41:58 -08001119 if (down && !isMetaKey(keyCode)) {
1120 getContext()->fadePointer();
1121 }
1122
Jeff Brownefd32662011-03-08 15:13:06 -08001123 getDispatcher()->notifyKey(when, getDeviceId(), mSource, policyFlags,
Jeff Brownb6997262010-10-08 22:31:17 -07001124 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
1125 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001126}
1127
Jeff Brown6328cdc2010-07-29 18:18:33 -07001128ssize_t KeyboardInputMapper::findKeyDownLocked(int32_t scanCode) {
1129 size_t n = mLocked.keyDowns.size();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001130 for (size_t i = 0; i < n; i++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001131 if (mLocked.keyDowns[i].scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001132 return i;
1133 }
1134 }
1135 return -1;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001136}
1137
Jeff Brown6d0fec22010-07-23 21:28:06 -07001138int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1139 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
1140}
Jeff Brown46b9ac02010-04-22 18:58:52 -07001141
Jeff Brown6d0fec22010-07-23 21:28:06 -07001142int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1143 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1144}
Jeff Brown46b9ac02010-04-22 18:58:52 -07001145
Jeff Brown6d0fec22010-07-23 21:28:06 -07001146bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1147 const int32_t* keyCodes, uint8_t* outFlags) {
1148 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
1149}
1150
1151int32_t KeyboardInputMapper::getMetaState() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001152 { // acquire lock
1153 AutoMutex _l(mLock);
1154 return mLocked.metaState;
1155 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001156}
1157
Jeff Brown49ed71d2010-12-06 17:13:33 -08001158void KeyboardInputMapper::resetLedStateLocked() {
1159 initializeLedStateLocked(mLocked.capsLockLedState, LED_CAPSL);
1160 initializeLedStateLocked(mLocked.numLockLedState, LED_NUML);
1161 initializeLedStateLocked(mLocked.scrollLockLedState, LED_SCROLLL);
1162
1163 updateLedStateLocked(true);
1164}
1165
1166void KeyboardInputMapper::initializeLedStateLocked(LockedState::LedState& ledState, int32_t led) {
1167 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
1168 ledState.on = false;
1169}
1170
Jeff Brown497a92c2010-09-12 17:55:08 -07001171void KeyboardInputMapper::updateLedStateLocked(bool reset) {
1172 updateLedStateForModifierLocked(mLocked.capsLockLedState, LED_CAPSL,
Jeff Brown51e7fe72010-10-29 22:19:53 -07001173 AMETA_CAPS_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001174 updateLedStateForModifierLocked(mLocked.numLockLedState, LED_NUML,
Jeff Brown51e7fe72010-10-29 22:19:53 -07001175 AMETA_NUM_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001176 updateLedStateForModifierLocked(mLocked.scrollLockLedState, LED_SCROLLL,
Jeff Brown51e7fe72010-10-29 22:19:53 -07001177 AMETA_SCROLL_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001178}
1179
1180void KeyboardInputMapper::updateLedStateForModifierLocked(LockedState::LedState& ledState,
1181 int32_t led, int32_t modifier, bool reset) {
1182 if (ledState.avail) {
1183 bool desiredState = (mLocked.metaState & modifier) != 0;
Jeff Brown49ed71d2010-12-06 17:13:33 -08001184 if (reset || ledState.on != desiredState) {
Jeff Brown497a92c2010-09-12 17:55:08 -07001185 getEventHub()->setLedState(getDeviceId(), led, desiredState);
1186 ledState.on = desiredState;
1187 }
1188 }
1189}
1190
Jeff Brown6d0fec22010-07-23 21:28:06 -07001191
Jeff Brown83c09682010-12-23 17:50:18 -08001192// --- CursorInputMapper ---
Jeff Brown6d0fec22010-07-23 21:28:06 -07001193
Jeff Brown83c09682010-12-23 17:50:18 -08001194CursorInputMapper::CursorInputMapper(InputDevice* device) :
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001195 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001196 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001197}
1198
Jeff Brown83c09682010-12-23 17:50:18 -08001199CursorInputMapper::~CursorInputMapper() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001200}
1201
Jeff Brown83c09682010-12-23 17:50:18 -08001202uint32_t CursorInputMapper::getSources() {
Jeff Brownefd32662011-03-08 15:13:06 -08001203 return mSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001204}
1205
Jeff Brown83c09682010-12-23 17:50:18 -08001206void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001207 InputMapper::populateDeviceInfo(info);
1208
Jeff Brown83c09682010-12-23 17:50:18 -08001209 if (mParameters.mode == Parameters::MODE_POINTER) {
1210 float minX, minY, maxX, maxY;
1211 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
Jeff Brownefd32662011-03-08 15:13:06 -08001212 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f);
1213 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f);
Jeff Brown83c09682010-12-23 17:50:18 -08001214 }
1215 } else {
Jeff Brownefd32662011-03-08 15:13:06 -08001216 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale);
1217 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale);
Jeff Brown83c09682010-12-23 17:50:18 -08001218 }
Jeff Brownefd32662011-03-08 15:13:06 -08001219 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001220
1221 if (mHaveVWheel) {
Jeff Brownefd32662011-03-08 15:13:06 -08001222 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001223 }
1224 if (mHaveHWheel) {
Jeff Brownefd32662011-03-08 15:13:06 -08001225 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001226 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001227}
1228
Jeff Brown83c09682010-12-23 17:50:18 -08001229void CursorInputMapper::dump(String8& dump) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07001230 { // acquire lock
1231 AutoMutex _l(mLock);
Jeff Brown83c09682010-12-23 17:50:18 -08001232 dump.append(INDENT2 "Cursor Input Mapper:\n");
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001233 dumpParameters(dump);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001234 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
1235 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
Jeff Brownef3d7e82010-09-30 14:33:04 -07001236 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
1237 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001238 dump.appendFormat(INDENT3 "HaveVWheel: %s\n", toString(mHaveVWheel));
1239 dump.appendFormat(INDENT3 "HaveHWheel: %s\n", toString(mHaveHWheel));
1240 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
1241 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001242 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mLocked.buttonState);
1243 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mLocked.buttonState)));
Jeff Brownef3d7e82010-09-30 14:33:04 -07001244 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
1245 } // release lock
1246}
1247
Jeff Brown83c09682010-12-23 17:50:18 -08001248void CursorInputMapper::configure() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001249 InputMapper::configure();
1250
1251 // Configure basic parameters.
1252 configureParameters();
Jeff Brown83c09682010-12-23 17:50:18 -08001253
1254 // Configure device mode.
1255 switch (mParameters.mode) {
1256 case Parameters::MODE_POINTER:
Jeff Brownefd32662011-03-08 15:13:06 -08001257 mSource = AINPUT_SOURCE_MOUSE;
Jeff Brown83c09682010-12-23 17:50:18 -08001258 mXPrecision = 1.0f;
1259 mYPrecision = 1.0f;
1260 mXScale = 1.0f;
1261 mYScale = 1.0f;
1262 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
1263 break;
1264 case Parameters::MODE_NAVIGATION:
Jeff Brownefd32662011-03-08 15:13:06 -08001265 mSource = AINPUT_SOURCE_TRACKBALL;
Jeff Brown83c09682010-12-23 17:50:18 -08001266 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1267 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1268 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1269 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1270 break;
1271 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08001272
1273 mVWheelScale = 1.0f;
1274 mHWheelScale = 1.0f;
Jeff Browncc0c1592011-02-19 05:07:28 -08001275
1276 mHaveVWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_WHEEL);
1277 mHaveHWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_HWHEEL);
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001278}
1279
Jeff Brown83c09682010-12-23 17:50:18 -08001280void CursorInputMapper::configureParameters() {
1281 mParameters.mode = Parameters::MODE_POINTER;
1282 String8 cursorModeString;
1283 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
1284 if (cursorModeString == "navigation") {
1285 mParameters.mode = Parameters::MODE_NAVIGATION;
1286 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
1287 LOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
1288 }
1289 }
1290
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001291 mParameters.orientationAware = false;
Jeff Brown83c09682010-12-23 17:50:18 -08001292 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001293 mParameters.orientationAware);
1294
Jeff Brown83c09682010-12-23 17:50:18 -08001295 mParameters.associatedDisplayId = mParameters.mode == Parameters::MODE_POINTER
1296 || mParameters.orientationAware ? 0 : -1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001297}
1298
Jeff Brown83c09682010-12-23 17:50:18 -08001299void CursorInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001300 dump.append(INDENT3 "Parameters:\n");
1301 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1302 mParameters.associatedDisplayId);
Jeff Brown83c09682010-12-23 17:50:18 -08001303
1304 switch (mParameters.mode) {
1305 case Parameters::MODE_POINTER:
1306 dump.append(INDENT4 "Mode: pointer\n");
1307 break;
1308 case Parameters::MODE_NAVIGATION:
1309 dump.append(INDENT4 "Mode: navigation\n");
1310 break;
1311 default:
1312 assert(false);
1313 }
1314
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001315 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1316 toString(mParameters.orientationAware));
1317}
1318
Jeff Brown83c09682010-12-23 17:50:18 -08001319void CursorInputMapper::initializeLocked() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001320 mAccumulator.clear();
1321
Jeff Brownefd32662011-03-08 15:13:06 -08001322 mLocked.buttonState = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001323 mLocked.downTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001324}
1325
Jeff Brown83c09682010-12-23 17:50:18 -08001326void CursorInputMapper::reset() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001327 for (;;) {
Jeff Brownefd32662011-03-08 15:13:06 -08001328 uint32_t buttonState;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001329 { // acquire lock
1330 AutoMutex _l(mLock);
1331
Jeff Brownefd32662011-03-08 15:13:06 -08001332 buttonState = mLocked.buttonState;
1333 if (!buttonState) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001334 initializeLocked();
1335 break; // done
1336 }
1337 } // release lock
1338
Jeff Brown83c09682010-12-23 17:50:18 -08001339 // Synthesize button up event on reset.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001340 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brownefd32662011-03-08 15:13:06 -08001341 mAccumulator.clear();
1342 mAccumulator.buttonDown = 0;
1343 mAccumulator.buttonUp = buttonState;
1344 mAccumulator.fields = Accumulator::FIELD_BUTTONS;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001345 sync(when);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001346 }
1347
Jeff Brown6d0fec22010-07-23 21:28:06 -07001348 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001349}
Jeff Brown46b9ac02010-04-22 18:58:52 -07001350
Jeff Brown83c09682010-12-23 17:50:18 -08001351void CursorInputMapper::process(const RawEvent* rawEvent) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001352 switch (rawEvent->type) {
Jeff Brownefd32662011-03-08 15:13:06 -08001353 case EV_KEY: {
1354 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
1355 if (buttonState) {
1356 if (rawEvent->value) {
1357 mAccumulator.buttonDown = buttonState;
1358 mAccumulator.buttonUp = 0;
1359 } else {
1360 mAccumulator.buttonDown = 0;
1361 mAccumulator.buttonUp = buttonState;
1362 }
1363 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
1364
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001365 // Sync now since BTN_MOUSE is not necessarily followed by SYN_REPORT and
1366 // we need to ensure that we report the up/down promptly.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001367 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001368 break;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001369 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001370 break;
Jeff Brownefd32662011-03-08 15:13:06 -08001371 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001372
Jeff Brown6d0fec22010-07-23 21:28:06 -07001373 case EV_REL:
1374 switch (rawEvent->scanCode) {
1375 case REL_X:
1376 mAccumulator.fields |= Accumulator::FIELD_REL_X;
1377 mAccumulator.relX = rawEvent->value;
1378 break;
1379 case REL_Y:
1380 mAccumulator.fields |= Accumulator::FIELD_REL_Y;
1381 mAccumulator.relY = rawEvent->value;
1382 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001383 case REL_WHEEL:
1384 mAccumulator.fields |= Accumulator::FIELD_REL_WHEEL;
1385 mAccumulator.relWheel = rawEvent->value;
1386 break;
1387 case REL_HWHEEL:
1388 mAccumulator.fields |= Accumulator::FIELD_REL_HWHEEL;
1389 mAccumulator.relHWheel = rawEvent->value;
1390 break;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001391 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001392 break;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001393
Jeff Brown6d0fec22010-07-23 21:28:06 -07001394 case EV_SYN:
1395 switch (rawEvent->scanCode) {
1396 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001397 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001398 break;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001399 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001400 break;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001401 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001402}
1403
Jeff Brown83c09682010-12-23 17:50:18 -08001404void CursorInputMapper::sync(nsecs_t when) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001405 uint32_t fields = mAccumulator.fields;
1406 if (fields == 0) {
1407 return; // no new state changes, so nothing to do
1408 }
1409
Jeff Brown9626b142011-03-03 02:09:54 -08001410 int32_t motionEventAction;
1411 int32_t motionEventEdgeFlags;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001412 PointerCoords pointerCoords;
1413 nsecs_t downTime;
Jeff Brown33bbfd22011-02-24 20:55:35 -08001414 float vscroll, hscroll;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001415 { // acquire lock
1416 AutoMutex _l(mLock);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001417
Jeff Brownefd32662011-03-08 15:13:06 -08001418 bool down, downChanged;
1419 bool wasDown = isPointerDown(mLocked.buttonState);
1420 bool buttonsChanged = fields & Accumulator::FIELD_BUTTONS;
1421 if (buttonsChanged) {
1422 mLocked.buttonState = (mLocked.buttonState | mAccumulator.buttonDown)
1423 & ~mAccumulator.buttonUp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001424
Jeff Brownefd32662011-03-08 15:13:06 -08001425 down = isPointerDown(mLocked.buttonState);
1426
1427 if (!wasDown && down) {
1428 mLocked.downTime = when;
1429 downChanged = true;
1430 } else if (wasDown && !down) {
1431 downChanged = true;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001432 } else {
Jeff Brownefd32662011-03-08 15:13:06 -08001433 downChanged = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001434 }
Jeff Brownefd32662011-03-08 15:13:06 -08001435 } else {
1436 down = wasDown;
1437 downChanged = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001438 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001439
Jeff Brown6328cdc2010-07-29 18:18:33 -07001440 downTime = mLocked.downTime;
Jeff Brown83c09682010-12-23 17:50:18 -08001441 float deltaX = fields & Accumulator::FIELD_REL_X ? mAccumulator.relX * mXScale : 0.0f;
1442 float deltaY = fields & Accumulator::FIELD_REL_Y ? mAccumulator.relY * mYScale : 0.0f;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001443
Jeff Brown6328cdc2010-07-29 18:18:33 -07001444 if (downChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08001445 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
1446 } else if (down || mPointerController == NULL) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001447 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
Jeff Browncc0c1592011-02-19 05:07:28 -08001448 } else {
1449 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001450 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001451
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001452 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0
Jeff Brown83c09682010-12-23 17:50:18 -08001453 && (deltaX != 0.0f || deltaY != 0.0f)) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001454 // Rotate motion based on display orientation if needed.
1455 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
1456 int32_t orientation;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001457 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1458 NULL, NULL, & orientation)) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001459 orientation = DISPLAY_ORIENTATION_0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001460 }
1461
1462 float temp;
1463 switch (orientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001464 case DISPLAY_ORIENTATION_90:
Jeff Brown83c09682010-12-23 17:50:18 -08001465 temp = deltaX;
1466 deltaX = deltaY;
1467 deltaY = -temp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001468 break;
1469
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001470 case DISPLAY_ORIENTATION_180:
Jeff Brown83c09682010-12-23 17:50:18 -08001471 deltaX = -deltaX;
1472 deltaY = -deltaY;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001473 break;
1474
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001475 case DISPLAY_ORIENTATION_270:
Jeff Brown83c09682010-12-23 17:50:18 -08001476 temp = deltaX;
1477 deltaX = -deltaY;
1478 deltaY = temp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001479 break;
1480 }
1481 }
Jeff Brown83c09682010-12-23 17:50:18 -08001482
Jeff Brown91c69ab2011-02-14 17:03:18 -08001483 pointerCoords.clear();
1484
Jeff Brown9626b142011-03-03 02:09:54 -08001485 motionEventEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
1486
Jeff Brown83c09682010-12-23 17:50:18 -08001487 if (mPointerController != NULL) {
1488 mPointerController->move(deltaX, deltaY);
Jeff Brownefd32662011-03-08 15:13:06 -08001489 if (buttonsChanged) {
1490 mPointerController->setButtonState(mLocked.buttonState);
Jeff Brown83c09682010-12-23 17:50:18 -08001491 }
Jeff Brownefd32662011-03-08 15:13:06 -08001492
Jeff Brown91c69ab2011-02-14 17:03:18 -08001493 float x, y;
1494 mPointerController->getPosition(&x, &y);
Jeff Brownebbd5d12011-02-17 13:01:34 -08001495 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
1496 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jeff Brown9626b142011-03-03 02:09:54 -08001497
1498 if (motionEventAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownefd32662011-03-08 15:13:06 -08001499 motionEventEdgeFlags = calculateEdgeFlagsUsingPointerBounds(
1500 mPointerController, x, y);
Jeff Brown9626b142011-03-03 02:09:54 -08001501 }
Jeff Brown83c09682010-12-23 17:50:18 -08001502 } else {
Jeff Brownebbd5d12011-02-17 13:01:34 -08001503 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
1504 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
Jeff Brown83c09682010-12-23 17:50:18 -08001505 }
1506
Jeff Brownefd32662011-03-08 15:13:06 -08001507 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001508
1509 if (mHaveVWheel && (fields & Accumulator::FIELD_REL_WHEEL)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001510 vscroll = mAccumulator.relWheel;
1511 } else {
1512 vscroll = 0;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001513 }
1514 if (mHaveHWheel && (fields & Accumulator::FIELD_REL_HWHEEL)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001515 hscroll = mAccumulator.relHWheel;
1516 } else {
1517 hscroll = 0;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001518 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001519 if (hscroll != 0 || vscroll != 0) {
1520 mPointerController->unfade();
1521 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001522 } // release lock
1523
Jeff Brown56194eb2011-03-02 19:23:13 -08001524 // Moving an external trackball or mouse should wake the device.
1525 // We don't do this for internal cursor devices to prevent them from waking up
1526 // the device in your pocket.
1527 // TODO: Use the input device configuration to control this behavior more finely.
1528 uint32_t policyFlags = 0;
1529 if (getDevice()->isExternal()) {
1530 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1531 }
1532
Jeff Brown6d0fec22010-07-23 21:28:06 -07001533 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown6328cdc2010-07-29 18:18:33 -07001534 int32_t pointerId = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08001535 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brown9626b142011-03-03 02:09:54 -08001536 motionEventAction, 0, metaState, motionEventEdgeFlags,
Jeff Brownb6997262010-10-08 22:31:17 -07001537 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1538
1539 mAccumulator.clear();
Jeff Brown33bbfd22011-02-24 20:55:35 -08001540
1541 if (vscroll != 0 || hscroll != 0) {
1542 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
1543 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
1544
Jeff Brownefd32662011-03-08 15:13:06 -08001545 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brown33bbfd22011-02-24 20:55:35 -08001546 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
1547 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1548 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001549}
1550
Jeff Brown83c09682010-12-23 17:50:18 -08001551int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brownc3fc2d02010-08-10 15:47:53 -07001552 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
1553 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1554 } else {
1555 return AKEY_STATE_UNKNOWN;
1556 }
1557}
1558
Jeff Brown05dc66a2011-03-02 14:41:58 -08001559void CursorInputMapper::fadePointer() {
1560 { // acquire lock
1561 AutoMutex _l(mLock);
Jeff Brownefd32662011-03-08 15:13:06 -08001562 if (mPointerController != NULL) {
1563 mPointerController->fade();
1564 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001565 } // release lock
1566}
1567
Jeff Brown6d0fec22010-07-23 21:28:06 -07001568
1569// --- TouchInputMapper ---
1570
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001571TouchInputMapper::TouchInputMapper(InputDevice* device) :
1572 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001573 mLocked.surfaceOrientation = -1;
1574 mLocked.surfaceWidth = -1;
1575 mLocked.surfaceHeight = -1;
1576
1577 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001578}
1579
1580TouchInputMapper::~TouchInputMapper() {
1581}
1582
1583uint32_t TouchInputMapper::getSources() {
Jeff Brown96ad3972011-03-09 17:39:48 -08001584 return mTouchSource | mPointerSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001585}
1586
1587void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1588 InputMapper::populateDeviceInfo(info);
1589
Jeff Brown6328cdc2010-07-29 18:18:33 -07001590 { // acquire lock
1591 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001592
Jeff Brown6328cdc2010-07-29 18:18:33 -07001593 // Ensure surface information is up to date so that orientation changes are
1594 // noticed immediately.
Jeff Brownefd32662011-03-08 15:13:06 -08001595 if (!configureSurfaceLocked()) {
1596 return;
1597 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001598
Jeff Brownefd32662011-03-08 15:13:06 -08001599 info->addMotionRange(mLocked.orientedRanges.x);
1600 info->addMotionRange(mLocked.orientedRanges.y);
Jeff Brown8d608662010-08-30 03:02:23 -07001601
1602 if (mLocked.orientedRanges.havePressure) {
Jeff Brownefd32662011-03-08 15:13:06 -08001603 info->addMotionRange(mLocked.orientedRanges.pressure);
Jeff Brown8d608662010-08-30 03:02:23 -07001604 }
1605
1606 if (mLocked.orientedRanges.haveSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001607 info->addMotionRange(mLocked.orientedRanges.size);
Jeff Brown8d608662010-08-30 03:02:23 -07001608 }
1609
Jeff Brownc6d282b2010-10-14 21:42:15 -07001610 if (mLocked.orientedRanges.haveTouchSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001611 info->addMotionRange(mLocked.orientedRanges.touchMajor);
1612 info->addMotionRange(mLocked.orientedRanges.touchMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001613 }
1614
Jeff Brownc6d282b2010-10-14 21:42:15 -07001615 if (mLocked.orientedRanges.haveToolSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001616 info->addMotionRange(mLocked.orientedRanges.toolMajor);
1617 info->addMotionRange(mLocked.orientedRanges.toolMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001618 }
1619
1620 if (mLocked.orientedRanges.haveOrientation) {
Jeff Brownefd32662011-03-08 15:13:06 -08001621 info->addMotionRange(mLocked.orientedRanges.orientation);
Jeff Brown8d608662010-08-30 03:02:23 -07001622 }
Jeff Brown96ad3972011-03-09 17:39:48 -08001623
1624 if (mPointerController != NULL) {
1625 float minX, minY, maxX, maxY;
1626 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
1627 info->addMotionRange(AMOTION_EVENT_AXIS_X, mPointerSource,
1628 minX, maxX, 0.0f, 0.0f);
1629 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mPointerSource,
1630 minY, maxY, 0.0f, 0.0f);
1631 }
1632 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mPointerSource,
1633 0.0f, 1.0f, 0.0f, 0.0f);
1634 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001635 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001636}
1637
Jeff Brownef3d7e82010-09-30 14:33:04 -07001638void TouchInputMapper::dump(String8& dump) {
1639 { // acquire lock
1640 AutoMutex _l(mLock);
1641 dump.append(INDENT2 "Touch Input Mapper:\n");
Jeff Brownef3d7e82010-09-30 14:33:04 -07001642 dumpParameters(dump);
1643 dumpVirtualKeysLocked(dump);
1644 dumpRawAxes(dump);
1645 dumpCalibration(dump);
1646 dumpSurfaceLocked(dump);
Jeff Brownefd32662011-03-08 15:13:06 -08001647
Jeff Brown511ee5f2010-10-18 13:32:20 -07001648 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
Jeff Brownc6d282b2010-10-14 21:42:15 -07001649 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mLocked.xScale);
1650 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mLocked.yScale);
1651 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mLocked.xPrecision);
1652 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mLocked.yPrecision);
1653 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mLocked.geometricScale);
1654 dump.appendFormat(INDENT4 "ToolSizeLinearScale: %0.3f\n", mLocked.toolSizeLinearScale);
1655 dump.appendFormat(INDENT4 "ToolSizeLinearBias: %0.3f\n", mLocked.toolSizeLinearBias);
1656 dump.appendFormat(INDENT4 "ToolSizeAreaScale: %0.3f\n", mLocked.toolSizeAreaScale);
1657 dump.appendFormat(INDENT4 "ToolSizeAreaBias: %0.3f\n", mLocked.toolSizeAreaBias);
1658 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mLocked.pressureScale);
1659 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mLocked.sizeScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001660 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mLocked.orientationScale);
1661
1662 dump.appendFormat(INDENT3 "Last Touch:\n");
1663 dump.appendFormat(INDENT4 "Pointer Count: %d\n", mLastTouch.pointerCount);
Jeff Brown96ad3972011-03-09 17:39:48 -08001664 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", mLastTouch.buttonState);
1665
1666 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
1667 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
1668 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
1669 mLocked.pointerGestureXMovementScale);
1670 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
1671 mLocked.pointerGestureYMovementScale);
1672 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
1673 mLocked.pointerGestureXZoomScale);
1674 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
1675 mLocked.pointerGestureYZoomScale);
1676 dump.appendFormat(INDENT4 "MaxSwipeWidthSquared: %d\n",
1677 mLocked.pointerGestureMaxSwipeWidthSquared);
1678 }
Jeff Brownef3d7e82010-09-30 14:33:04 -07001679 } // release lock
1680}
1681
Jeff Brown6328cdc2010-07-29 18:18:33 -07001682void TouchInputMapper::initializeLocked() {
1683 mCurrentTouch.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001684 mLastTouch.clear();
1685 mDownTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001686
1687 for (uint32_t i = 0; i < MAX_POINTERS; i++) {
1688 mAveragingTouchFilter.historyStart[i] = 0;
1689 mAveragingTouchFilter.historyEnd[i] = 0;
1690 }
1691
1692 mJumpyTouchFilter.jumpyPointsDropped = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001693
1694 mLocked.currentVirtualKey.down = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001695
1696 mLocked.orientedRanges.havePressure = false;
1697 mLocked.orientedRanges.haveSize = false;
Jeff Brownc6d282b2010-10-14 21:42:15 -07001698 mLocked.orientedRanges.haveTouchSize = false;
1699 mLocked.orientedRanges.haveToolSize = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001700 mLocked.orientedRanges.haveOrientation = false;
Jeff Brown96ad3972011-03-09 17:39:48 -08001701
1702 mPointerGesture.reset();
Jeff Brown8d608662010-08-30 03:02:23 -07001703}
1704
Jeff Brown6d0fec22010-07-23 21:28:06 -07001705void TouchInputMapper::configure() {
1706 InputMapper::configure();
1707
1708 // Configure basic parameters.
Jeff Brown8d608662010-08-30 03:02:23 -07001709 configureParameters();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001710
Jeff Brown83c09682010-12-23 17:50:18 -08001711 // Configure sources.
1712 switch (mParameters.deviceType) {
1713 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Jeff Brownefd32662011-03-08 15:13:06 -08001714 mTouchSource = AINPUT_SOURCE_TOUCHSCREEN;
Jeff Brown96ad3972011-03-09 17:39:48 -08001715 mPointerSource = 0;
Jeff Brown83c09682010-12-23 17:50:18 -08001716 break;
1717 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Jeff Brownefd32662011-03-08 15:13:06 -08001718 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
Jeff Brown96ad3972011-03-09 17:39:48 -08001719 mPointerSource = 0;
1720 break;
1721 case Parameters::DEVICE_TYPE_POINTER:
1722 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
1723 mPointerSource = AINPUT_SOURCE_MOUSE;
Jeff Brown83c09682010-12-23 17:50:18 -08001724 break;
1725 default:
1726 assert(false);
1727 }
1728
Jeff Brown6d0fec22010-07-23 21:28:06 -07001729 // Configure absolute axis information.
Jeff Brown8d608662010-08-30 03:02:23 -07001730 configureRawAxes();
Jeff Brown8d608662010-08-30 03:02:23 -07001731
1732 // Prepare input device calibration.
1733 parseCalibration();
1734 resolveCalibration();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001735
Jeff Brown6328cdc2010-07-29 18:18:33 -07001736 { // acquire lock
1737 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001738
Jeff Brown8d608662010-08-30 03:02:23 -07001739 // Configure surface dimensions and orientation.
Jeff Brown6328cdc2010-07-29 18:18:33 -07001740 configureSurfaceLocked();
1741 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001742}
1743
Jeff Brown8d608662010-08-30 03:02:23 -07001744void TouchInputMapper::configureParameters() {
1745 mParameters.useBadTouchFilter = getPolicy()->filterTouchEvents();
1746 mParameters.useAveragingTouchFilter = getPolicy()->filterTouchEvents();
1747 mParameters.useJumpyTouchFilter = getPolicy()->filterJumpyTouchEvents();
Jeff Brownfe508922011-01-18 15:10:10 -08001748 mParameters.virtualKeyQuietTime = getPolicy()->getVirtualKeyQuietTime();
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001749
Jeff Brown96ad3972011-03-09 17:39:48 -08001750 if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
1751 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
1752 // The device is a cursor device with a touch pad attached.
1753 // By default don't use the touch pad to move the pointer.
1754 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
1755 } else {
1756 // The device is just a touch pad.
1757 // By default use the touch pad to move the pointer and to perform related gestures.
1758 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
1759 }
1760
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001761 String8 deviceTypeString;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001762 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
1763 deviceTypeString)) {
Jeff Brown58a2da82011-01-25 16:02:22 -08001764 if (deviceTypeString == "touchScreen") {
1765 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brownefd32662011-03-08 15:13:06 -08001766 } else if (deviceTypeString == "touchPad") {
1767 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
Jeff Brown96ad3972011-03-09 17:39:48 -08001768 } else if (deviceTypeString == "pointer") {
1769 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
Jeff Brownefd32662011-03-08 15:13:06 -08001770 } else {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001771 LOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
1772 }
1773 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001774
Jeff Brownefd32662011-03-08 15:13:06 -08001775 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001776 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
1777 mParameters.orientationAware);
1778
Jeff Brownefd32662011-03-08 15:13:06 -08001779 mParameters.associatedDisplayId = mParameters.orientationAware
1780 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
Jeff Brown96ad3972011-03-09 17:39:48 -08001781 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
Jeff Brownefd32662011-03-08 15:13:06 -08001782 ? 0 : -1;
Jeff Brown8d608662010-08-30 03:02:23 -07001783}
1784
Jeff Brownef3d7e82010-09-30 14:33:04 -07001785void TouchInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001786 dump.append(INDENT3 "Parameters:\n");
1787
1788 switch (mParameters.deviceType) {
1789 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
1790 dump.append(INDENT4 "DeviceType: touchScreen\n");
1791 break;
1792 case Parameters::DEVICE_TYPE_TOUCH_PAD:
1793 dump.append(INDENT4 "DeviceType: touchPad\n");
1794 break;
Jeff Brown96ad3972011-03-09 17:39:48 -08001795 case Parameters::DEVICE_TYPE_POINTER:
1796 dump.append(INDENT4 "DeviceType: pointer\n");
1797 break;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001798 default:
1799 assert(false);
1800 }
1801
1802 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1803 mParameters.associatedDisplayId);
1804 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1805 toString(mParameters.orientationAware));
1806
1807 dump.appendFormat(INDENT4 "UseBadTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001808 toString(mParameters.useBadTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001809 dump.appendFormat(INDENT4 "UseAveragingTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001810 toString(mParameters.useAveragingTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001811 dump.appendFormat(INDENT4 "UseJumpyTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001812 toString(mParameters.useJumpyTouchFilter));
Jeff Brownb88102f2010-09-08 11:49:43 -07001813}
1814
Jeff Brown8d608662010-08-30 03:02:23 -07001815void TouchInputMapper::configureRawAxes() {
1816 mRawAxes.x.clear();
1817 mRawAxes.y.clear();
1818 mRawAxes.pressure.clear();
1819 mRawAxes.touchMajor.clear();
1820 mRawAxes.touchMinor.clear();
1821 mRawAxes.toolMajor.clear();
1822 mRawAxes.toolMinor.clear();
1823 mRawAxes.orientation.clear();
1824}
1825
Jeff Brownef3d7e82010-09-30 14:33:04 -07001826void TouchInputMapper::dumpRawAxes(String8& dump) {
1827 dump.append(INDENT3 "Raw Axes:\n");
Jeff Browncb1404e2011-01-15 18:14:15 -08001828 dumpRawAbsoluteAxisInfo(dump, mRawAxes.x, "X");
1829 dumpRawAbsoluteAxisInfo(dump, mRawAxes.y, "Y");
1830 dumpRawAbsoluteAxisInfo(dump, mRawAxes.pressure, "Pressure");
1831 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMajor, "TouchMajor");
1832 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMinor, "TouchMinor");
1833 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMajor, "ToolMajor");
1834 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMinor, "ToolMinor");
1835 dumpRawAbsoluteAxisInfo(dump, mRawAxes.orientation, "Orientation");
Jeff Brown6d0fec22010-07-23 21:28:06 -07001836}
1837
Jeff Brown6328cdc2010-07-29 18:18:33 -07001838bool TouchInputMapper::configureSurfaceLocked() {
Jeff Brown9626b142011-03-03 02:09:54 -08001839 // Ensure we have valid X and Y axes.
1840 if (!mRawAxes.x.valid || !mRawAxes.y.valid) {
1841 LOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
1842 "The device will be inoperable.", getDeviceName().string());
1843 return false;
1844 }
1845
Jeff Brown6d0fec22010-07-23 21:28:06 -07001846 // Update orientation and dimensions if needed.
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001847 int32_t orientation = DISPLAY_ORIENTATION_0;
Jeff Brown9626b142011-03-03 02:09:54 -08001848 int32_t width = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
1849 int32_t height = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001850
1851 if (mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001852 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001853 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
Jeff Brownefd32662011-03-08 15:13:06 -08001854 &mLocked.associatedDisplayWidth, &mLocked.associatedDisplayHeight,
1855 &mLocked.associatedDisplayOrientation)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001856 return false;
1857 }
Jeff Brownefd32662011-03-08 15:13:06 -08001858
1859 // A touch screen inherits the dimensions of the display.
1860 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
1861 width = mLocked.associatedDisplayWidth;
1862 height = mLocked.associatedDisplayHeight;
1863 }
1864
1865 // The device inherits the orientation of the display if it is orientation aware.
1866 if (mParameters.orientationAware) {
1867 orientation = mLocked.associatedDisplayOrientation;
1868 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001869 }
1870
Jeff Brown96ad3972011-03-09 17:39:48 -08001871 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
1872 && mPointerController == NULL) {
1873 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
1874 }
1875
Jeff Brown6328cdc2010-07-29 18:18:33 -07001876 bool orientationChanged = mLocked.surfaceOrientation != orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001877 if (orientationChanged) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001878 mLocked.surfaceOrientation = orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001879 }
1880
Jeff Brown6328cdc2010-07-29 18:18:33 -07001881 bool sizeChanged = mLocked.surfaceWidth != width || mLocked.surfaceHeight != height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001882 if (sizeChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08001883 LOGI("Device reconfigured: id=%d, name='%s', surface size is now %dx%d",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001884 getDeviceId(), getDeviceName().string(), width, height);
Jeff Brown8d608662010-08-30 03:02:23 -07001885
Jeff Brown6328cdc2010-07-29 18:18:33 -07001886 mLocked.surfaceWidth = width;
1887 mLocked.surfaceHeight = height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001888
Jeff Brown8d608662010-08-30 03:02:23 -07001889 // Configure X and Y factors.
Jeff Brown9626b142011-03-03 02:09:54 -08001890 mLocked.xScale = float(width) / (mRawAxes.x.maxValue - mRawAxes.x.minValue + 1);
1891 mLocked.yScale = float(height) / (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1);
1892 mLocked.xPrecision = 1.0f / mLocked.xScale;
1893 mLocked.yPrecision = 1.0f / mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001894
Jeff Brownefd32662011-03-08 15:13:06 -08001895 mLocked.orientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
1896 mLocked.orientedRanges.x.source = mTouchSource;
1897 mLocked.orientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
1898 mLocked.orientedRanges.y.source = mTouchSource;
1899
Jeff Brown9626b142011-03-03 02:09:54 -08001900 configureVirtualKeysLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001901
Jeff Brown8d608662010-08-30 03:02:23 -07001902 // Scale factor for terms that are not oriented in a particular axis.
1903 // If the pixels are square then xScale == yScale otherwise we fake it
1904 // by choosing an average.
1905 mLocked.geometricScale = avg(mLocked.xScale, mLocked.yScale);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001906
Jeff Brown8d608662010-08-30 03:02:23 -07001907 // Size of diagonal axis.
1908 float diagonalSize = pythag(width, height);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001909
Jeff Brown8d608662010-08-30 03:02:23 -07001910 // TouchMajor and TouchMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07001911 if (mCalibration.touchSizeCalibration != Calibration::TOUCH_SIZE_CALIBRATION_NONE) {
1912 mLocked.orientedRanges.haveTouchSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08001913
1914 mLocked.orientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
1915 mLocked.orientedRanges.touchMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07001916 mLocked.orientedRanges.touchMajor.min = 0;
1917 mLocked.orientedRanges.touchMajor.max = diagonalSize;
1918 mLocked.orientedRanges.touchMajor.flat = 0;
1919 mLocked.orientedRanges.touchMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08001920
Jeff Brown8d608662010-08-30 03:02:23 -07001921 mLocked.orientedRanges.touchMinor = mLocked.orientedRanges.touchMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08001922 mLocked.orientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07001923 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001924
Jeff Brown8d608662010-08-30 03:02:23 -07001925 // ToolMajor and ToolMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07001926 mLocked.toolSizeLinearScale = 0;
1927 mLocked.toolSizeLinearBias = 0;
1928 mLocked.toolSizeAreaScale = 0;
1929 mLocked.toolSizeAreaBias = 0;
1930 if (mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
1931 if (mCalibration.toolSizeCalibration == Calibration::TOOL_SIZE_CALIBRATION_LINEAR) {
1932 if (mCalibration.haveToolSizeLinearScale) {
1933 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
Jeff Brown8d608662010-08-30 03:02:23 -07001934 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07001935 mLocked.toolSizeLinearScale = float(min(width, height))
Jeff Brown8d608662010-08-30 03:02:23 -07001936 / mRawAxes.toolMajor.maxValue;
1937 }
1938
Jeff Brownc6d282b2010-10-14 21:42:15 -07001939 if (mCalibration.haveToolSizeLinearBias) {
1940 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
1941 }
1942 } else if (mCalibration.toolSizeCalibration ==
1943 Calibration::TOOL_SIZE_CALIBRATION_AREA) {
1944 if (mCalibration.haveToolSizeLinearScale) {
1945 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
1946 } else {
1947 mLocked.toolSizeLinearScale = min(width, height);
1948 }
1949
1950 if (mCalibration.haveToolSizeLinearBias) {
1951 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
1952 }
1953
1954 if (mCalibration.haveToolSizeAreaScale) {
1955 mLocked.toolSizeAreaScale = mCalibration.toolSizeAreaScale;
1956 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
1957 mLocked.toolSizeAreaScale = 1.0f / mRawAxes.toolMajor.maxValue;
1958 }
1959
1960 if (mCalibration.haveToolSizeAreaBias) {
1961 mLocked.toolSizeAreaBias = mCalibration.toolSizeAreaBias;
Jeff Brown8d608662010-08-30 03:02:23 -07001962 }
1963 }
1964
Jeff Brownc6d282b2010-10-14 21:42:15 -07001965 mLocked.orientedRanges.haveToolSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08001966
1967 mLocked.orientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
1968 mLocked.orientedRanges.toolMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07001969 mLocked.orientedRanges.toolMajor.min = 0;
1970 mLocked.orientedRanges.toolMajor.max = diagonalSize;
1971 mLocked.orientedRanges.toolMajor.flat = 0;
1972 mLocked.orientedRanges.toolMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08001973
Jeff Brown8d608662010-08-30 03:02:23 -07001974 mLocked.orientedRanges.toolMinor = mLocked.orientedRanges.toolMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08001975 mLocked.orientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07001976 }
1977
1978 // Pressure factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07001979 mLocked.pressureScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07001980 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE) {
1981 RawAbsoluteAxisInfo rawPressureAxis;
1982 switch (mCalibration.pressureSource) {
1983 case Calibration::PRESSURE_SOURCE_PRESSURE:
1984 rawPressureAxis = mRawAxes.pressure;
1985 break;
1986 case Calibration::PRESSURE_SOURCE_TOUCH:
1987 rawPressureAxis = mRawAxes.touchMajor;
1988 break;
1989 default:
1990 rawPressureAxis.clear();
1991 }
1992
Jeff Brown8d608662010-08-30 03:02:23 -07001993 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
1994 || mCalibration.pressureCalibration
1995 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
1996 if (mCalibration.havePressureScale) {
1997 mLocked.pressureScale = mCalibration.pressureScale;
1998 } else if (rawPressureAxis.valid && rawPressureAxis.maxValue != 0) {
1999 mLocked.pressureScale = 1.0f / rawPressureAxis.maxValue;
2000 }
2001 }
2002
2003 mLocked.orientedRanges.havePressure = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002004
2005 mLocked.orientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
2006 mLocked.orientedRanges.pressure.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002007 mLocked.orientedRanges.pressure.min = 0;
2008 mLocked.orientedRanges.pressure.max = 1.0;
2009 mLocked.orientedRanges.pressure.flat = 0;
2010 mLocked.orientedRanges.pressure.fuzz = 0;
2011 }
2012
2013 // Size factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002014 mLocked.sizeScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002015 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002016 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_NORMALIZED) {
2017 if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2018 mLocked.sizeScale = 1.0f / mRawAxes.toolMajor.maxValue;
2019 }
2020 }
2021
2022 mLocked.orientedRanges.haveSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002023
2024 mLocked.orientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
2025 mLocked.orientedRanges.size.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002026 mLocked.orientedRanges.size.min = 0;
2027 mLocked.orientedRanges.size.max = 1.0;
2028 mLocked.orientedRanges.size.flat = 0;
2029 mLocked.orientedRanges.size.fuzz = 0;
2030 }
2031
2032 // Orientation
Jeff Brownc6d282b2010-10-14 21:42:15 -07002033 mLocked.orientationScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002034 if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002035 if (mCalibration.orientationCalibration
2036 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
2037 if (mRawAxes.orientation.valid && mRawAxes.orientation.maxValue != 0) {
2038 mLocked.orientationScale = float(M_PI_2) / mRawAxes.orientation.maxValue;
2039 }
2040 }
2041
Jeff Brownefd32662011-03-08 15:13:06 -08002042 mLocked.orientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
2043 mLocked.orientedRanges.orientation.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002044 mLocked.orientedRanges.orientation.min = - M_PI_2;
2045 mLocked.orientedRanges.orientation.max = M_PI_2;
2046 mLocked.orientedRanges.orientation.flat = 0;
2047 mLocked.orientedRanges.orientation.fuzz = 0;
2048 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002049 }
2050
2051 if (orientationChanged || sizeChanged) {
Jeff Brown9626b142011-03-03 02:09:54 -08002052 // Compute oriented surface dimensions, precision, scales and ranges.
2053 // Note that the maximum value reported is an inclusive maximum value so it is one
2054 // unit less than the total width or height of surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002055 switch (mLocked.surfaceOrientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08002056 case DISPLAY_ORIENTATION_90:
2057 case DISPLAY_ORIENTATION_270:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002058 mLocked.orientedSurfaceWidth = mLocked.surfaceHeight;
2059 mLocked.orientedSurfaceHeight = mLocked.surfaceWidth;
Jeff Brown9626b142011-03-03 02:09:54 -08002060
Jeff Brown6328cdc2010-07-29 18:18:33 -07002061 mLocked.orientedXPrecision = mLocked.yPrecision;
2062 mLocked.orientedYPrecision = mLocked.xPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002063
2064 mLocked.orientedRanges.x.min = 0;
2065 mLocked.orientedRanges.x.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2066 * mLocked.yScale;
2067 mLocked.orientedRanges.x.flat = 0;
2068 mLocked.orientedRanges.x.fuzz = mLocked.yScale;
2069
2070 mLocked.orientedRanges.y.min = 0;
2071 mLocked.orientedRanges.y.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2072 * mLocked.xScale;
2073 mLocked.orientedRanges.y.flat = 0;
2074 mLocked.orientedRanges.y.fuzz = mLocked.xScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002075 break;
Jeff Brown9626b142011-03-03 02:09:54 -08002076
Jeff Brown6d0fec22010-07-23 21:28:06 -07002077 default:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002078 mLocked.orientedSurfaceWidth = mLocked.surfaceWidth;
2079 mLocked.orientedSurfaceHeight = mLocked.surfaceHeight;
Jeff Brown9626b142011-03-03 02:09:54 -08002080
Jeff Brown6328cdc2010-07-29 18:18:33 -07002081 mLocked.orientedXPrecision = mLocked.xPrecision;
2082 mLocked.orientedYPrecision = mLocked.yPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002083
2084 mLocked.orientedRanges.x.min = 0;
2085 mLocked.orientedRanges.x.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2086 * mLocked.xScale;
2087 mLocked.orientedRanges.x.flat = 0;
2088 mLocked.orientedRanges.x.fuzz = mLocked.xScale;
2089
2090 mLocked.orientedRanges.y.min = 0;
2091 mLocked.orientedRanges.y.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2092 * mLocked.yScale;
2093 mLocked.orientedRanges.y.flat = 0;
2094 mLocked.orientedRanges.y.fuzz = mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002095 break;
2096 }
Jeff Brown96ad3972011-03-09 17:39:48 -08002097
2098 // Compute pointer gesture detection parameters.
2099 // TODO: These factors should not be hardcoded.
2100 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
2101 int32_t rawWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2102 int32_t rawHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
2103
2104 // Scale movements such that one whole swipe of the touch pad covers a portion
2105 // of the display along whichever axis of the touch pad is longer.
2106 // Assume that the touch pad has a square aspect ratio such that movements in
2107 // X and Y of the same number of raw units cover the same physical distance.
2108 const float scaleFactor = 0.8f;
2109
2110 mLocked.pointerGestureXMovementScale = rawWidth > rawHeight
2111 ? scaleFactor * float(mLocked.associatedDisplayWidth) / rawWidth
2112 : scaleFactor * float(mLocked.associatedDisplayHeight) / rawHeight;
2113 mLocked.pointerGestureYMovementScale = mLocked.pointerGestureXMovementScale;
2114
2115 // Scale zooms to cover a smaller range of the display than movements do.
2116 // This value determines the area around the pointer that is affected by freeform
2117 // pointer gestures.
2118 mLocked.pointerGestureXZoomScale = mLocked.pointerGestureXMovementScale * 0.4f;
2119 mLocked.pointerGestureYZoomScale = mLocked.pointerGestureYMovementScale * 0.4f;
2120
2121 // Max width between pointers to detect a swipe gesture is 3/4 of the short
2122 // axis of the touch pad. Touches that are wider than this are translated
2123 // into freeform gestures.
2124 mLocked.pointerGestureMaxSwipeWidthSquared = min(rawWidth, rawHeight) * 3 / 4;
2125 mLocked.pointerGestureMaxSwipeWidthSquared *=
2126 mLocked.pointerGestureMaxSwipeWidthSquared;
2127 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002128 }
2129
2130 return true;
2131}
2132
Jeff Brownef3d7e82010-09-30 14:33:04 -07002133void TouchInputMapper::dumpSurfaceLocked(String8& dump) {
2134 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mLocked.surfaceWidth);
2135 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mLocked.surfaceHeight);
2136 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mLocked.surfaceOrientation);
Jeff Brownb88102f2010-09-08 11:49:43 -07002137}
2138
Jeff Brown6328cdc2010-07-29 18:18:33 -07002139void TouchInputMapper::configureVirtualKeysLocked() {
Jeff Brown8d608662010-08-30 03:02:23 -07002140 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
Jeff Brown90655042010-12-02 13:50:46 -08002141 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002142
Jeff Brown6328cdc2010-07-29 18:18:33 -07002143 mLocked.virtualKeys.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002144
Jeff Brown6328cdc2010-07-29 18:18:33 -07002145 if (virtualKeyDefinitions.size() == 0) {
2146 return;
2147 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002148
Jeff Brown6328cdc2010-07-29 18:18:33 -07002149 mLocked.virtualKeys.setCapacity(virtualKeyDefinitions.size());
2150
Jeff Brown8d608662010-08-30 03:02:23 -07002151 int32_t touchScreenLeft = mRawAxes.x.minValue;
2152 int32_t touchScreenTop = mRawAxes.y.minValue;
Jeff Brown9626b142011-03-03 02:09:54 -08002153 int32_t touchScreenWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2154 int32_t touchScreenHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002155
2156 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002157 const VirtualKeyDefinition& virtualKeyDefinition =
Jeff Brown6328cdc2010-07-29 18:18:33 -07002158 virtualKeyDefinitions[i];
2159
2160 mLocked.virtualKeys.add();
2161 VirtualKey& virtualKey = mLocked.virtualKeys.editTop();
2162
2163 virtualKey.scanCode = virtualKeyDefinition.scanCode;
2164 int32_t keyCode;
2165 uint32_t flags;
Jeff Brown6f2fba42011-02-19 01:08:02 -08002166 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode,
Jeff Brown6328cdc2010-07-29 18:18:33 -07002167 & keyCode, & flags)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002168 LOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
2169 virtualKey.scanCode);
Jeff Brown6328cdc2010-07-29 18:18:33 -07002170 mLocked.virtualKeys.pop(); // drop the key
2171 continue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002172 }
2173
Jeff Brown6328cdc2010-07-29 18:18:33 -07002174 virtualKey.keyCode = keyCode;
2175 virtualKey.flags = flags;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002176
Jeff Brown6328cdc2010-07-29 18:18:33 -07002177 // convert the key definition's display coordinates into touch coordinates for a hit box
2178 int32_t halfWidth = virtualKeyDefinition.width / 2;
2179 int32_t halfHeight = virtualKeyDefinition.height / 2;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002180
Jeff Brown6328cdc2010-07-29 18:18:33 -07002181 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
2182 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2183 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
2184 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2185 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
2186 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
2187 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
2188 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
Jeff Brownef3d7e82010-09-30 14:33:04 -07002189 }
2190}
2191
2192void TouchInputMapper::dumpVirtualKeysLocked(String8& dump) {
2193 if (!mLocked.virtualKeys.isEmpty()) {
2194 dump.append(INDENT3 "Virtual Keys:\n");
2195
2196 for (size_t i = 0; i < mLocked.virtualKeys.size(); i++) {
2197 const VirtualKey& virtualKey = mLocked.virtualKeys.itemAt(i);
2198 dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, "
2199 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
2200 i, virtualKey.scanCode, virtualKey.keyCode,
2201 virtualKey.hitLeft, virtualKey.hitRight,
2202 virtualKey.hitTop, virtualKey.hitBottom);
2203 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002204 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002205}
2206
Jeff Brown8d608662010-08-30 03:02:23 -07002207void TouchInputMapper::parseCalibration() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002208 const PropertyMap& in = getDevice()->getConfiguration();
Jeff Brown8d608662010-08-30 03:02:23 -07002209 Calibration& out = mCalibration;
2210
Jeff Brownc6d282b2010-10-14 21:42:15 -07002211 // Touch Size
2212 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT;
2213 String8 touchSizeCalibrationString;
2214 if (in.tryGetProperty(String8("touch.touchSize.calibration"), touchSizeCalibrationString)) {
2215 if (touchSizeCalibrationString == "none") {
2216 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
2217 } else if (touchSizeCalibrationString == "geometric") {
2218 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC;
2219 } else if (touchSizeCalibrationString == "pressure") {
2220 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
2221 } else if (touchSizeCalibrationString != "default") {
2222 LOGW("Invalid value for touch.touchSize.calibration: '%s'",
2223 touchSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002224 }
2225 }
2226
Jeff Brownc6d282b2010-10-14 21:42:15 -07002227 // Tool Size
2228 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_DEFAULT;
2229 String8 toolSizeCalibrationString;
2230 if (in.tryGetProperty(String8("touch.toolSize.calibration"), toolSizeCalibrationString)) {
2231 if (toolSizeCalibrationString == "none") {
2232 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
2233 } else if (toolSizeCalibrationString == "geometric") {
2234 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC;
2235 } else if (toolSizeCalibrationString == "linear") {
2236 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
2237 } else if (toolSizeCalibrationString == "area") {
2238 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_AREA;
2239 } else if (toolSizeCalibrationString != "default") {
2240 LOGW("Invalid value for touch.toolSize.calibration: '%s'",
2241 toolSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002242 }
2243 }
2244
Jeff Brownc6d282b2010-10-14 21:42:15 -07002245 out.haveToolSizeLinearScale = in.tryGetProperty(String8("touch.toolSize.linearScale"),
2246 out.toolSizeLinearScale);
2247 out.haveToolSizeLinearBias = in.tryGetProperty(String8("touch.toolSize.linearBias"),
2248 out.toolSizeLinearBias);
2249 out.haveToolSizeAreaScale = in.tryGetProperty(String8("touch.toolSize.areaScale"),
2250 out.toolSizeAreaScale);
2251 out.haveToolSizeAreaBias = in.tryGetProperty(String8("touch.toolSize.areaBias"),
2252 out.toolSizeAreaBias);
2253 out.haveToolSizeIsSummed = in.tryGetProperty(String8("touch.toolSize.isSummed"),
2254 out.toolSizeIsSummed);
Jeff Brown8d608662010-08-30 03:02:23 -07002255
2256 // Pressure
2257 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
2258 String8 pressureCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002259 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002260 if (pressureCalibrationString == "none") {
2261 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2262 } else if (pressureCalibrationString == "physical") {
2263 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
2264 } else if (pressureCalibrationString == "amplitude") {
2265 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2266 } else if (pressureCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002267 LOGW("Invalid value for touch.pressure.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002268 pressureCalibrationString.string());
2269 }
2270 }
2271
2272 out.pressureSource = Calibration::PRESSURE_SOURCE_DEFAULT;
2273 String8 pressureSourceString;
2274 if (in.tryGetProperty(String8("touch.pressure.source"), pressureSourceString)) {
2275 if (pressureSourceString == "pressure") {
2276 out.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2277 } else if (pressureSourceString == "touch") {
2278 out.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2279 } else if (pressureSourceString != "default") {
2280 LOGW("Invalid value for touch.pressure.source: '%s'",
2281 pressureSourceString.string());
2282 }
2283 }
2284
2285 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
2286 out.pressureScale);
2287
2288 // Size
2289 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
2290 String8 sizeCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002291 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002292 if (sizeCalibrationString == "none") {
2293 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2294 } else if (sizeCalibrationString == "normalized") {
2295 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2296 } else if (sizeCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002297 LOGW("Invalid value for touch.size.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002298 sizeCalibrationString.string());
2299 }
2300 }
2301
2302 // Orientation
2303 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
2304 String8 orientationCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002305 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002306 if (orientationCalibrationString == "none") {
2307 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2308 } else if (orientationCalibrationString == "interpolated") {
2309 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002310 } else if (orientationCalibrationString == "vector") {
2311 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002312 } else if (orientationCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002313 LOGW("Invalid value for touch.orientation.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002314 orientationCalibrationString.string());
2315 }
2316 }
2317}
2318
2319void TouchInputMapper::resolveCalibration() {
2320 // Pressure
2321 switch (mCalibration.pressureSource) {
2322 case Calibration::PRESSURE_SOURCE_DEFAULT:
2323 if (mRawAxes.pressure.valid) {
2324 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2325 } else if (mRawAxes.touchMajor.valid) {
2326 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2327 }
2328 break;
2329
2330 case Calibration::PRESSURE_SOURCE_PRESSURE:
2331 if (! mRawAxes.pressure.valid) {
2332 LOGW("Calibration property touch.pressure.source is 'pressure' but "
2333 "the pressure axis is not available.");
2334 }
2335 break;
2336
2337 case Calibration::PRESSURE_SOURCE_TOUCH:
2338 if (! mRawAxes.touchMajor.valid) {
2339 LOGW("Calibration property touch.pressure.source is 'touch' but "
2340 "the touchMajor axis is not available.");
2341 }
2342 break;
2343
2344 default:
2345 break;
2346 }
2347
2348 switch (mCalibration.pressureCalibration) {
2349 case Calibration::PRESSURE_CALIBRATION_DEFAULT:
2350 if (mCalibration.pressureSource != Calibration::PRESSURE_SOURCE_DEFAULT) {
2351 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2352 } else {
2353 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2354 }
2355 break;
2356
2357 default:
2358 break;
2359 }
2360
Jeff Brownc6d282b2010-10-14 21:42:15 -07002361 // Tool Size
2362 switch (mCalibration.toolSizeCalibration) {
2363 case Calibration::TOOL_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002364 if (mRawAxes.toolMajor.valid) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002365 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
Jeff Brown8d608662010-08-30 03:02:23 -07002366 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002367 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002368 }
2369 break;
2370
2371 default:
2372 break;
2373 }
2374
Jeff Brownc6d282b2010-10-14 21:42:15 -07002375 // Touch Size
2376 switch (mCalibration.touchSizeCalibration) {
2377 case Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002378 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE
Jeff Brownc6d282b2010-10-14 21:42:15 -07002379 && mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2380 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
Jeff Brown8d608662010-08-30 03:02:23 -07002381 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002382 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002383 }
2384 break;
2385
2386 default:
2387 break;
2388 }
2389
2390 // Size
2391 switch (mCalibration.sizeCalibration) {
2392 case Calibration::SIZE_CALIBRATION_DEFAULT:
2393 if (mRawAxes.toolMajor.valid) {
2394 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2395 } else {
2396 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2397 }
2398 break;
2399
2400 default:
2401 break;
2402 }
2403
2404 // Orientation
2405 switch (mCalibration.orientationCalibration) {
2406 case Calibration::ORIENTATION_CALIBRATION_DEFAULT:
2407 if (mRawAxes.orientation.valid) {
2408 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
2409 } else {
2410 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2411 }
2412 break;
2413
2414 default:
2415 break;
2416 }
2417}
2418
Jeff Brownef3d7e82010-09-30 14:33:04 -07002419void TouchInputMapper::dumpCalibration(String8& dump) {
2420 dump.append(INDENT3 "Calibration:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002421
Jeff Brownc6d282b2010-10-14 21:42:15 -07002422 // Touch Size
2423 switch (mCalibration.touchSizeCalibration) {
2424 case Calibration::TOUCH_SIZE_CALIBRATION_NONE:
2425 dump.append(INDENT4 "touch.touchSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002426 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002427 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
2428 dump.append(INDENT4 "touch.touchSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002429 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002430 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
2431 dump.append(INDENT4 "touch.touchSize.calibration: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002432 break;
2433 default:
2434 assert(false);
2435 }
2436
Jeff Brownc6d282b2010-10-14 21:42:15 -07002437 // Tool Size
2438 switch (mCalibration.toolSizeCalibration) {
2439 case Calibration::TOOL_SIZE_CALIBRATION_NONE:
2440 dump.append(INDENT4 "touch.toolSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002441 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002442 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
2443 dump.append(INDENT4 "touch.toolSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002444 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002445 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
2446 dump.append(INDENT4 "touch.toolSize.calibration: linear\n");
2447 break;
2448 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
2449 dump.append(INDENT4 "touch.toolSize.calibration: area\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002450 break;
2451 default:
2452 assert(false);
2453 }
2454
Jeff Brownc6d282b2010-10-14 21:42:15 -07002455 if (mCalibration.haveToolSizeLinearScale) {
2456 dump.appendFormat(INDENT4 "touch.toolSize.linearScale: %0.3f\n",
2457 mCalibration.toolSizeLinearScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002458 }
2459
Jeff Brownc6d282b2010-10-14 21:42:15 -07002460 if (mCalibration.haveToolSizeLinearBias) {
2461 dump.appendFormat(INDENT4 "touch.toolSize.linearBias: %0.3f\n",
2462 mCalibration.toolSizeLinearBias);
Jeff Brown8d608662010-08-30 03:02:23 -07002463 }
2464
Jeff Brownc6d282b2010-10-14 21:42:15 -07002465 if (mCalibration.haveToolSizeAreaScale) {
2466 dump.appendFormat(INDENT4 "touch.toolSize.areaScale: %0.3f\n",
2467 mCalibration.toolSizeAreaScale);
2468 }
2469
2470 if (mCalibration.haveToolSizeAreaBias) {
2471 dump.appendFormat(INDENT4 "touch.toolSize.areaBias: %0.3f\n",
2472 mCalibration.toolSizeAreaBias);
2473 }
2474
2475 if (mCalibration.haveToolSizeIsSummed) {
Jeff Brown1f245102010-11-18 20:53:46 -08002476 dump.appendFormat(INDENT4 "touch.toolSize.isSummed: %s\n",
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002477 toString(mCalibration.toolSizeIsSummed));
Jeff Brown8d608662010-08-30 03:02:23 -07002478 }
2479
2480 // Pressure
2481 switch (mCalibration.pressureCalibration) {
2482 case Calibration::PRESSURE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002483 dump.append(INDENT4 "touch.pressure.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002484 break;
2485 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002486 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002487 break;
2488 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002489 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002490 break;
2491 default:
2492 assert(false);
2493 }
2494
2495 switch (mCalibration.pressureSource) {
2496 case Calibration::PRESSURE_SOURCE_PRESSURE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002497 dump.append(INDENT4 "touch.pressure.source: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002498 break;
2499 case Calibration::PRESSURE_SOURCE_TOUCH:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002500 dump.append(INDENT4 "touch.pressure.source: touch\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002501 break;
2502 case Calibration::PRESSURE_SOURCE_DEFAULT:
2503 break;
2504 default:
2505 assert(false);
2506 }
2507
2508 if (mCalibration.havePressureScale) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07002509 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
2510 mCalibration.pressureScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002511 }
2512
2513 // Size
2514 switch (mCalibration.sizeCalibration) {
2515 case Calibration::SIZE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002516 dump.append(INDENT4 "touch.size.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002517 break;
2518 case Calibration::SIZE_CALIBRATION_NORMALIZED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002519 dump.append(INDENT4 "touch.size.calibration: normalized\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002520 break;
2521 default:
2522 assert(false);
2523 }
2524
2525 // Orientation
2526 switch (mCalibration.orientationCalibration) {
2527 case Calibration::ORIENTATION_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002528 dump.append(INDENT4 "touch.orientation.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002529 break;
2530 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002531 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002532 break;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002533 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
2534 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
2535 break;
Jeff Brown8d608662010-08-30 03:02:23 -07002536 default:
2537 assert(false);
2538 }
2539}
2540
Jeff Brown6d0fec22010-07-23 21:28:06 -07002541void TouchInputMapper::reset() {
2542 // Synthesize touch up event if touch is currently down.
2543 // This will also take care of finishing virtual key processing if needed.
2544 if (mLastTouch.pointerCount != 0) {
2545 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
2546 mCurrentTouch.clear();
2547 syncTouch(when, true);
2548 }
2549
Jeff Brown6328cdc2010-07-29 18:18:33 -07002550 { // acquire lock
2551 AutoMutex _l(mLock);
2552 initializeLocked();
2553 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002554
Jeff Brown6328cdc2010-07-29 18:18:33 -07002555 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002556}
2557
2558void TouchInputMapper::syncTouch(nsecs_t when, bool havePointerIds) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002559 // Preprocess pointer data.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002560 if (mParameters.useBadTouchFilter) {
2561 if (applyBadTouchFilter()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002562 havePointerIds = false;
2563 }
2564 }
2565
Jeff Brown6d0fec22010-07-23 21:28:06 -07002566 if (mParameters.useJumpyTouchFilter) {
2567 if (applyJumpyTouchFilter()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002568 havePointerIds = false;
2569 }
2570 }
2571
2572 if (! havePointerIds) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002573 calculatePointerIds();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002574 }
2575
Jeff Brown6d0fec22010-07-23 21:28:06 -07002576 TouchData temp;
2577 TouchData* savedTouch;
2578 if (mParameters.useAveragingTouchFilter) {
2579 temp.copyFrom(mCurrentTouch);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002580 savedTouch = & temp;
2581
Jeff Brown6d0fec22010-07-23 21:28:06 -07002582 applyAveragingTouchFilter();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002583 } else {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002584 savedTouch = & mCurrentTouch;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002585 }
2586
Jeff Brown56194eb2011-03-02 19:23:13 -08002587 uint32_t policyFlags = 0;
Jeff Brown05dc66a2011-03-02 14:41:58 -08002588 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
Jeff Brownefd32662011-03-08 15:13:06 -08002589 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
2590 // If this is a touch screen, hide the pointer on an initial down.
2591 getContext()->fadePointer();
2592 }
Jeff Brown56194eb2011-03-02 19:23:13 -08002593
2594 // Initial downs on external touch devices should wake the device.
2595 // We don't do this for internal touch screens to prevent them from waking
2596 // up in your pocket.
2597 // TODO: Use the input device configuration to control this behavior more finely.
2598 if (getDevice()->isExternal()) {
2599 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
2600 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08002601 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002602
Jeff Brown05dc66a2011-03-02 14:41:58 -08002603 // Process touches and virtual keys.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002604 TouchResult touchResult = consumeOffScreenTouches(when, policyFlags);
2605 if (touchResult == DISPATCH_TOUCH) {
Jeff Brownefd32662011-03-08 15:13:06 -08002606 suppressSwipeOntoVirtualKeys(when);
Jeff Brown96ad3972011-03-09 17:39:48 -08002607 if (mPointerController != NULL) {
2608 dispatchPointerGestures(when, policyFlags);
2609 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002610 dispatchTouches(when, policyFlags);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002611 }
2612
Jeff Brown6328cdc2010-07-29 18:18:33 -07002613 // Copy current touch to last touch in preparation for the next cycle.
Jeff Brown96ad3972011-03-09 17:39:48 -08002614 // Keep the button state so we can track edge-triggered button state changes.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002615 if (touchResult == DROP_STROKE) {
2616 mLastTouch.clear();
Jeff Brown96ad3972011-03-09 17:39:48 -08002617 mLastTouch.buttonState = savedTouch->buttonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002618 } else {
2619 mLastTouch.copyFrom(*savedTouch);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002620 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002621}
2622
Jeff Brown6d0fec22010-07-23 21:28:06 -07002623TouchInputMapper::TouchResult TouchInputMapper::consumeOffScreenTouches(
2624 nsecs_t when, uint32_t policyFlags) {
2625 int32_t keyEventAction, keyEventFlags;
2626 int32_t keyCode, scanCode, downTime;
2627 TouchResult touchResult;
Jeff Brown349703e2010-06-22 01:27:15 -07002628
Jeff Brown6328cdc2010-07-29 18:18:33 -07002629 { // acquire lock
2630 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002631
Jeff Brown6328cdc2010-07-29 18:18:33 -07002632 // Update surface size and orientation, including virtual key positions.
2633 if (! configureSurfaceLocked()) {
2634 return DROP_STROKE;
2635 }
2636
2637 // Check for virtual key press.
2638 if (mLocked.currentVirtualKey.down) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002639 if (mCurrentTouch.pointerCount == 0) {
2640 // Pointer went up while virtual key was down.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002641 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002642#if DEBUG_VIRTUAL_KEYS
2643 LOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002644 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002645#endif
2646 keyEventAction = AKEY_EVENT_ACTION_UP;
2647 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2648 touchResult = SKIP_TOUCH;
2649 goto DispatchVirtualKey;
2650 }
2651
2652 if (mCurrentTouch.pointerCount == 1) {
2653 int32_t x = mCurrentTouch.pointers[0].x;
2654 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002655 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
2656 if (virtualKey && virtualKey->keyCode == mLocked.currentVirtualKey.keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002657 // Pointer is still within the space of the virtual key.
2658 return SKIP_TOUCH;
2659 }
2660 }
2661
2662 // Pointer left virtual key area or another pointer also went down.
2663 // Send key cancellation and drop the stroke so subsequent motions will be
2664 // considered fresh downs. This is useful when the user swipes away from the
2665 // virtual key area into the main display surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002666 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002667#if DEBUG_VIRTUAL_KEYS
2668 LOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002669 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002670#endif
2671 keyEventAction = AKEY_EVENT_ACTION_UP;
2672 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
2673 | AKEY_EVENT_FLAG_CANCELED;
Jeff Brownc3db8582010-10-20 15:33:38 -07002674
2675 // Check whether the pointer moved inside the display area where we should
2676 // start a new stroke.
2677 int32_t x = mCurrentTouch.pointers[0].x;
2678 int32_t y = mCurrentTouch.pointers[0].y;
2679 if (isPointInsideSurfaceLocked(x, y)) {
2680 mLastTouch.clear();
2681 touchResult = DISPATCH_TOUCH;
2682 } else {
2683 touchResult = DROP_STROKE;
2684 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002685 } else {
2686 if (mCurrentTouch.pointerCount >= 1 && mLastTouch.pointerCount == 0) {
2687 // Pointer just went down. Handle off-screen touches, if needed.
2688 int32_t x = mCurrentTouch.pointers[0].x;
2689 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002690 if (! isPointInsideSurfaceLocked(x, y)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002691 // If exactly one pointer went down, check for virtual key hit.
2692 // Otherwise we will drop the entire stroke.
2693 if (mCurrentTouch.pointerCount == 1) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002694 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002695 if (virtualKey) {
Jeff Brownfe508922011-01-18 15:10:10 -08002696 if (mContext->shouldDropVirtualKey(when, getDevice(),
2697 virtualKey->keyCode, virtualKey->scanCode)) {
2698 return DROP_STROKE;
2699 }
2700
Jeff Brown6328cdc2010-07-29 18:18:33 -07002701 mLocked.currentVirtualKey.down = true;
2702 mLocked.currentVirtualKey.downTime = when;
2703 mLocked.currentVirtualKey.keyCode = virtualKey->keyCode;
2704 mLocked.currentVirtualKey.scanCode = virtualKey->scanCode;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002705#if DEBUG_VIRTUAL_KEYS
2706 LOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002707 mLocked.currentVirtualKey.keyCode,
2708 mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002709#endif
2710 keyEventAction = AKEY_EVENT_ACTION_DOWN;
2711 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM
2712 | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2713 touchResult = SKIP_TOUCH;
2714 goto DispatchVirtualKey;
2715 }
2716 }
2717 return DROP_STROKE;
2718 }
2719 }
2720 return DISPATCH_TOUCH;
2721 }
2722
2723 DispatchVirtualKey:
2724 // Collect remaining state needed to dispatch virtual key.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002725 keyCode = mLocked.currentVirtualKey.keyCode;
2726 scanCode = mLocked.currentVirtualKey.scanCode;
2727 downTime = mLocked.currentVirtualKey.downTime;
2728 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002729
2730 // Dispatch virtual key.
2731 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown0eaf3932010-10-01 14:55:30 -07002732 policyFlags |= POLICY_FLAG_VIRTUAL;
Jeff Brownb6997262010-10-08 22:31:17 -07002733 getDispatcher()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
2734 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
2735 return touchResult;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002736}
2737
Jeff Brownefd32662011-03-08 15:13:06 -08002738void TouchInputMapper::suppressSwipeOntoVirtualKeys(nsecs_t when) {
Jeff Brownfe508922011-01-18 15:10:10 -08002739 // Disable all virtual key touches that happen within a short time interval of the
2740 // most recent touch. The idea is to filter out stray virtual key presses when
2741 // interacting with the touch screen.
2742 //
2743 // Problems we're trying to solve:
2744 //
2745 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
2746 // virtual key area that is implemented by a separate touch panel and accidentally
2747 // triggers a virtual key.
2748 //
2749 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
2750 // area and accidentally triggers a virtual key. This often happens when virtual keys
2751 // are layed out below the screen near to where the on screen keyboard's space bar
2752 // is displayed.
2753 if (mParameters.virtualKeyQuietTime > 0 && mCurrentTouch.pointerCount != 0) {
2754 mContext->disableVirtualKeysUntil(when + mParameters.virtualKeyQuietTime);
2755 }
2756}
2757
Jeff Brown6d0fec22010-07-23 21:28:06 -07002758void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
2759 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
2760 uint32_t lastPointerCount = mLastTouch.pointerCount;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002761 if (currentPointerCount == 0 && lastPointerCount == 0) {
2762 return; // nothing to do!
2763 }
2764
Jeff Brown96ad3972011-03-09 17:39:48 -08002765 // Update current touch coordinates.
2766 int32_t edgeFlags;
2767 float xPrecision, yPrecision;
2768 prepareTouches(&edgeFlags, &xPrecision, &yPrecision);
2769
2770 // Dispatch motions.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002771 BitSet32 currentIdBits = mCurrentTouch.idBits;
2772 BitSet32 lastIdBits = mLastTouch.idBits;
Jeff Brown96ad3972011-03-09 17:39:48 -08002773 uint32_t metaState = getContext()->getGlobalMetaState();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002774
2775 if (currentIdBits == lastIdBits) {
2776 // No pointer id changes so this is a move event.
2777 // The dispatcher takes care of batching moves so we don't have to deal with that here.
Jeff Brown96ad3972011-03-09 17:39:48 -08002778 dispatchMotion(when, policyFlags, mTouchSource,
2779 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
2780 mCurrentTouchCoords, mCurrentTouch.idToIndex, currentIdBits, -1,
2781 xPrecision, yPrecision, mDownTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002782 } else {
Jeff Brownc3db8582010-10-20 15:33:38 -07002783 // There may be pointers going up and pointers going down and pointers moving
2784 // all at the same time.
Jeff Brown96ad3972011-03-09 17:39:48 -08002785 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2786 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002787 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
Jeff Brown96ad3972011-03-09 17:39:48 -08002788 BitSet32 dispatchedIdBits(lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002789
Jeff Brown96ad3972011-03-09 17:39:48 -08002790 // Update last coordinates of pointers that have moved so that we observe the new
2791 // pointer positions at the same time as other pointers that have just gone up.
2792 bool moveNeeded = updateMovedPointerCoords(
2793 mCurrentTouchCoords, mCurrentTouch.idToIndex,
2794 mLastTouchCoords, mLastTouch.idToIndex,
2795 moveIdBits);
Jeff Brownc3db8582010-10-20 15:33:38 -07002796
Jeff Brown96ad3972011-03-09 17:39:48 -08002797 // Dispatch pointer up events.
Jeff Brownc3db8582010-10-20 15:33:38 -07002798 while (!upIdBits.isEmpty()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002799 uint32_t upId = upIdBits.firstMarkedBit();
2800 upIdBits.clearBit(upId);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002801
Jeff Brown96ad3972011-03-09 17:39:48 -08002802 dispatchMotion(when, policyFlags, mTouchSource,
2803 AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, 0,
2804 mLastTouchCoords, mLastTouch.idToIndex, dispatchedIdBits, upId,
2805 xPrecision, yPrecision, mDownTime);
2806 dispatchedIdBits.clearBit(upId);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002807 }
2808
Jeff Brownc3db8582010-10-20 15:33:38 -07002809 // Dispatch move events if any of the remaining pointers moved from their old locations.
2810 // Although applications receive new locations as part of individual pointer up
2811 // events, they do not generally handle them except when presented in a move event.
2812 if (moveNeeded) {
Jeff Brown96ad3972011-03-09 17:39:48 -08002813 assert(moveIdBits.value == dispatchedIdBits.value);
2814 dispatchMotion(when, policyFlags, mTouchSource,
2815 AMOTION_EVENT_ACTION_MOVE, 0, metaState, 0,
2816 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, -1,
2817 xPrecision, yPrecision, mDownTime);
Jeff Brownc3db8582010-10-20 15:33:38 -07002818 }
2819
2820 // Dispatch pointer down events using the new pointer locations.
2821 while (!downIdBits.isEmpty()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002822 uint32_t downId = downIdBits.firstMarkedBit();
2823 downIdBits.clearBit(downId);
Jeff Brown96ad3972011-03-09 17:39:48 -08002824 dispatchedIdBits.markBit(downId);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002825
Jeff Brown96ad3972011-03-09 17:39:48 -08002826 if (dispatchedIdBits.count() == 1) {
2827 // First pointer is going down. Set down time.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002828 mDownTime = when;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002829 } else {
Jeff Brown96ad3972011-03-09 17:39:48 -08002830 // Only send edge flags with first pointer down.
2831 edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002832 }
2833
Jeff Brown96ad3972011-03-09 17:39:48 -08002834 dispatchMotion(when, policyFlags, mTouchSource,
2835 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
2836 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, downId,
2837 xPrecision, yPrecision, mDownTime);
2838 }
2839 }
2840
2841 // Update state for next time.
2842 for (uint32_t i = 0; i < currentPointerCount; i++) {
2843 mLastTouchCoords[i].copyFrom(mCurrentTouchCoords[i]);
2844 }
2845}
2846
2847void TouchInputMapper::prepareTouches(int32_t* outEdgeFlags,
2848 float* outXPrecision, float* outYPrecision) {
2849 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
2850 uint32_t lastPointerCount = mLastTouch.pointerCount;
2851
2852 AutoMutex _l(mLock);
2853
2854 // Walk through the the active pointers and map touch screen coordinates (TouchData) into
2855 // display or surface coordinates (PointerCoords) and adjust for display orientation.
2856 for (uint32_t i = 0; i < currentPointerCount; i++) {
2857 const PointerData& in = mCurrentTouch.pointers[i];
2858
2859 // ToolMajor and ToolMinor
2860 float toolMajor, toolMinor;
2861 switch (mCalibration.toolSizeCalibration) {
2862 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
2863 toolMajor = in.toolMajor * mLocked.geometricScale;
2864 if (mRawAxes.toolMinor.valid) {
2865 toolMinor = in.toolMinor * mLocked.geometricScale;
2866 } else {
2867 toolMinor = toolMajor;
2868 }
2869 break;
2870 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
2871 toolMajor = in.toolMajor != 0
2872 ? in.toolMajor * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias
2873 : 0;
2874 if (mRawAxes.toolMinor.valid) {
2875 toolMinor = in.toolMinor != 0
2876 ? in.toolMinor * mLocked.toolSizeLinearScale
2877 + mLocked.toolSizeLinearBias
2878 : 0;
2879 } else {
2880 toolMinor = toolMajor;
2881 }
2882 break;
2883 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
2884 if (in.toolMajor != 0) {
2885 float diameter = sqrtf(in.toolMajor
2886 * mLocked.toolSizeAreaScale + mLocked.toolSizeAreaBias);
2887 toolMajor = diameter * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias;
2888 } else {
2889 toolMajor = 0;
2890 }
2891 toolMinor = toolMajor;
2892 break;
2893 default:
2894 toolMajor = 0;
2895 toolMinor = 0;
2896 break;
2897 }
2898
2899 if (mCalibration.haveToolSizeIsSummed && mCalibration.toolSizeIsSummed) {
2900 toolMajor /= currentPointerCount;
2901 toolMinor /= currentPointerCount;
2902 }
2903
2904 // Pressure
2905 float rawPressure;
2906 switch (mCalibration.pressureSource) {
2907 case Calibration::PRESSURE_SOURCE_PRESSURE:
2908 rawPressure = in.pressure;
2909 break;
2910 case Calibration::PRESSURE_SOURCE_TOUCH:
2911 rawPressure = in.touchMajor;
2912 break;
2913 default:
2914 rawPressure = 0;
2915 }
2916
2917 float pressure;
2918 switch (mCalibration.pressureCalibration) {
2919 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
2920 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
2921 pressure = rawPressure * mLocked.pressureScale;
2922 break;
2923 default:
2924 pressure = 1;
2925 break;
2926 }
2927
2928 // TouchMajor and TouchMinor
2929 float touchMajor, touchMinor;
2930 switch (mCalibration.touchSizeCalibration) {
2931 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
2932 touchMajor = in.touchMajor * mLocked.geometricScale;
2933 if (mRawAxes.touchMinor.valid) {
2934 touchMinor = in.touchMinor * mLocked.geometricScale;
2935 } else {
2936 touchMinor = touchMajor;
2937 }
2938 break;
2939 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
2940 touchMajor = toolMajor * pressure;
2941 touchMinor = toolMinor * pressure;
2942 break;
2943 default:
2944 touchMajor = 0;
2945 touchMinor = 0;
2946 break;
2947 }
2948
2949 if (touchMajor > toolMajor) {
2950 touchMajor = toolMajor;
2951 }
2952 if (touchMinor > toolMinor) {
2953 touchMinor = toolMinor;
2954 }
2955
2956 // Size
2957 float size;
2958 switch (mCalibration.sizeCalibration) {
2959 case Calibration::SIZE_CALIBRATION_NORMALIZED: {
2960 float rawSize = mRawAxes.toolMinor.valid
2961 ? avg(in.toolMajor, in.toolMinor)
2962 : in.toolMajor;
2963 size = rawSize * mLocked.sizeScale;
2964 break;
2965 }
2966 default:
2967 size = 0;
2968 break;
2969 }
2970
2971 // Orientation
2972 float orientation;
2973 switch (mCalibration.orientationCalibration) {
2974 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
2975 orientation = in.orientation * mLocked.orientationScale;
2976 break;
2977 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
2978 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2979 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2980 if (c1 != 0 || c2 != 0) {
2981 orientation = atan2f(c1, c2) * 0.5f;
2982 float scale = 1.0f + pythag(c1, c2) / 16.0f;
2983 touchMajor *= scale;
2984 touchMinor /= scale;
2985 toolMajor *= scale;
2986 toolMinor /= scale;
2987 } else {
2988 orientation = 0;
2989 }
2990 break;
2991 }
2992 default:
2993 orientation = 0;
2994 }
2995
2996 // X and Y
2997 // Adjust coords for surface orientation.
2998 float x, y;
2999 switch (mLocked.surfaceOrientation) {
3000 case DISPLAY_ORIENTATION_90:
3001 x = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3002 y = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3003 orientation -= M_PI_2;
3004 if (orientation < - M_PI_2) {
3005 orientation += M_PI;
3006 }
3007 break;
3008 case DISPLAY_ORIENTATION_180:
3009 x = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3010 y = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3011 break;
3012 case DISPLAY_ORIENTATION_270:
3013 x = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3014 y = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3015 orientation += M_PI_2;
3016 if (orientation > M_PI_2) {
3017 orientation -= M_PI;
3018 }
3019 break;
3020 default:
3021 x = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3022 y = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3023 break;
3024 }
3025
3026 // Write output coords.
3027 PointerCoords& out = mCurrentTouchCoords[i];
3028 out.clear();
3029 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3030 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3031 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
3032 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
3033 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
3034 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
3035 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
3036 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
3037 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
3038 }
3039
3040 // Check edge flags by looking only at the first pointer since the flags are
3041 // global to the event.
3042 *outEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3043 if (lastPointerCount == 0 && currentPointerCount > 0) {
3044 const PointerData& in = mCurrentTouch.pointers[0];
3045
3046 if (in.x <= mRawAxes.x.minValue) {
3047 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_LEFT,
3048 mLocked.surfaceOrientation);
3049 } else if (in.x >= mRawAxes.x.maxValue) {
3050 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_RIGHT,
3051 mLocked.surfaceOrientation);
3052 }
3053 if (in.y <= mRawAxes.y.minValue) {
3054 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_TOP,
3055 mLocked.surfaceOrientation);
3056 } else if (in.y >= mRawAxes.y.maxValue) {
3057 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_BOTTOM,
3058 mLocked.surfaceOrientation);
3059 }
3060 }
3061
3062 *outXPrecision = mLocked.orientedXPrecision;
3063 *outYPrecision = mLocked.orientedYPrecision;
3064}
3065
3066void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags) {
3067 // Update current gesture coordinates.
3068 bool cancelPreviousGesture, finishPreviousGesture;
3069 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture);
3070
3071 // Send events!
3072 uint32_t metaState = getContext()->getGlobalMetaState();
3073
3074 // Update last coordinates of pointers that have moved so that we observe the new
3075 // pointer positions at the same time as other pointers that have just gone up.
3076 bool down = mPointerGesture.currentGestureMode == PointerGesture::CLICK_OR_DRAG
3077 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
3078 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
3079 bool moveNeeded = false;
3080 if (down && !cancelPreviousGesture && !finishPreviousGesture
3081 && mPointerGesture.lastGesturePointerCount != 0
3082 && mPointerGesture.currentGesturePointerCount != 0) {
3083 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
3084 & mPointerGesture.lastGestureIdBits.value);
3085 moveNeeded = updateMovedPointerCoords(
3086 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3087 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3088 movedGestureIdBits);
3089 }
3090
3091 // Send motion events for all pointers that went up or were canceled.
3092 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
3093 if (!dispatchedGestureIdBits.isEmpty()) {
3094 if (cancelPreviousGesture) {
3095 dispatchMotion(when, policyFlags, mPointerSource,
3096 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3097 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3098 dispatchedGestureIdBits, -1,
3099 0, 0, mPointerGesture.downTime);
3100
3101 dispatchedGestureIdBits.clear();
3102 } else {
3103 BitSet32 upGestureIdBits;
3104 if (finishPreviousGesture) {
3105 upGestureIdBits = dispatchedGestureIdBits;
3106 } else {
3107 upGestureIdBits.value = dispatchedGestureIdBits.value
3108 & ~mPointerGesture.currentGestureIdBits.value;
3109 }
3110 while (!upGestureIdBits.isEmpty()) {
3111 uint32_t id = upGestureIdBits.firstMarkedBit();
3112 upGestureIdBits.clearBit(id);
3113
3114 dispatchMotion(when, policyFlags, mPointerSource,
3115 AMOTION_EVENT_ACTION_POINTER_UP, 0,
3116 metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3117 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3118 dispatchedGestureIdBits, id,
3119 0, 0, mPointerGesture.downTime);
3120
3121 dispatchedGestureIdBits.clearBit(id);
3122 }
3123 }
3124 }
3125
3126 // Send motion events for all pointers that moved.
3127 if (moveNeeded) {
3128 dispatchMotion(when, policyFlags, mPointerSource,
3129 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3130 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3131 dispatchedGestureIdBits, -1,
3132 0, 0, mPointerGesture.downTime);
3133 }
3134
3135 // Send motion events for all pointers that went down.
3136 if (down) {
3137 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
3138 & ~dispatchedGestureIdBits.value);
3139 while (!downGestureIdBits.isEmpty()) {
3140 uint32_t id = downGestureIdBits.firstMarkedBit();
3141 downGestureIdBits.clearBit(id);
3142 dispatchedGestureIdBits.markBit(id);
3143
3144 int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3145 if (dispatchedGestureIdBits.count() == 1) {
3146 // First pointer is going down. Calculate edge flags and set down time.
3147 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3148 const PointerCoords& downCoords = mPointerGesture.currentGestureCoords[index];
3149 edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3150 downCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
3151 downCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3152 mPointerGesture.downTime = when;
3153 }
3154
3155 dispatchMotion(when, policyFlags, mPointerSource,
3156 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
3157 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3158 dispatchedGestureIdBits, id,
3159 0, 0, mPointerGesture.downTime);
3160 }
3161 }
3162
3163 // Send down and up for a tap.
3164 if (mPointerGesture.currentGestureMode == PointerGesture::TAP) {
3165 const PointerCoords& coords = mPointerGesture.currentGestureCoords[0];
3166 int32_t edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3167 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3168 coords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3169 nsecs_t downTime = mPointerGesture.downTime = mPointerGesture.tapTime;
3170 mPointerGesture.resetTapTime();
3171
3172 dispatchMotion(downTime, policyFlags, mPointerSource,
3173 AMOTION_EVENT_ACTION_DOWN, 0, metaState, edgeFlags,
3174 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3175 mPointerGesture.currentGestureIdBits, -1,
3176 0, 0, downTime);
3177 dispatchMotion(when, policyFlags, mPointerSource,
3178 AMOTION_EVENT_ACTION_UP, 0, metaState, edgeFlags,
3179 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3180 mPointerGesture.currentGestureIdBits, -1,
3181 0, 0, downTime);
3182 }
3183
3184 // Send motion events for hover.
3185 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
3186 dispatchMotion(when, policyFlags, mPointerSource,
3187 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3188 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3189 mPointerGesture.currentGestureIdBits, -1,
3190 0, 0, mPointerGesture.downTime);
3191 }
3192
3193 // Update state.
3194 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
3195 if (!down) {
3196 mPointerGesture.lastGesturePointerCount = 0;
3197 mPointerGesture.lastGestureIdBits.clear();
3198 } else {
3199 uint32_t currentGesturePointerCount = mPointerGesture.currentGesturePointerCount;
3200 mPointerGesture.lastGesturePointerCount = currentGesturePointerCount;
3201 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
3202 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
3203 uint32_t id = idBits.firstMarkedBit();
3204 idBits.clearBit(id);
3205 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3206 mPointerGesture.lastGestureCoords[index].copyFrom(
3207 mPointerGesture.currentGestureCoords[index]);
3208 mPointerGesture.lastGestureIdToIndex[id] = index;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003209 }
3210 }
3211}
3212
Jeff Brown96ad3972011-03-09 17:39:48 -08003213void TouchInputMapper::preparePointerGestures(nsecs_t when,
3214 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture) {
3215 *outCancelPreviousGesture = false;
3216 *outFinishPreviousGesture = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003217
Jeff Brown96ad3972011-03-09 17:39:48 -08003218 AutoMutex _l(mLock);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003219
Jeff Brown96ad3972011-03-09 17:39:48 -08003220 // Update the velocity tracker.
3221 {
3222 VelocityTracker::Position positions[MAX_POINTERS];
3223 uint32_t count = 0;
3224 for (BitSet32 idBits(mCurrentTouch.idBits); !idBits.isEmpty(); count++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07003225 uint32_t id = idBits.firstMarkedBit();
3226 idBits.clearBit(id);
Jeff Brown96ad3972011-03-09 17:39:48 -08003227 uint32_t index = mCurrentTouch.idToIndex[id];
3228 positions[count].x = mCurrentTouch.pointers[index].x
3229 * mLocked.pointerGestureXMovementScale;
3230 positions[count].y = mCurrentTouch.pointers[index].y
3231 * mLocked.pointerGestureYMovementScale;
3232 }
3233 mPointerGesture.velocityTracker.addMovement(when, mCurrentTouch.idBits, positions);
3234 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003235
Jeff Brown96ad3972011-03-09 17:39:48 -08003236 // Pick a new active touch id if needed.
3237 // Choose an arbitrary pointer that just went down, if there is one.
3238 // Otherwise choose an arbitrary remaining pointer.
3239 // This guarantees we always have an active touch id when there is at least one pointer.
3240 // We always switch to the newest pointer down because that's usually where the user's
3241 // attention is focused.
3242 int32_t activeTouchId;
3243 BitSet32 downTouchIdBits(mCurrentTouch.idBits.value & ~mLastTouch.idBits.value);
3244 if (!downTouchIdBits.isEmpty()) {
3245 activeTouchId = mPointerGesture.activeTouchId = downTouchIdBits.firstMarkedBit();
3246 } else {
3247 activeTouchId = mPointerGesture.activeTouchId;
3248 if (activeTouchId < 0 || !mCurrentTouch.idBits.hasBit(activeTouchId)) {
3249 if (!mCurrentTouch.idBits.isEmpty()) {
3250 activeTouchId = mPointerGesture.activeTouchId =
3251 mCurrentTouch.idBits.firstMarkedBit();
3252 } else {
3253 activeTouchId = mPointerGesture.activeTouchId = -1;
3254 }
3255 }
3256 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003257
Jeff Brown96ad3972011-03-09 17:39:48 -08003258 // Update the touch origin data to track where each finger originally went down.
3259 if (mCurrentTouch.pointerCount == 0 || mPointerGesture.touchOrigin.pointerCount == 0) {
3260 // Fast path when all fingers have gone up or down.
3261 mPointerGesture.touchOrigin.copyFrom(mCurrentTouch);
3262 } else {
3263 // Slow path when only some fingers have gone up or down.
3264 for (BitSet32 idBits(mPointerGesture.touchOrigin.idBits.value
3265 & ~mCurrentTouch.idBits.value); !idBits.isEmpty(); ) {
3266 uint32_t id = idBits.firstMarkedBit();
3267 idBits.clearBit(id);
3268 mPointerGesture.touchOrigin.idBits.clearBit(id);
3269 uint32_t index = mPointerGesture.touchOrigin.idToIndex[id];
3270 uint32_t count = --mPointerGesture.touchOrigin.pointerCount;
3271 while (index < count) {
3272 mPointerGesture.touchOrigin.pointers[index] =
3273 mPointerGesture.touchOrigin.pointers[index + 1];
3274 uint32_t movedId = mPointerGesture.touchOrigin.pointers[index].id;
3275 mPointerGesture.touchOrigin.idToIndex[movedId] = index;
3276 index += 1;
3277 }
3278 }
3279 for (BitSet32 idBits(mCurrentTouch.idBits.value
3280 & ~mPointerGesture.touchOrigin.idBits.value); !idBits.isEmpty(); ) {
3281 uint32_t id = idBits.firstMarkedBit();
3282 idBits.clearBit(id);
3283 mPointerGesture.touchOrigin.idBits.markBit(id);
3284 uint32_t index = mPointerGesture.touchOrigin.pointerCount++;
3285 mPointerGesture.touchOrigin.pointers[index] =
3286 mCurrentTouch.pointers[mCurrentTouch.idToIndex[id]];
3287 mPointerGesture.touchOrigin.idToIndex[id] = index;
3288 }
3289 }
3290
3291 // Determine whether we are in quiet time.
3292 bool isQuietTime = when < mPointerGesture.quietTime + QUIET_INTERVAL;
3293 if (!isQuietTime) {
3294 if ((mPointerGesture.lastGestureMode == PointerGesture::SWIPE
3295 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
3296 && mCurrentTouch.pointerCount < 2) {
3297 // Enter quiet time when exiting swipe or freeform state.
3298 // This is to prevent accidentally entering the hover state and flinging the
3299 // pointer when finishing a swipe and there is still one pointer left onscreen.
3300 isQuietTime = true;
3301 } else if (mPointerGesture.lastGestureMode == PointerGesture::CLICK_OR_DRAG
3302 && mCurrentTouch.pointerCount >= 2
3303 && !isPointerDown(mCurrentTouch.buttonState)) {
3304 // Enter quiet time when releasing the button and there are still two or more
3305 // fingers down. This may indicate that one finger was used to press the button
3306 // but it has not gone up yet.
3307 isQuietTime = true;
3308 }
3309 if (isQuietTime) {
3310 mPointerGesture.quietTime = when;
3311 }
3312 }
3313
3314 // Switch states based on button and pointer state.
3315 if (isQuietTime) {
3316 // Case 1: Quiet time. (QUIET)
3317#if DEBUG_GESTURES
3318 LOGD("Gestures: QUIET for next %0.3fms",
3319 (mPointerGesture.quietTime + QUIET_INTERVAL - when) * 0.000001f);
3320#endif
3321 *outFinishPreviousGesture = true;
3322
3323 mPointerGesture.activeGestureId = -1;
3324 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
3325 mPointerGesture.currentGesturePointerCount = 0;
3326 mPointerGesture.currentGestureIdBits.clear();
3327 } else if (isPointerDown(mCurrentTouch.buttonState)) {
3328 // Case 2: Button is pressed. (DRAG)
3329 // The pointer follows the active touch point.
3330 // Emit DOWN, MOVE, UP events at the pointer location.
3331 //
3332 // Only the active touch matters; other fingers are ignored. This policy helps
3333 // to handle the case where the user places a second finger on the touch pad
3334 // to apply the necessary force to depress an integrated button below the surface.
3335 // We don't want the second finger to be delivered to applications.
3336 //
3337 // For this to work well, we need to make sure to track the pointer that is really
3338 // active. If the user first puts one finger down to click then adds another
3339 // finger to drag then the active pointer should switch to the finger that is
3340 // being dragged.
3341#if DEBUG_GESTURES
3342 LOGD("Gestures: CLICK_OR_DRAG activeTouchId=%d, "
3343 "currentTouchPointerCount=%d", activeTouchId, mCurrentTouch.pointerCount);
3344#endif
3345 // Reset state when just starting.
3346 if (mPointerGesture.lastGestureMode != PointerGesture::CLICK_OR_DRAG) {
3347 *outFinishPreviousGesture = true;
3348 mPointerGesture.activeGestureId = 0;
3349 }
3350
3351 // Switch pointers if needed.
3352 // Find the fastest pointer and follow it.
3353 if (activeTouchId >= 0) {
3354 if (mCurrentTouch.pointerCount > 1) {
3355 int32_t bestId = -1;
3356 float bestSpeed = DRAG_MIN_SWITCH_SPEED;
3357 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3358 uint32_t id = mCurrentTouch.pointers[i].id;
3359 float vx, vy;
3360 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
3361 float speed = pythag(vx, vy);
3362 if (speed > bestSpeed) {
3363 bestId = id;
3364 bestSpeed = speed;
3365 }
3366 }
Jeff Brown8d608662010-08-30 03:02:23 -07003367 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003368 if (bestId >= 0 && bestId != activeTouchId) {
3369 mPointerGesture.activeTouchId = activeTouchId = bestId;
3370#if DEBUG_GESTURES
3371 LOGD("Gestures: CLICK_OR_DRAG switched pointers, "
3372 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
3373#endif
Jeff Brown8d608662010-08-30 03:02:23 -07003374 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003375 }
3376
Jeff Brown96ad3972011-03-09 17:39:48 -08003377 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3378 const PointerData& currentPointer =
3379 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3380 const PointerData& lastPointer =
3381 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3382 float deltaX = (currentPointer.x - lastPointer.x)
3383 * mLocked.pointerGestureXMovementScale;
3384 float deltaY = (currentPointer.y - lastPointer.y)
3385 * mLocked.pointerGestureYMovementScale;
3386 mPointerController->move(deltaX, deltaY);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003387 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003388 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003389
Jeff Brown96ad3972011-03-09 17:39:48 -08003390 float x, y;
3391 mPointerController->getPosition(&x, &y);
Jeff Brown91c69ab2011-02-14 17:03:18 -08003392
Jeff Brown96ad3972011-03-09 17:39:48 -08003393 mPointerGesture.currentGestureMode = PointerGesture::CLICK_OR_DRAG;
3394 mPointerGesture.currentGesturePointerCount = 1;
3395 mPointerGesture.currentGestureIdBits.clear();
3396 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3397 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3398 mPointerGesture.currentGestureCoords[0].clear();
3399 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3400 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3401 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3402 } else if (mCurrentTouch.pointerCount == 0) {
3403 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
3404 *outFinishPreviousGesture = true;
3405
3406 // Watch for taps coming out of HOVER or INDETERMINATE_MULTITOUCH mode.
3407 bool tapped = false;
3408 if (mPointerGesture.lastGestureMode == PointerGesture::HOVER
3409 || mPointerGesture.lastGestureMode
3410 == PointerGesture::INDETERMINATE_MULTITOUCH) {
3411 if (when <= mPointerGesture.tapTime + TAP_INTERVAL) {
3412 float x, y;
3413 mPointerController->getPosition(&x, &y);
3414 if (fabs(x - mPointerGesture.initialPointerX) <= TAP_SLOP
3415 && fabs(y - mPointerGesture.initialPointerY) <= TAP_SLOP) {
3416#if DEBUG_GESTURES
3417 LOGD("Gestures: TAP");
3418#endif
3419 mPointerGesture.activeGestureId = 0;
3420 mPointerGesture.currentGestureMode = PointerGesture::TAP;
3421 mPointerGesture.currentGesturePointerCount = 1;
3422 mPointerGesture.currentGestureIdBits.clear();
3423 mPointerGesture.currentGestureIdBits.markBit(
3424 mPointerGesture.activeGestureId);
3425 mPointerGesture.currentGestureIdToIndex[
3426 mPointerGesture.activeGestureId] = 0;
3427 mPointerGesture.currentGestureCoords[0].clear();
3428 mPointerGesture.currentGestureCoords[0].setAxisValue(
3429 AMOTION_EVENT_AXIS_X, mPointerGesture.initialPointerX);
3430 mPointerGesture.currentGestureCoords[0].setAxisValue(
3431 AMOTION_EVENT_AXIS_Y, mPointerGesture.initialPointerY);
3432 mPointerGesture.currentGestureCoords[0].setAxisValue(
3433 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3434 tapped = true;
3435 } else {
3436#if DEBUG_GESTURES
3437 LOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
3438 x - mPointerGesture.initialPointerX,
3439 y - mPointerGesture.initialPointerY);
3440#endif
3441 }
3442 } else {
3443#if DEBUG_GESTURES
3444 LOGD("Gestures: Not a TAP, delay=%lld",
3445 when - mPointerGesture.tapTime);
3446#endif
Jeff Brown6328cdc2010-07-29 18:18:33 -07003447 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003448 }
3449 if (!tapped) {
3450#if DEBUG_GESTURES
3451 LOGD("Gestures: NEUTRAL");
3452#endif
3453 mPointerGesture.activeGestureId = -1;
3454 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
3455 mPointerGesture.currentGesturePointerCount = 0;
3456 mPointerGesture.currentGestureIdBits.clear();
3457 }
3458 } else if (mCurrentTouch.pointerCount == 1) {
3459 // Case 4. Exactly one finger down, button is not pressed. (HOVER)
3460 // The pointer follows the active touch point.
3461 // Emit HOVER_MOVE events at the pointer location.
3462 assert(activeTouchId >= 0);
3463
3464#if DEBUG_GESTURES
3465 LOGD("Gestures: HOVER");
3466#endif
3467
3468 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3469 const PointerData& currentPointer =
3470 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3471 const PointerData& lastPointer =
3472 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3473 float deltaX = (currentPointer.x - lastPointer.x)
3474 * mLocked.pointerGestureXMovementScale;
3475 float deltaY = (currentPointer.y - lastPointer.y)
3476 * mLocked.pointerGestureYMovementScale;
3477 mPointerController->move(deltaX, deltaY);
3478 }
3479
3480 *outFinishPreviousGesture = true;
3481 mPointerGesture.activeGestureId = 0;
3482
3483 float x, y;
3484 mPointerController->getPosition(&x, &y);
3485
3486 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
3487 mPointerGesture.currentGesturePointerCount = 1;
3488 mPointerGesture.currentGestureIdBits.clear();
3489 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3490 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3491 mPointerGesture.currentGestureCoords[0].clear();
3492 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3493 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3494 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 0.0f);
3495
3496 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
3497 mPointerGesture.tapTime = when;
3498 mPointerGesture.initialPointerX = x;
3499 mPointerGesture.initialPointerY = y;
3500 }
3501 } else {
3502 // Case 5. At least two fingers down, button is not pressed. (SWIPE or FREEFORM
3503 // or INDETERMINATE_MULTITOUCH)
3504 // Initially we watch and wait for something interesting to happen so as to
3505 // avoid making a spurious guess as to the nature of the gesture. For example,
3506 // the fingers may be in transition to some other state such as pressing or
3507 // releasing the button or we may be performing a two finger tap.
3508 //
3509 // Fix the centroid of the figure when the gesture actually starts.
3510 // We do not recalculate the centroid at any other time during the gesture because
3511 // it would affect the relationship of the touch points relative to the pointer location.
3512 assert(activeTouchId >= 0);
3513
3514 uint32_t currentTouchPointerCount = mCurrentTouch.pointerCount;
3515 if (currentTouchPointerCount > MAX_POINTERS) {
3516 currentTouchPointerCount = MAX_POINTERS;
3517 }
3518
3519 if (mPointerGesture.lastGestureMode != PointerGesture::INDETERMINATE_MULTITOUCH
3520 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
3521 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
3522 mPointerGesture.currentGestureMode = PointerGesture::INDETERMINATE_MULTITOUCH;
3523
3524 *outFinishPreviousGesture = true;
3525 mPointerGesture.activeGestureId = -1;
3526
3527 // Remember the initial pointer location.
3528 // Everything we do will be relative to this location.
3529 mPointerController->getPosition(&mPointerGesture.initialPointerX,
3530 &mPointerGesture.initialPointerY);
3531
3532 // Track taps.
3533 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
3534 mPointerGesture.tapTime = when;
3535 }
3536
3537 // Reset the touch origin to be relative to exactly where the fingers are now
3538 // in case they have moved some distance away as part of a previous gesture.
3539 // We want to know how far the fingers have traveled since we started considering
3540 // a multitouch gesture.
3541 mPointerGesture.touchOrigin.copyFrom(mCurrentTouch);
3542 } else {
3543 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3544 }
3545
3546 if (mPointerGesture.currentGestureMode == PointerGesture::INDETERMINATE_MULTITOUCH) {
3547 // Wait for the pointers to start moving before doing anything.
3548 bool decideNow = true;
3549 for (uint32_t i = 0; i < currentTouchPointerCount; i++) {
3550 const PointerData& current = mCurrentTouch.pointers[i];
3551 const PointerData& origin = mPointerGesture.touchOrigin.pointers[
3552 mPointerGesture.touchOrigin.idToIndex[current.id]];
3553 float distance = pythag(
3554 (current.x - origin.x) * mLocked.pointerGestureXZoomScale,
3555 (current.y - origin.y) * mLocked.pointerGestureYZoomScale);
3556 if (distance < MULTITOUCH_MIN_TRAVEL) {
3557 decideNow = false;
3558 break;
3559 }
3560 }
3561
3562 if (decideNow) {
3563 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
3564 if (currentTouchPointerCount == 2
3565 && distanceSquared(
3566 mCurrentTouch.pointers[0].x, mCurrentTouch.pointers[0].y,
3567 mCurrentTouch.pointers[1].x, mCurrentTouch.pointers[1].y)
3568 <= mLocked.pointerGestureMaxSwipeWidthSquared) {
3569 const PointerData& current1 = mCurrentTouch.pointers[0];
3570 const PointerData& current2 = mCurrentTouch.pointers[1];
3571 const PointerData& origin1 = mPointerGesture.touchOrigin.pointers[
3572 mPointerGesture.touchOrigin.idToIndex[current1.id]];
3573 const PointerData& origin2 = mPointerGesture.touchOrigin.pointers[
3574 mPointerGesture.touchOrigin.idToIndex[current2.id]];
3575
3576 float x1 = (current1.x - origin1.x) * mLocked.pointerGestureXZoomScale;
3577 float y1 = (current1.y - origin1.y) * mLocked.pointerGestureYZoomScale;
3578 float x2 = (current2.x - origin2.x) * mLocked.pointerGestureXZoomScale;
3579 float y2 = (current2.y - origin2.y) * mLocked.pointerGestureYZoomScale;
3580 float magnitude1 = pythag(x1, y1);
3581 float magnitude2 = pythag(x2, y2);
3582
3583 // Calculate the dot product of the vectors.
3584 // When the vectors are oriented in approximately the same direction,
3585 // the angle betweeen them is near zero and the cosine of the angle
3586 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
3587 // We know that the magnitude is at least MULTITOUCH_MIN_TRAVEL because
3588 // we checked it above.
3589 float dot = x1 * x2 + y1 * y2;
3590 float cosine = dot / (magnitude1 * magnitude2); // denominator always > 0
3591 if (cosine > SWIPE_TRANSITION_ANGLE_COSINE) {
3592 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
3593 }
3594 }
3595
3596 // Remember the initial centroid for the duration of the gesture.
3597 mPointerGesture.initialCentroidX = 0;
3598 mPointerGesture.initialCentroidY = 0;
3599 for (uint32_t i = 0; i < currentTouchPointerCount; i++) {
3600 const PointerData& touch = mCurrentTouch.pointers[i];
3601 mPointerGesture.initialCentroidX += touch.x;
3602 mPointerGesture.initialCentroidY += touch.y;
3603 }
3604 mPointerGesture.initialCentroidX /= int32_t(currentTouchPointerCount);
3605 mPointerGesture.initialCentroidY /= int32_t(currentTouchPointerCount);
3606
3607 mPointerGesture.activeGestureId = 0;
3608 }
3609 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
3610 // Switch to FREEFORM if additional pointers go down.
3611 if (currentTouchPointerCount > 2) {
3612 *outCancelPreviousGesture = true;
3613 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003614 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003615 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003616
Jeff Brown96ad3972011-03-09 17:39:48 -08003617 if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
3618 // SWIPE mode.
3619#if DEBUG_GESTURES
3620 LOGD("Gestures: SWIPE activeTouchId=%d,"
3621 "activeGestureId=%d, currentTouchPointerCount=%d",
3622 activeTouchId, mPointerGesture.activeGestureId, currentTouchPointerCount);
3623#endif
3624 assert(mPointerGesture.activeGestureId >= 0);
3625
3626 float x = (mCurrentTouch.pointers[0].x + mCurrentTouch.pointers[1].x
3627 - mPointerGesture.initialCentroidX * 2) * 0.5f
3628 * mLocked.pointerGestureXMovementScale + mPointerGesture.initialPointerX;
3629 float y = (mCurrentTouch.pointers[0].y + mCurrentTouch.pointers[1].y
3630 - mPointerGesture.initialCentroidY * 2) * 0.5f
3631 * mLocked.pointerGestureYMovementScale + mPointerGesture.initialPointerY;
3632
3633 mPointerGesture.currentGesturePointerCount = 1;
3634 mPointerGesture.currentGestureIdBits.clear();
3635 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3636 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3637 mPointerGesture.currentGestureCoords[0].clear();
3638 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3639 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3640 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3641 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
3642 // FREEFORM mode.
3643#if DEBUG_GESTURES
3644 LOGD("Gestures: FREEFORM activeTouchId=%d,"
3645 "activeGestureId=%d, currentTouchPointerCount=%d",
3646 activeTouchId, mPointerGesture.activeGestureId, currentTouchPointerCount);
3647#endif
3648 assert(mPointerGesture.activeGestureId >= 0);
3649
3650 mPointerGesture.currentGesturePointerCount = currentTouchPointerCount;
3651 mPointerGesture.currentGestureIdBits.clear();
3652
3653 BitSet32 mappedTouchIdBits;
3654 BitSet32 usedGestureIdBits;
3655 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
3656 // Initially, assign the active gesture id to the active touch point
3657 // if there is one. No other touch id bits are mapped yet.
3658 if (!*outCancelPreviousGesture) {
3659 mappedTouchIdBits.markBit(activeTouchId);
3660 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3661 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3662 mPointerGesture.activeGestureId;
3663 } else {
3664 mPointerGesture.activeGestureId = -1;
3665 }
3666 } else {
3667 // Otherwise, assume we mapped all touches from the previous frame.
3668 // Reuse all mappings that are still applicable.
3669 mappedTouchIdBits.value = mLastTouch.idBits.value & mCurrentTouch.idBits.value;
3670 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3671
3672 // Check whether we need to choose a new active gesture id because the
3673 // current went went up.
3674 for (BitSet32 upTouchIdBits(mLastTouch.idBits.value & ~mCurrentTouch.idBits.value);
3675 !upTouchIdBits.isEmpty(); ) {
3676 uint32_t upTouchId = upTouchIdBits.firstMarkedBit();
3677 upTouchIdBits.clearBit(upTouchId);
3678 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3679 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3680 mPointerGesture.activeGestureId = -1;
3681 break;
3682 }
3683 }
3684 }
3685
3686#if DEBUG_GESTURES
3687 LOGD("Gestures: FREEFORM follow up "
3688 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3689 "activeGestureId=%d",
3690 mappedTouchIdBits.value, usedGestureIdBits.value,
3691 mPointerGesture.activeGestureId);
3692#endif
3693
3694 for (uint32_t i = 0; i < currentTouchPointerCount; i++) {
3695 uint32_t touchId = mCurrentTouch.pointers[i].id;
3696 uint32_t gestureId;
3697 if (!mappedTouchIdBits.hasBit(touchId)) {
3698 gestureId = usedGestureIdBits.firstUnmarkedBit();
3699 usedGestureIdBits.markBit(gestureId);
3700 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3701#if DEBUG_GESTURES
3702 LOGD("Gestures: FREEFORM "
3703 "new mapping for touch id %d -> gesture id %d",
3704 touchId, gestureId);
3705#endif
3706 } else {
3707 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3708#if DEBUG_GESTURES
3709 LOGD("Gestures: FREEFORM "
3710 "existing mapping for touch id %d -> gesture id %d",
3711 touchId, gestureId);
3712#endif
3713 }
3714 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3715 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3716
3717 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.initialCentroidX)
3718 * mLocked.pointerGestureXZoomScale + mPointerGesture.initialPointerX;
3719 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.initialCentroidY)
3720 * mLocked.pointerGestureYZoomScale + mPointerGesture.initialPointerY;
3721
3722 mPointerGesture.currentGestureCoords[i].clear();
3723 mPointerGesture.currentGestureCoords[i].setAxisValue(
3724 AMOTION_EVENT_AXIS_X, x);
3725 mPointerGesture.currentGestureCoords[i].setAxisValue(
3726 AMOTION_EVENT_AXIS_Y, y);
3727 mPointerGesture.currentGestureCoords[i].setAxisValue(
3728 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3729 }
3730
3731 if (mPointerGesture.activeGestureId < 0) {
3732 mPointerGesture.activeGestureId =
3733 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3734#if DEBUG_GESTURES
3735 LOGD("Gestures: FREEFORM new "
3736 "activeGestureId=%d", mPointerGesture.activeGestureId);
3737#endif
3738 }
3739 } else {
3740 // INDETERMINATE_MULTITOUCH mode.
3741 // Do nothing.
3742#if DEBUG_GESTURES
3743 LOGD("Gestures: INDETERMINATE_MULTITOUCH");
3744#endif
3745 }
3746 }
3747
3748 // Unfade the pointer if the user is doing anything with the touch pad.
3749 mPointerController->setButtonState(mCurrentTouch.buttonState);
3750 if (mCurrentTouch.buttonState || mCurrentTouch.pointerCount != 0) {
3751 mPointerController->unfade();
3752 }
3753
3754#if DEBUG_GESTURES
3755 LOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3756 "currentGestureMode=%d, currentGesturePointerCount=%d, currentGestureIdBits=0x%08x, "
3757 "lastGestureMode=%d, lastGesturePointerCount=%d, lastGestureIdBits=0x%08x",
3758 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3759 mPointerGesture.currentGestureMode, mPointerGesture.currentGesturePointerCount,
3760 mPointerGesture.currentGestureIdBits.value,
3761 mPointerGesture.lastGestureMode, mPointerGesture.lastGesturePointerCount,
3762 mPointerGesture.lastGestureIdBits.value);
3763 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
3764 uint32_t id = idBits.firstMarkedBit();
3765 idBits.clearBit(id);
3766 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3767 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3768 LOGD(" currentGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
3769 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3770 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3771 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3772 }
3773 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
3774 uint32_t id = idBits.firstMarkedBit();
3775 idBits.clearBit(id);
3776 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3777 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3778 LOGD(" lastGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
3779 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3780 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3781 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3782 }
3783#endif
3784}
3785
3786void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3787 int32_t action, int32_t flags, uint32_t metaState, int32_t edgeFlags,
3788 const PointerCoords* coords, const uint32_t* idToIndex, BitSet32 idBits,
3789 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
3790 PointerCoords pointerCoords[MAX_POINTERS];
3791 int32_t pointerIds[MAX_POINTERS];
3792 uint32_t pointerCount = 0;
3793 while (!idBits.isEmpty()) {
3794 uint32_t id = idBits.firstMarkedBit();
3795 idBits.clearBit(id);
3796 uint32_t index = idToIndex[id];
3797 pointerIds[pointerCount] = id;
3798 pointerCoords[pointerCount].copyFrom(coords[index]);
3799
3800 if (changedId >= 0 && id == uint32_t(changedId)) {
3801 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3802 }
3803
3804 pointerCount += 1;
3805 }
3806
3807 assert(pointerCount != 0);
3808
3809 if (changedId >= 0 && pointerCount == 1) {
3810 // Replace initial down and final up action.
3811 // We can compare the action without masking off the changed pointer index
3812 // because we know the index is 0.
3813 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3814 action = AMOTION_EVENT_ACTION_DOWN;
3815 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
3816 action = AMOTION_EVENT_ACTION_UP;
3817 } else {
3818 // Can't happen.
3819 assert(false);
3820 }
3821 }
3822
3823 getDispatcher()->notifyMotion(when, getDeviceId(), source, policyFlags,
3824 action, flags, metaState, edgeFlags,
3825 pointerCount, pointerIds, pointerCoords, xPrecision, yPrecision, downTime);
3826}
3827
3828bool TouchInputMapper::updateMovedPointerCoords(
3829 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
3830 PointerCoords* outCoords, const uint32_t* outIdToIndex, BitSet32 idBits) const {
3831 bool changed = false;
3832 while (!idBits.isEmpty()) {
3833 uint32_t id = idBits.firstMarkedBit();
3834 idBits.clearBit(id);
3835
3836 uint32_t inIndex = inIdToIndex[id];
3837 uint32_t outIndex = outIdToIndex[id];
3838 const PointerCoords& curInCoords = inCoords[inIndex];
3839 PointerCoords& curOutCoords = outCoords[outIndex];
3840
3841 if (curInCoords != curOutCoords) {
3842 curOutCoords.copyFrom(curInCoords);
3843 changed = true;
3844 }
3845 }
3846 return changed;
3847}
3848
3849void TouchInputMapper::fadePointer() {
3850 { // acquire lock
3851 AutoMutex _l(mLock);
3852 if (mPointerController != NULL) {
3853 mPointerController->fade();
3854 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003855 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07003856}
3857
Jeff Brown6328cdc2010-07-29 18:18:33 -07003858bool TouchInputMapper::isPointInsideSurfaceLocked(int32_t x, int32_t y) {
Jeff Brown9626b142011-03-03 02:09:54 -08003859 return x >= mRawAxes.x.minValue && x <= mRawAxes.x.maxValue
3860 && y >= mRawAxes.y.minValue && y <= mRawAxes.y.maxValue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07003861}
3862
Jeff Brown6328cdc2010-07-29 18:18:33 -07003863const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHitLocked(
3864 int32_t x, int32_t y) {
3865 size_t numVirtualKeys = mLocked.virtualKeys.size();
3866 for (size_t i = 0; i < numVirtualKeys; i++) {
3867 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07003868
3869#if DEBUG_VIRTUAL_KEYS
3870 LOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3871 "left=%d, top=%d, right=%d, bottom=%d",
3872 x, y,
3873 virtualKey.keyCode, virtualKey.scanCode,
3874 virtualKey.hitLeft, virtualKey.hitTop,
3875 virtualKey.hitRight, virtualKey.hitBottom);
3876#endif
3877
3878 if (virtualKey.isHit(x, y)) {
3879 return & virtualKey;
3880 }
3881 }
3882
3883 return NULL;
3884}
3885
3886void TouchInputMapper::calculatePointerIds() {
3887 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
3888 uint32_t lastPointerCount = mLastTouch.pointerCount;
3889
3890 if (currentPointerCount == 0) {
3891 // No pointers to assign.
3892 mCurrentTouch.idBits.clear();
3893 } else if (lastPointerCount == 0) {
3894 // All pointers are new.
3895 mCurrentTouch.idBits.clear();
3896 for (uint32_t i = 0; i < currentPointerCount; i++) {
3897 mCurrentTouch.pointers[i].id = i;
3898 mCurrentTouch.idToIndex[i] = i;
3899 mCurrentTouch.idBits.markBit(i);
3900 }
3901 } else if (currentPointerCount == 1 && lastPointerCount == 1) {
3902 // Only one pointer and no change in count so it must have the same id as before.
3903 uint32_t id = mLastTouch.pointers[0].id;
3904 mCurrentTouch.pointers[0].id = id;
3905 mCurrentTouch.idToIndex[id] = 0;
3906 mCurrentTouch.idBits.value = BitSet32::valueForBit(id);
3907 } else {
3908 // General case.
3909 // We build a heap of squared euclidean distances between current and last pointers
3910 // associated with the current and last pointer indices. Then, we find the best
3911 // match (by distance) for each current pointer.
3912 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3913
3914 uint32_t heapSize = 0;
3915 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3916 currentPointerIndex++) {
3917 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3918 lastPointerIndex++) {
3919 int64_t deltaX = mCurrentTouch.pointers[currentPointerIndex].x
3920 - mLastTouch.pointers[lastPointerIndex].x;
3921 int64_t deltaY = mCurrentTouch.pointers[currentPointerIndex].y
3922 - mLastTouch.pointers[lastPointerIndex].y;
3923
3924 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3925
3926 // Insert new element into the heap (sift up).
3927 heap[heapSize].currentPointerIndex = currentPointerIndex;
3928 heap[heapSize].lastPointerIndex = lastPointerIndex;
3929 heap[heapSize].distance = distance;
3930 heapSize += 1;
3931 }
3932 }
3933
3934 // Heapify
3935 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
3936 startIndex -= 1;
3937 for (uint32_t parentIndex = startIndex; ;) {
3938 uint32_t childIndex = parentIndex * 2 + 1;
3939 if (childIndex >= heapSize) {
3940 break;
3941 }
3942
3943 if (childIndex + 1 < heapSize
3944 && heap[childIndex + 1].distance < heap[childIndex].distance) {
3945 childIndex += 1;
3946 }
3947
3948 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3949 break;
3950 }
3951
3952 swap(heap[parentIndex], heap[childIndex]);
3953 parentIndex = childIndex;
3954 }
3955 }
3956
3957#if DEBUG_POINTER_ASSIGNMENT
3958 LOGD("calculatePointerIds - initial distance min-heap: size=%d", heapSize);
3959 for (size_t i = 0; i < heapSize; i++) {
3960 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
3961 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
3962 heap[i].distance);
3963 }
3964#endif
3965
3966 // Pull matches out by increasing order of distance.
3967 // To avoid reassigning pointers that have already been matched, the loop keeps track
3968 // of which last and current pointers have been matched using the matchedXXXBits variables.
3969 // It also tracks the used pointer id bits.
3970 BitSet32 matchedLastBits(0);
3971 BitSet32 matchedCurrentBits(0);
3972 BitSet32 usedIdBits(0);
3973 bool first = true;
3974 for (uint32_t i = min(currentPointerCount, lastPointerCount); i > 0; i--) {
3975 for (;;) {
3976 if (first) {
3977 // The first time through the loop, we just consume the root element of
3978 // the heap (the one with smallest distance).
3979 first = false;
3980 } else {
3981 // Previous iterations consumed the root element of the heap.
3982 // Pop root element off of the heap (sift down).
3983 heapSize -= 1;
3984 assert(heapSize > 0);
3985
3986 // Sift down.
3987 heap[0] = heap[heapSize];
3988 for (uint32_t parentIndex = 0; ;) {
3989 uint32_t childIndex = parentIndex * 2 + 1;
3990 if (childIndex >= heapSize) {
3991 break;
3992 }
3993
3994 if (childIndex + 1 < heapSize
3995 && heap[childIndex + 1].distance < heap[childIndex].distance) {
3996 childIndex += 1;
3997 }
3998
3999 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4000 break;
4001 }
4002
4003 swap(heap[parentIndex], heap[childIndex]);
4004 parentIndex = childIndex;
4005 }
4006
4007#if DEBUG_POINTER_ASSIGNMENT
4008 LOGD("calculatePointerIds - reduced distance min-heap: size=%d", heapSize);
4009 for (size_t i = 0; i < heapSize; i++) {
4010 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4011 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4012 heap[i].distance);
4013 }
4014#endif
4015 }
4016
4017 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4018 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4019
4020 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4021 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4022
4023 matchedCurrentBits.markBit(currentPointerIndex);
4024 matchedLastBits.markBit(lastPointerIndex);
4025
4026 uint32_t id = mLastTouch.pointers[lastPointerIndex].id;
4027 mCurrentTouch.pointers[currentPointerIndex].id = id;
4028 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4029 usedIdBits.markBit(id);
4030
4031#if DEBUG_POINTER_ASSIGNMENT
4032 LOGD("calculatePointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
4033 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
4034#endif
4035 break;
4036 }
4037 }
4038
4039 // Assign fresh ids to new pointers.
4040 if (currentPointerCount > lastPointerCount) {
4041 for (uint32_t i = currentPointerCount - lastPointerCount; ;) {
4042 uint32_t currentPointerIndex = matchedCurrentBits.firstUnmarkedBit();
4043 uint32_t id = usedIdBits.firstUnmarkedBit();
4044
4045 mCurrentTouch.pointers[currentPointerIndex].id = id;
4046 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4047 usedIdBits.markBit(id);
4048
4049#if DEBUG_POINTER_ASSIGNMENT
4050 LOGD("calculatePointerIds - assigned: cur=%d, id=%d",
4051 currentPointerIndex, id);
4052#endif
4053
4054 if (--i == 0) break; // done
4055 matchedCurrentBits.markBit(currentPointerIndex);
4056 }
4057 }
4058
4059 // Fix id bits.
4060 mCurrentTouch.idBits = usedIdBits;
4061 }
4062}
4063
4064/* Special hack for devices that have bad screen data: if one of the
4065 * points has moved more than a screen height from the last position,
4066 * then drop it. */
4067bool TouchInputMapper::applyBadTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004068 uint32_t pointerCount = mCurrentTouch.pointerCount;
4069
4070 // Nothing to do if there are no points.
4071 if (pointerCount == 0) {
4072 return false;
4073 }
4074
4075 // Don't do anything if a finger is going down or up. We run
4076 // here before assigning pointer IDs, so there isn't a good
4077 // way to do per-finger matching.
4078 if (pointerCount != mLastTouch.pointerCount) {
4079 return false;
4080 }
4081
4082 // We consider a single movement across more than a 7/16 of
4083 // the long size of the screen to be bad. This was a magic value
4084 // determined by looking at the maximum distance it is feasible
4085 // to actually move in one sample.
Jeff Brown9626b142011-03-03 02:09:54 -08004086 int32_t maxDeltaY = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) * 7 / 16;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004087
4088 // XXX The original code in InputDevice.java included commented out
4089 // code for testing the X axis. Note that when we drop a point
4090 // we don't actually restore the old X either. Strange.
4091 // The old code also tries to track when bad points were previously
4092 // detected but it turns out that due to the placement of a "break"
4093 // at the end of the loop, we never set mDroppedBadPoint to true
4094 // so it is effectively dead code.
4095 // Need to figure out if the old code is busted or just overcomplicated
4096 // but working as intended.
4097
4098 // Look through all new points and see if any are farther than
4099 // acceptable from all previous points.
4100 for (uint32_t i = pointerCount; i-- > 0; ) {
4101 int32_t y = mCurrentTouch.pointers[i].y;
4102 int32_t closestY = INT_MAX;
4103 int32_t closestDeltaY = 0;
4104
4105#if DEBUG_HACKS
4106 LOGD("BadTouchFilter: Looking at next point #%d: y=%d", i, y);
4107#endif
4108
4109 for (uint32_t j = pointerCount; j-- > 0; ) {
4110 int32_t lastY = mLastTouch.pointers[j].y;
4111 int32_t deltaY = abs(y - lastY);
4112
4113#if DEBUG_HACKS
4114 LOGD("BadTouchFilter: Comparing with last point #%d: y=%d deltaY=%d",
4115 j, lastY, deltaY);
4116#endif
4117
4118 if (deltaY < maxDeltaY) {
4119 goto SkipSufficientlyClosePoint;
4120 }
4121 if (deltaY < closestDeltaY) {
4122 closestDeltaY = deltaY;
4123 closestY = lastY;
4124 }
4125 }
4126
4127 // Must not have found a close enough match.
4128#if DEBUG_HACKS
4129 LOGD("BadTouchFilter: Dropping bad point #%d: newY=%d oldY=%d deltaY=%d maxDeltaY=%d",
4130 i, y, closestY, closestDeltaY, maxDeltaY);
4131#endif
4132
4133 mCurrentTouch.pointers[i].y = closestY;
4134 return true; // XXX original code only corrects one point
4135
4136 SkipSufficientlyClosePoint: ;
4137 }
4138
4139 // No change.
4140 return false;
4141}
4142
4143/* Special hack for devices that have bad screen data: drop points where
4144 * the coordinate value for one axis has jumped to the other pointer's location.
4145 */
4146bool TouchInputMapper::applyJumpyTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004147 uint32_t pointerCount = mCurrentTouch.pointerCount;
4148 if (mLastTouch.pointerCount != pointerCount) {
4149#if DEBUG_HACKS
4150 LOGD("JumpyTouchFilter: Different pointer count %d -> %d",
4151 mLastTouch.pointerCount, pointerCount);
4152 for (uint32_t i = 0; i < pointerCount; i++) {
4153 LOGD(" Pointer %d (%d, %d)", i,
4154 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4155 }
4156#endif
4157
4158 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_TRANSITION_DROPS) {
4159 if (mLastTouch.pointerCount == 1 && pointerCount == 2) {
4160 // Just drop the first few events going from 1 to 2 pointers.
4161 // They're bad often enough that they're not worth considering.
4162 mCurrentTouch.pointerCount = 1;
4163 mJumpyTouchFilter.jumpyPointsDropped += 1;
4164
4165#if DEBUG_HACKS
4166 LOGD("JumpyTouchFilter: Pointer 2 dropped");
4167#endif
4168 return true;
4169 } else if (mLastTouch.pointerCount == 2 && pointerCount == 1) {
4170 // The event when we go from 2 -> 1 tends to be messed up too
4171 mCurrentTouch.pointerCount = 2;
4172 mCurrentTouch.pointers[0] = mLastTouch.pointers[0];
4173 mCurrentTouch.pointers[1] = mLastTouch.pointers[1];
4174 mJumpyTouchFilter.jumpyPointsDropped += 1;
4175
4176#if DEBUG_HACKS
4177 for (int32_t i = 0; i < 2; i++) {
4178 LOGD("JumpyTouchFilter: Pointer %d replaced (%d, %d)", i,
4179 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4180 }
4181#endif
4182 return true;
4183 }
4184 }
4185 // Reset jumpy points dropped on other transitions or if limit exceeded.
4186 mJumpyTouchFilter.jumpyPointsDropped = 0;
4187
4188#if DEBUG_HACKS
4189 LOGD("JumpyTouchFilter: Transition - drop limit reset");
4190#endif
4191 return false;
4192 }
4193
4194 // We have the same number of pointers as last time.
4195 // A 'jumpy' point is one where the coordinate value for one axis
4196 // has jumped to the other pointer's location. No need to do anything
4197 // else if we only have one pointer.
4198 if (pointerCount < 2) {
4199 return false;
4200 }
4201
4202 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_DROP_LIMIT) {
Jeff Brown9626b142011-03-03 02:09:54 -08004203 int jumpyEpsilon = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) / JUMPY_EPSILON_DIVISOR;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004204
4205 // We only replace the single worst jumpy point as characterized by pointer distance
4206 // in a single axis.
4207 int32_t badPointerIndex = -1;
4208 int32_t badPointerReplacementIndex = -1;
4209 int32_t badPointerDistance = INT_MIN; // distance to be corrected
4210
4211 for (uint32_t i = pointerCount; i-- > 0; ) {
4212 int32_t x = mCurrentTouch.pointers[i].x;
4213 int32_t y = mCurrentTouch.pointers[i].y;
4214
4215#if DEBUG_HACKS
4216 LOGD("JumpyTouchFilter: Point %d (%d, %d)", i, x, y);
4217#endif
4218
4219 // Check if a touch point is too close to another's coordinates
4220 bool dropX = false, dropY = false;
4221 for (uint32_t j = 0; j < pointerCount; j++) {
4222 if (i == j) {
4223 continue;
4224 }
4225
4226 if (abs(x - mCurrentTouch.pointers[j].x) <= jumpyEpsilon) {
4227 dropX = true;
4228 break;
4229 }
4230
4231 if (abs(y - mCurrentTouch.pointers[j].y) <= jumpyEpsilon) {
4232 dropY = true;
4233 break;
4234 }
4235 }
4236 if (! dropX && ! dropY) {
4237 continue; // not jumpy
4238 }
4239
4240 // Find a replacement candidate by comparing with older points on the
4241 // complementary (non-jumpy) axis.
4242 int32_t distance = INT_MIN; // distance to be corrected
4243 int32_t replacementIndex = -1;
4244
4245 if (dropX) {
4246 // X looks too close. Find an older replacement point with a close Y.
4247 int32_t smallestDeltaY = INT_MAX;
4248 for (uint32_t j = 0; j < pointerCount; j++) {
4249 int32_t deltaY = abs(y - mLastTouch.pointers[j].y);
4250 if (deltaY < smallestDeltaY) {
4251 smallestDeltaY = deltaY;
4252 replacementIndex = j;
4253 }
4254 }
4255 distance = abs(x - mLastTouch.pointers[replacementIndex].x);
4256 } else {
4257 // Y looks too close. Find an older replacement point with a close X.
4258 int32_t smallestDeltaX = INT_MAX;
4259 for (uint32_t j = 0; j < pointerCount; j++) {
4260 int32_t deltaX = abs(x - mLastTouch.pointers[j].x);
4261 if (deltaX < smallestDeltaX) {
4262 smallestDeltaX = deltaX;
4263 replacementIndex = j;
4264 }
4265 }
4266 distance = abs(y - mLastTouch.pointers[replacementIndex].y);
4267 }
4268
4269 // If replacing this pointer would correct a worse error than the previous ones
4270 // considered, then use this replacement instead.
4271 if (distance > badPointerDistance) {
4272 badPointerIndex = i;
4273 badPointerReplacementIndex = replacementIndex;
4274 badPointerDistance = distance;
4275 }
4276 }
4277
4278 // Correct the jumpy pointer if one was found.
4279 if (badPointerIndex >= 0) {
4280#if DEBUG_HACKS
4281 LOGD("JumpyTouchFilter: Replacing bad pointer %d with (%d, %d)",
4282 badPointerIndex,
4283 mLastTouch.pointers[badPointerReplacementIndex].x,
4284 mLastTouch.pointers[badPointerReplacementIndex].y);
4285#endif
4286
4287 mCurrentTouch.pointers[badPointerIndex].x =
4288 mLastTouch.pointers[badPointerReplacementIndex].x;
4289 mCurrentTouch.pointers[badPointerIndex].y =
4290 mLastTouch.pointers[badPointerReplacementIndex].y;
4291 mJumpyTouchFilter.jumpyPointsDropped += 1;
4292 return true;
4293 }
4294 }
4295
4296 mJumpyTouchFilter.jumpyPointsDropped = 0;
4297 return false;
4298}
4299
4300/* Special hack for devices that have bad screen data: aggregate and
4301 * compute averages of the coordinate data, to reduce the amount of
4302 * jitter seen by applications. */
4303void TouchInputMapper::applyAveragingTouchFilter() {
4304 for (uint32_t currentIndex = 0; currentIndex < mCurrentTouch.pointerCount; currentIndex++) {
4305 uint32_t id = mCurrentTouch.pointers[currentIndex].id;
4306 int32_t x = mCurrentTouch.pointers[currentIndex].x;
4307 int32_t y = mCurrentTouch.pointers[currentIndex].y;
Jeff Brown8d608662010-08-30 03:02:23 -07004308 int32_t pressure;
4309 switch (mCalibration.pressureSource) {
4310 case Calibration::PRESSURE_SOURCE_PRESSURE:
4311 pressure = mCurrentTouch.pointers[currentIndex].pressure;
4312 break;
4313 case Calibration::PRESSURE_SOURCE_TOUCH:
4314 pressure = mCurrentTouch.pointers[currentIndex].touchMajor;
4315 break;
4316 default:
4317 pressure = 1;
4318 break;
4319 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004320
4321 if (mLastTouch.idBits.hasBit(id)) {
4322 // Pointer was down before and is still down now.
4323 // Compute average over history trace.
4324 uint32_t start = mAveragingTouchFilter.historyStart[id];
4325 uint32_t end = mAveragingTouchFilter.historyEnd[id];
4326
4327 int64_t deltaX = x - mAveragingTouchFilter.historyData[end].pointers[id].x;
4328 int64_t deltaY = y - mAveragingTouchFilter.historyData[end].pointers[id].y;
4329 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4330
4331#if DEBUG_HACKS
4332 LOGD("AveragingTouchFilter: Pointer id %d - Distance from last sample: %lld",
4333 id, distance);
4334#endif
4335
4336 if (distance < AVERAGING_DISTANCE_LIMIT) {
4337 // Increment end index in preparation for recording new historical data.
4338 end += 1;
4339 if (end > AVERAGING_HISTORY_SIZE) {
4340 end = 0;
4341 }
4342
4343 // If the end index has looped back to the start index then we have filled
4344 // the historical trace up to the desired size so we drop the historical
4345 // data at the start of the trace.
4346 if (end == start) {
4347 start += 1;
4348 if (start > AVERAGING_HISTORY_SIZE) {
4349 start = 0;
4350 }
4351 }
4352
4353 // Add the raw data to the historical trace.
4354 mAveragingTouchFilter.historyStart[id] = start;
4355 mAveragingTouchFilter.historyEnd[id] = end;
4356 mAveragingTouchFilter.historyData[end].pointers[id].x = x;
4357 mAveragingTouchFilter.historyData[end].pointers[id].y = y;
4358 mAveragingTouchFilter.historyData[end].pointers[id].pressure = pressure;
4359
4360 // Average over all historical positions in the trace by total pressure.
4361 int32_t averagedX = 0;
4362 int32_t averagedY = 0;
4363 int32_t totalPressure = 0;
4364 for (;;) {
4365 int32_t historicalX = mAveragingTouchFilter.historyData[start].pointers[id].x;
4366 int32_t historicalY = mAveragingTouchFilter.historyData[start].pointers[id].y;
4367 int32_t historicalPressure = mAveragingTouchFilter.historyData[start]
4368 .pointers[id].pressure;
4369
4370 averagedX += historicalX * historicalPressure;
4371 averagedY += historicalY * historicalPressure;
4372 totalPressure += historicalPressure;
4373
4374 if (start == end) {
4375 break;
4376 }
4377
4378 start += 1;
4379 if (start > AVERAGING_HISTORY_SIZE) {
4380 start = 0;
4381 }
4382 }
4383
Jeff Brown8d608662010-08-30 03:02:23 -07004384 if (totalPressure != 0) {
4385 averagedX /= totalPressure;
4386 averagedY /= totalPressure;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004387
4388#if DEBUG_HACKS
Jeff Brown8d608662010-08-30 03:02:23 -07004389 LOGD("AveragingTouchFilter: Pointer id %d - "
4390 "totalPressure=%d, averagedX=%d, averagedY=%d", id, totalPressure,
4391 averagedX, averagedY);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004392#endif
4393
Jeff Brown8d608662010-08-30 03:02:23 -07004394 mCurrentTouch.pointers[currentIndex].x = averagedX;
4395 mCurrentTouch.pointers[currentIndex].y = averagedY;
4396 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004397 } else {
4398#if DEBUG_HACKS
4399 LOGD("AveragingTouchFilter: Pointer id %d - Exceeded max distance", id);
4400#endif
4401 }
4402 } else {
4403#if DEBUG_HACKS
4404 LOGD("AveragingTouchFilter: Pointer id %d - Pointer went up", id);
4405#endif
4406 }
4407
4408 // Reset pointer history.
4409 mAveragingTouchFilter.historyStart[id] = 0;
4410 mAveragingTouchFilter.historyEnd[id] = 0;
4411 mAveragingTouchFilter.historyData[0].pointers[id].x = x;
4412 mAveragingTouchFilter.historyData[0].pointers[id].y = y;
4413 mAveragingTouchFilter.historyData[0].pointers[id].pressure = pressure;
4414 }
4415}
4416
4417int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004418 { // acquire lock
4419 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004420
Jeff Brown6328cdc2010-07-29 18:18:33 -07004421 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.keyCode == keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004422 return AKEY_STATE_VIRTUAL;
4423 }
4424
Jeff Brown6328cdc2010-07-29 18:18:33 -07004425 size_t numVirtualKeys = mLocked.virtualKeys.size();
4426 for (size_t i = 0; i < numVirtualKeys; i++) {
4427 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004428 if (virtualKey.keyCode == keyCode) {
4429 return AKEY_STATE_UP;
4430 }
4431 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004432 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004433
4434 return AKEY_STATE_UNKNOWN;
4435}
4436
4437int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004438 { // acquire lock
4439 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004440
Jeff Brown6328cdc2010-07-29 18:18:33 -07004441 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004442 return AKEY_STATE_VIRTUAL;
4443 }
4444
Jeff Brown6328cdc2010-07-29 18:18:33 -07004445 size_t numVirtualKeys = mLocked.virtualKeys.size();
4446 for (size_t i = 0; i < numVirtualKeys; i++) {
4447 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004448 if (virtualKey.scanCode == scanCode) {
4449 return AKEY_STATE_UP;
4450 }
4451 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004452 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004453
4454 return AKEY_STATE_UNKNOWN;
4455}
4456
4457bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4458 const int32_t* keyCodes, uint8_t* outFlags) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004459 { // acquire lock
4460 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004461
Jeff Brown6328cdc2010-07-29 18:18:33 -07004462 size_t numVirtualKeys = mLocked.virtualKeys.size();
4463 for (size_t i = 0; i < numVirtualKeys; i++) {
4464 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004465
4466 for (size_t i = 0; i < numCodes; i++) {
4467 if (virtualKey.keyCode == keyCodes[i]) {
4468 outFlags[i] = 1;
4469 }
4470 }
4471 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004472 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004473
4474 return true;
4475}
4476
4477
4478// --- SingleTouchInputMapper ---
4479
Jeff Brown47e6b1b2010-11-29 17:37:49 -08004480SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
4481 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004482 initialize();
4483}
4484
4485SingleTouchInputMapper::~SingleTouchInputMapper() {
4486}
4487
4488void SingleTouchInputMapper::initialize() {
4489 mAccumulator.clear();
4490
4491 mDown = false;
4492 mX = 0;
4493 mY = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07004494 mPressure = 0; // default to 0 for devices that don't report pressure
4495 mToolWidth = 0; // default to 0 for devices that don't report tool width
Jeff Brown96ad3972011-03-09 17:39:48 -08004496 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004497}
4498
4499void SingleTouchInputMapper::reset() {
4500 TouchInputMapper::reset();
4501
Jeff Brown6d0fec22010-07-23 21:28:06 -07004502 initialize();
4503 }
4504
4505void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
4506 switch (rawEvent->type) {
4507 case EV_KEY:
4508 switch (rawEvent->scanCode) {
4509 case BTN_TOUCH:
4510 mAccumulator.fields |= Accumulator::FIELD_BTN_TOUCH;
4511 mAccumulator.btnTouch = rawEvent->value != 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004512 // Don't sync immediately. Wait until the next SYN_REPORT since we might
4513 // not have received valid position information yet. This logic assumes that
4514 // BTN_TOUCH is always followed by SYN_REPORT as part of a complete packet.
Jeff Brown6d0fec22010-07-23 21:28:06 -07004515 break;
Jeff Brown96ad3972011-03-09 17:39:48 -08004516 default:
4517 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
4518 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
4519 if (buttonState) {
4520 if (rawEvent->value) {
4521 mAccumulator.buttonDown |= buttonState;
4522 } else {
4523 mAccumulator.buttonUp |= buttonState;
4524 }
4525 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
4526 }
4527 }
4528 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004529 }
4530 break;
4531
4532 case EV_ABS:
4533 switch (rawEvent->scanCode) {
4534 case ABS_X:
4535 mAccumulator.fields |= Accumulator::FIELD_ABS_X;
4536 mAccumulator.absX = rawEvent->value;
4537 break;
4538 case ABS_Y:
4539 mAccumulator.fields |= Accumulator::FIELD_ABS_Y;
4540 mAccumulator.absY = rawEvent->value;
4541 break;
4542 case ABS_PRESSURE:
4543 mAccumulator.fields |= Accumulator::FIELD_ABS_PRESSURE;
4544 mAccumulator.absPressure = rawEvent->value;
4545 break;
4546 case ABS_TOOL_WIDTH:
4547 mAccumulator.fields |= Accumulator::FIELD_ABS_TOOL_WIDTH;
4548 mAccumulator.absToolWidth = rawEvent->value;
4549 break;
4550 }
4551 break;
4552
4553 case EV_SYN:
4554 switch (rawEvent->scanCode) {
4555 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004556 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004557 break;
4558 }
4559 break;
4560 }
4561}
4562
4563void SingleTouchInputMapper::sync(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004564 uint32_t fields = mAccumulator.fields;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004565 if (fields == 0) {
4566 return; // no new state changes, so nothing to do
4567 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004568
4569 if (fields & Accumulator::FIELD_BTN_TOUCH) {
4570 mDown = mAccumulator.btnTouch;
4571 }
4572
4573 if (fields & Accumulator::FIELD_ABS_X) {
4574 mX = mAccumulator.absX;
4575 }
4576
4577 if (fields & Accumulator::FIELD_ABS_Y) {
4578 mY = mAccumulator.absY;
4579 }
4580
4581 if (fields & Accumulator::FIELD_ABS_PRESSURE) {
4582 mPressure = mAccumulator.absPressure;
4583 }
4584
4585 if (fields & Accumulator::FIELD_ABS_TOOL_WIDTH) {
Jeff Brown8d608662010-08-30 03:02:23 -07004586 mToolWidth = mAccumulator.absToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004587 }
4588
Jeff Brown96ad3972011-03-09 17:39:48 -08004589 if (fields & Accumulator::FIELD_BUTTONS) {
4590 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
4591 }
4592
Jeff Brown6d0fec22010-07-23 21:28:06 -07004593 mCurrentTouch.clear();
4594
4595 if (mDown) {
4596 mCurrentTouch.pointerCount = 1;
4597 mCurrentTouch.pointers[0].id = 0;
4598 mCurrentTouch.pointers[0].x = mX;
4599 mCurrentTouch.pointers[0].y = mY;
4600 mCurrentTouch.pointers[0].pressure = mPressure;
Jeff Brown8d608662010-08-30 03:02:23 -07004601 mCurrentTouch.pointers[0].touchMajor = 0;
4602 mCurrentTouch.pointers[0].touchMinor = 0;
4603 mCurrentTouch.pointers[0].toolMajor = mToolWidth;
4604 mCurrentTouch.pointers[0].toolMinor = mToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004605 mCurrentTouch.pointers[0].orientation = 0;
4606 mCurrentTouch.idToIndex[0] = 0;
4607 mCurrentTouch.idBits.markBit(0);
Jeff Brown96ad3972011-03-09 17:39:48 -08004608 mCurrentTouch.buttonState = mButtonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004609 }
4610
4611 syncTouch(when, true);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004612
4613 mAccumulator.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07004614}
4615
Jeff Brown8d608662010-08-30 03:02:23 -07004616void SingleTouchInputMapper::configureRawAxes() {
4617 TouchInputMapper::configureRawAxes();
Jeff Brown6d0fec22010-07-23 21:28:06 -07004618
Jeff Brown8d608662010-08-30 03:02:23 -07004619 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_X, & mRawAxes.x);
4620 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_Y, & mRawAxes.y);
4621 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_PRESSURE, & mRawAxes.pressure);
4622 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_TOOL_WIDTH, & mRawAxes.toolMajor);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004623}
4624
4625
4626// --- MultiTouchInputMapper ---
4627
Jeff Brown47e6b1b2010-11-29 17:37:49 -08004628MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
4629 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004630 initialize();
4631}
4632
4633MultiTouchInputMapper::~MultiTouchInputMapper() {
4634}
4635
4636void MultiTouchInputMapper::initialize() {
4637 mAccumulator.clear();
Jeff Brown96ad3972011-03-09 17:39:48 -08004638 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004639}
4640
4641void MultiTouchInputMapper::reset() {
4642 TouchInputMapper::reset();
4643
Jeff Brown6d0fec22010-07-23 21:28:06 -07004644 initialize();
4645}
4646
4647void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
4648 switch (rawEvent->type) {
Jeff Brown96ad3972011-03-09 17:39:48 -08004649 case EV_KEY: {
4650 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
4651 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
4652 if (buttonState) {
4653 if (rawEvent->value) {
4654 mAccumulator.buttonDown |= buttonState;
4655 } else {
4656 mAccumulator.buttonUp |= buttonState;
4657 }
4658 }
4659 }
4660 break;
4661 }
4662
Jeff Brown6d0fec22010-07-23 21:28:06 -07004663 case EV_ABS: {
4664 uint32_t pointerIndex = mAccumulator.pointerCount;
4665 Accumulator::Pointer* pointer = & mAccumulator.pointers[pointerIndex];
4666
4667 switch (rawEvent->scanCode) {
4668 case ABS_MT_POSITION_X:
4669 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_X;
4670 pointer->absMTPositionX = rawEvent->value;
4671 break;
4672 case ABS_MT_POSITION_Y:
4673 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_Y;
4674 pointer->absMTPositionY = rawEvent->value;
4675 break;
4676 case ABS_MT_TOUCH_MAJOR:
4677 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MAJOR;
4678 pointer->absMTTouchMajor = rawEvent->value;
4679 break;
4680 case ABS_MT_TOUCH_MINOR:
4681 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MINOR;
4682 pointer->absMTTouchMinor = rawEvent->value;
4683 break;
4684 case ABS_MT_WIDTH_MAJOR:
4685 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MAJOR;
4686 pointer->absMTWidthMajor = rawEvent->value;
4687 break;
4688 case ABS_MT_WIDTH_MINOR:
4689 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MINOR;
4690 pointer->absMTWidthMinor = rawEvent->value;
4691 break;
4692 case ABS_MT_ORIENTATION:
4693 pointer->fields |= Accumulator::FIELD_ABS_MT_ORIENTATION;
4694 pointer->absMTOrientation = rawEvent->value;
4695 break;
4696 case ABS_MT_TRACKING_ID:
4697 pointer->fields |= Accumulator::FIELD_ABS_MT_TRACKING_ID;
4698 pointer->absMTTrackingId = rawEvent->value;
4699 break;
Jeff Brown8d608662010-08-30 03:02:23 -07004700 case ABS_MT_PRESSURE:
4701 pointer->fields |= Accumulator::FIELD_ABS_MT_PRESSURE;
4702 pointer->absMTPressure = rawEvent->value;
4703 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004704 }
4705 break;
4706 }
4707
4708 case EV_SYN:
4709 switch (rawEvent->scanCode) {
4710 case SYN_MT_REPORT: {
4711 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
4712 uint32_t pointerIndex = mAccumulator.pointerCount;
4713
4714 if (mAccumulator.pointers[pointerIndex].fields) {
4715 if (pointerIndex == MAX_POINTERS) {
4716 LOGW("MultiTouch device driver returned more than maximum of %d pointers.",
4717 MAX_POINTERS);
4718 } else {
4719 pointerIndex += 1;
4720 mAccumulator.pointerCount = pointerIndex;
4721 }
4722 }
4723
4724 mAccumulator.pointers[pointerIndex].clear();
4725 break;
4726 }
4727
4728 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004729 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004730 break;
4731 }
4732 break;
4733 }
4734}
4735
4736void MultiTouchInputMapper::sync(nsecs_t when) {
4737 static const uint32_t REQUIRED_FIELDS =
Jeff Brown8d608662010-08-30 03:02:23 -07004738 Accumulator::FIELD_ABS_MT_POSITION_X | Accumulator::FIELD_ABS_MT_POSITION_Y;
Jeff Brown46b9ac02010-04-22 18:58:52 -07004739
Jeff Brown6d0fec22010-07-23 21:28:06 -07004740 uint32_t inCount = mAccumulator.pointerCount;
4741 uint32_t outCount = 0;
4742 bool havePointerIds = true;
Jeff Brown46b9ac02010-04-22 18:58:52 -07004743
Jeff Brown6d0fec22010-07-23 21:28:06 -07004744 mCurrentTouch.clear();
Jeff Brown46b9ac02010-04-22 18:58:52 -07004745
Jeff Brown6d0fec22010-07-23 21:28:06 -07004746 for (uint32_t inIndex = 0; inIndex < inCount; inIndex++) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004747 const Accumulator::Pointer& inPointer = mAccumulator.pointers[inIndex];
4748 uint32_t fields = inPointer.fields;
Jeff Brown46b9ac02010-04-22 18:58:52 -07004749
Jeff Brown6d0fec22010-07-23 21:28:06 -07004750 if ((fields & REQUIRED_FIELDS) != REQUIRED_FIELDS) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004751 // Some drivers send empty MT sync packets without X / Y to indicate a pointer up.
4752 // Drop this finger.
Jeff Brown46b9ac02010-04-22 18:58:52 -07004753 continue;
4754 }
4755
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004756 PointerData& outPointer = mCurrentTouch.pointers[outCount];
4757 outPointer.x = inPointer.absMTPositionX;
4758 outPointer.y = inPointer.absMTPositionY;
Jeff Brown46b9ac02010-04-22 18:58:52 -07004759
Jeff Brown8d608662010-08-30 03:02:23 -07004760 if (fields & Accumulator::FIELD_ABS_MT_PRESSURE) {
4761 if (inPointer.absMTPressure <= 0) {
Jeff Brownc3db8582010-10-20 15:33:38 -07004762 // Some devices send sync packets with X / Y but with a 0 pressure to indicate
4763 // a pointer going up. Drop this finger.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004764 continue;
4765 }
Jeff Brown8d608662010-08-30 03:02:23 -07004766 outPointer.pressure = inPointer.absMTPressure;
4767 } else {
4768 // Default pressure to 0 if absent.
4769 outPointer.pressure = 0;
4770 }
4771
4772 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MAJOR) {
4773 if (inPointer.absMTTouchMajor <= 0) {
4774 // Some devices send sync packets with X / Y but with a 0 touch major to indicate
4775 // a pointer going up. Drop this finger.
4776 continue;
4777 }
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004778 outPointer.touchMajor = inPointer.absMTTouchMajor;
4779 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004780 // Default touch area to 0 if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004781 outPointer.touchMajor = 0;
4782 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07004783
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004784 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MINOR) {
4785 outPointer.touchMinor = inPointer.absMTTouchMinor;
4786 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004787 // Assume touch area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004788 outPointer.touchMinor = outPointer.touchMajor;
4789 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07004790
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004791 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MAJOR) {
4792 outPointer.toolMajor = inPointer.absMTWidthMajor;
4793 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004794 // Default tool area to 0 if absent.
4795 outPointer.toolMajor = 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004796 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07004797
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004798 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MINOR) {
4799 outPointer.toolMinor = inPointer.absMTWidthMinor;
4800 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004801 // Assume tool area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004802 outPointer.toolMinor = outPointer.toolMajor;
4803 }
4804
4805 if (fields & Accumulator::FIELD_ABS_MT_ORIENTATION) {
4806 outPointer.orientation = inPointer.absMTOrientation;
4807 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004808 // Default orientation to vertical if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004809 outPointer.orientation = 0;
4810 }
4811
Jeff Brown8d608662010-08-30 03:02:23 -07004812 // Assign pointer id using tracking id if available.
Jeff Brown6d0fec22010-07-23 21:28:06 -07004813 if (havePointerIds) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004814 if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) {
4815 uint32_t id = uint32_t(inPointer.absMTTrackingId);
Jeff Brown46b9ac02010-04-22 18:58:52 -07004816
Jeff Brown6d0fec22010-07-23 21:28:06 -07004817 if (id > MAX_POINTER_ID) {
4818#if DEBUG_POINTERS
4819 LOGD("Pointers: Ignoring driver provided pointer id %d because "
Jeff Brown01ce2e92010-09-26 22:20:12 -07004820 "it is larger than max supported id %d",
Jeff Brown6d0fec22010-07-23 21:28:06 -07004821 id, MAX_POINTER_ID);
4822#endif
4823 havePointerIds = false;
4824 }
4825 else {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004826 outPointer.id = id;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004827 mCurrentTouch.idToIndex[id] = outCount;
4828 mCurrentTouch.idBits.markBit(id);
4829 }
4830 } else {
4831 havePointerIds = false;
Jeff Brown46b9ac02010-04-22 18:58:52 -07004832 }
4833 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07004834
Jeff Brown6d0fec22010-07-23 21:28:06 -07004835 outCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -07004836 }
4837
Jeff Brown6d0fec22010-07-23 21:28:06 -07004838 mCurrentTouch.pointerCount = outCount;
Jeff Brown46b9ac02010-04-22 18:58:52 -07004839
Jeff Brown96ad3972011-03-09 17:39:48 -08004840 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
4841 mCurrentTouch.buttonState = mButtonState;
4842
Jeff Brown6d0fec22010-07-23 21:28:06 -07004843 syncTouch(when, havePointerIds);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004844
4845 mAccumulator.clear();
Jeff Brown46b9ac02010-04-22 18:58:52 -07004846}
4847
Jeff Brown8d608662010-08-30 03:02:23 -07004848void MultiTouchInputMapper::configureRawAxes() {
4849 TouchInputMapper::configureRawAxes();
Jeff Brown46b9ac02010-04-22 18:58:52 -07004850
Jeff Brown8d608662010-08-30 03:02:23 -07004851 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_X, & mRawAxes.x);
4852 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_Y, & mRawAxes.y);
4853 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MAJOR, & mRawAxes.touchMajor);
4854 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MINOR, & mRawAxes.touchMinor);
4855 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MAJOR, & mRawAxes.toolMajor);
4856 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MINOR, & mRawAxes.toolMinor);
4857 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_ORIENTATION, & mRawAxes.orientation);
4858 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_PRESSURE, & mRawAxes.pressure);
Jeff Brown9c3cda02010-06-15 01:31:58 -07004859}
4860
Jeff Brown46b9ac02010-04-22 18:58:52 -07004861
Jeff Browncb1404e2011-01-15 18:14:15 -08004862// --- JoystickInputMapper ---
4863
4864JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
4865 InputMapper(device) {
Jeff Browncb1404e2011-01-15 18:14:15 -08004866}
4867
4868JoystickInputMapper::~JoystickInputMapper() {
4869}
4870
4871uint32_t JoystickInputMapper::getSources() {
4872 return AINPUT_SOURCE_JOYSTICK;
4873}
4874
4875void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
4876 InputMapper::populateDeviceInfo(info);
4877
Jeff Brown6f2fba42011-02-19 01:08:02 -08004878 for (size_t i = 0; i < mAxes.size(); i++) {
4879 const Axis& axis = mAxes.valueAt(i);
Jeff Brownefd32662011-03-08 15:13:06 -08004880 info->addMotionRange(axis.axisInfo.axis, AINPUT_SOURCE_JOYSTICK,
4881 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08004882 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
Jeff Brownefd32662011-03-08 15:13:06 -08004883 info->addMotionRange(axis.axisInfo.highAxis, AINPUT_SOURCE_JOYSTICK,
4884 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08004885 }
Jeff Browncb1404e2011-01-15 18:14:15 -08004886 }
4887}
4888
4889void JoystickInputMapper::dump(String8& dump) {
4890 dump.append(INDENT2 "Joystick Input Mapper:\n");
4891
Jeff Brown6f2fba42011-02-19 01:08:02 -08004892 dump.append(INDENT3 "Axes:\n");
4893 size_t numAxes = mAxes.size();
4894 for (size_t i = 0; i < numAxes; i++) {
4895 const Axis& axis = mAxes.valueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08004896 const char* label = getAxisLabel(axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004897 if (label) {
Jeff Brown85297452011-03-04 13:07:49 -08004898 dump.appendFormat(INDENT4 "%s", label);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004899 } else {
Jeff Brown85297452011-03-04 13:07:49 -08004900 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004901 }
Jeff Brown85297452011-03-04 13:07:49 -08004902 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
4903 label = getAxisLabel(axis.axisInfo.highAxis);
4904 if (label) {
4905 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
4906 } else {
4907 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
4908 axis.axisInfo.splitValue);
4909 }
4910 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
4911 dump.append(" (invert)");
4912 }
4913
4914 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f\n",
4915 axis.min, axis.max, axis.flat, axis.fuzz);
4916 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
4917 "highScale=%0.5f, highOffset=%0.5f\n",
4918 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004919 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, rawFlat=%d, rawFuzz=%d\n",
4920 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
4921 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz);
Jeff Browncb1404e2011-01-15 18:14:15 -08004922 }
4923}
4924
4925void JoystickInputMapper::configure() {
4926 InputMapper::configure();
4927
Jeff Brown6f2fba42011-02-19 01:08:02 -08004928 // Collect all axes.
4929 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
4930 RawAbsoluteAxisInfo rawAxisInfo;
4931 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), abs, &rawAxisInfo);
4932 if (rawAxisInfo.valid) {
Jeff Brown85297452011-03-04 13:07:49 -08004933 // Map axis.
4934 AxisInfo axisInfo;
4935 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004936 if (!explicitlyMapped) {
4937 // Axis is not explicitly mapped, will choose a generic axis later.
Jeff Brown85297452011-03-04 13:07:49 -08004938 axisInfo.mode = AxisInfo::MODE_NORMAL;
4939 axisInfo.axis = -1;
Jeff Brown6f2fba42011-02-19 01:08:02 -08004940 }
Jeff Browncb1404e2011-01-15 18:14:15 -08004941
Jeff Brown85297452011-03-04 13:07:49 -08004942 // Apply flat override.
4943 int32_t rawFlat = axisInfo.flatOverride < 0
4944 ? rawAxisInfo.flat : axisInfo.flatOverride;
4945
4946 // Calculate scaling factors and limits.
Jeff Brown6f2fba42011-02-19 01:08:02 -08004947 Axis axis;
Jeff Brown85297452011-03-04 13:07:49 -08004948 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
4949 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
4950 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
4951 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
4952 scale, 0.0f, highScale, 0.0f,
4953 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
4954 } else if (isCenteredAxis(axisInfo.axis)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08004955 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
4956 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
Jeff Brown85297452011-03-04 13:07:49 -08004957 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
4958 scale, offset, scale, offset,
4959 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004960 } else {
4961 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
Jeff Brown85297452011-03-04 13:07:49 -08004962 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
4963 scale, 0.0f, scale, 0.0f,
4964 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004965 }
4966
4967 // To eliminate noise while the joystick is at rest, filter out small variations
4968 // in axis values up front.
4969 axis.filter = axis.flat * 0.25f;
4970
4971 mAxes.add(abs, axis);
4972 }
4973 }
4974
4975 // If there are too many axes, start dropping them.
4976 // Prefer to keep explicitly mapped axes.
4977 if (mAxes.size() > PointerCoords::MAX_AXES) {
4978 LOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.",
4979 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
4980 pruneAxes(true);
4981 pruneAxes(false);
4982 }
4983
4984 // Assign generic axis ids to remaining axes.
4985 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
4986 size_t numAxes = mAxes.size();
4987 for (size_t i = 0; i < numAxes; i++) {
4988 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08004989 if (axis.axisInfo.axis < 0) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08004990 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
4991 && haveAxis(nextGenericAxisId)) {
4992 nextGenericAxisId += 1;
4993 }
4994
4995 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
Jeff Brown85297452011-03-04 13:07:49 -08004996 axis.axisInfo.axis = nextGenericAxisId;
Jeff Brown6f2fba42011-02-19 01:08:02 -08004997 nextGenericAxisId += 1;
4998 } else {
4999 LOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
5000 "have already been assigned to other axes.",
5001 getDeviceName().string(), mAxes.keyAt(i));
5002 mAxes.removeItemsAt(i--);
5003 numAxes -= 1;
5004 }
5005 }
5006 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005007}
5008
Jeff Brown85297452011-03-04 13:07:49 -08005009bool JoystickInputMapper::haveAxis(int32_t axisId) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005010 size_t numAxes = mAxes.size();
5011 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005012 const Axis& axis = mAxes.valueAt(i);
5013 if (axis.axisInfo.axis == axisId
5014 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
5015 && axis.axisInfo.highAxis == axisId)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005016 return true;
5017 }
5018 }
5019 return false;
5020}
Jeff Browncb1404e2011-01-15 18:14:15 -08005021
Jeff Brown6f2fba42011-02-19 01:08:02 -08005022void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
5023 size_t i = mAxes.size();
5024 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
5025 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
5026 continue;
5027 }
5028 LOGI("Discarding joystick '%s' axis %d because there are too many axes.",
5029 getDeviceName().string(), mAxes.keyAt(i));
5030 mAxes.removeItemsAt(i);
5031 }
5032}
5033
5034bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
5035 switch (axis) {
5036 case AMOTION_EVENT_AXIS_X:
5037 case AMOTION_EVENT_AXIS_Y:
5038 case AMOTION_EVENT_AXIS_Z:
5039 case AMOTION_EVENT_AXIS_RX:
5040 case AMOTION_EVENT_AXIS_RY:
5041 case AMOTION_EVENT_AXIS_RZ:
5042 case AMOTION_EVENT_AXIS_HAT_X:
5043 case AMOTION_EVENT_AXIS_HAT_Y:
5044 case AMOTION_EVENT_AXIS_ORIENTATION:
Jeff Brown85297452011-03-04 13:07:49 -08005045 case AMOTION_EVENT_AXIS_RUDDER:
5046 case AMOTION_EVENT_AXIS_WHEEL:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005047 return true;
5048 default:
5049 return false;
5050 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005051}
5052
5053void JoystickInputMapper::reset() {
5054 // Recenter all axes.
5055 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Browncb1404e2011-01-15 18:14:15 -08005056
Jeff Brown6f2fba42011-02-19 01:08:02 -08005057 size_t numAxes = mAxes.size();
5058 for (size_t i = 0; i < numAxes; i++) {
5059 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005060 axis.resetValue();
Jeff Brown6f2fba42011-02-19 01:08:02 -08005061 }
5062
5063 sync(when, true /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005064
5065 InputMapper::reset();
5066}
5067
5068void JoystickInputMapper::process(const RawEvent* rawEvent) {
5069 switch (rawEvent->type) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005070 case EV_ABS: {
5071 ssize_t index = mAxes.indexOfKey(rawEvent->scanCode);
5072 if (index >= 0) {
5073 Axis& axis = mAxes.editValueAt(index);
Jeff Brown85297452011-03-04 13:07:49 -08005074 float newValue, highNewValue;
5075 switch (axis.axisInfo.mode) {
5076 case AxisInfo::MODE_INVERT:
5077 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
5078 * axis.scale + axis.offset;
5079 highNewValue = 0.0f;
5080 break;
5081 case AxisInfo::MODE_SPLIT:
5082 if (rawEvent->value < axis.axisInfo.splitValue) {
5083 newValue = (axis.axisInfo.splitValue - rawEvent->value)
5084 * axis.scale + axis.offset;
5085 highNewValue = 0.0f;
5086 } else if (rawEvent->value > axis.axisInfo.splitValue) {
5087 newValue = 0.0f;
5088 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
5089 * axis.highScale + axis.highOffset;
5090 } else {
5091 newValue = 0.0f;
5092 highNewValue = 0.0f;
5093 }
5094 break;
5095 default:
5096 newValue = rawEvent->value * axis.scale + axis.offset;
5097 highNewValue = 0.0f;
5098 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005099 }
Jeff Brown85297452011-03-04 13:07:49 -08005100 axis.newValue = newValue;
5101 axis.highNewValue = highNewValue;
Jeff Browncb1404e2011-01-15 18:14:15 -08005102 }
5103 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005104 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005105
5106 case EV_SYN:
5107 switch (rawEvent->scanCode) {
5108 case SYN_REPORT:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005109 sync(rawEvent->when, false /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005110 break;
5111 }
5112 break;
5113 }
5114}
5115
Jeff Brown6f2fba42011-02-19 01:08:02 -08005116void JoystickInputMapper::sync(nsecs_t when, bool force) {
Jeff Brown85297452011-03-04 13:07:49 -08005117 if (!filterAxes(force)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005118 return;
Jeff Browncb1404e2011-01-15 18:14:15 -08005119 }
5120
5121 int32_t metaState = mContext->getGlobalMetaState();
5122
Jeff Brown6f2fba42011-02-19 01:08:02 -08005123 PointerCoords pointerCoords;
5124 pointerCoords.clear();
5125
5126 size_t numAxes = mAxes.size();
5127 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005128 const Axis& axis = mAxes.valueAt(i);
5129 pointerCoords.setAxisValue(axis.axisInfo.axis, axis.currentValue);
5130 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5131 pointerCoords.setAxisValue(axis.axisInfo.highAxis, axis.highCurrentValue);
5132 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005133 }
5134
Jeff Brown56194eb2011-03-02 19:23:13 -08005135 // Moving a joystick axis should not wake the devide because joysticks can
5136 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
5137 // button will likely wake the device.
5138 // TODO: Use the input device configuration to control this behavior more finely.
5139 uint32_t policyFlags = 0;
5140
Jeff Brown6f2fba42011-02-19 01:08:02 -08005141 int32_t pointerId = 0;
Jeff Brown56194eb2011-03-02 19:23:13 -08005142 getDispatcher()->notifyMotion(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Jeff Brown6f2fba42011-02-19 01:08:02 -08005143 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
5144 1, &pointerId, &pointerCoords, 0, 0, 0);
Jeff Browncb1404e2011-01-15 18:14:15 -08005145}
5146
Jeff Brown85297452011-03-04 13:07:49 -08005147bool JoystickInputMapper::filterAxes(bool force) {
5148 bool atLeastOneSignificantChange = force;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005149 size_t numAxes = mAxes.size();
5150 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005151 Axis& axis = mAxes.editValueAt(i);
5152 if (force || hasValueChangedSignificantly(axis.filter,
5153 axis.newValue, axis.currentValue, axis.min, axis.max)) {
5154 axis.currentValue = axis.newValue;
5155 atLeastOneSignificantChange = true;
5156 }
5157 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5158 if (force || hasValueChangedSignificantly(axis.filter,
5159 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
5160 axis.highCurrentValue = axis.highNewValue;
5161 atLeastOneSignificantChange = true;
5162 }
5163 }
5164 }
5165 return atLeastOneSignificantChange;
5166}
5167
5168bool JoystickInputMapper::hasValueChangedSignificantly(
5169 float filter, float newValue, float currentValue, float min, float max) {
5170 if (newValue != currentValue) {
5171 // Filter out small changes in value unless the value is converging on the axis
5172 // bounds or center point. This is intended to reduce the amount of information
5173 // sent to applications by particularly noisy joysticks (such as PS3).
5174 if (fabs(newValue - currentValue) > filter
5175 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
5176 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
5177 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
5178 return true;
5179 }
5180 }
5181 return false;
5182}
5183
5184bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
5185 float filter, float newValue, float currentValue, float thresholdValue) {
5186 float newDistance = fabs(newValue - thresholdValue);
5187 if (newDistance < filter) {
5188 float oldDistance = fabs(currentValue - thresholdValue);
5189 if (newDistance < oldDistance) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005190 return true;
5191 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005192 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08005193 return false;
Jeff Browncb1404e2011-01-15 18:14:15 -08005194}
5195
Jeff Brown46b9ac02010-04-22 18:58:52 -07005196} // namespace android