blob: 182bd50d6150bf059bc85105a0f3da4cbe780195 [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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brownace13b12011-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -070045
46#include <stddef.h>
Jeff Brown8d608662010-08-30 03:02:23 -070047#include <stdlib.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070048#include <unistd.h>
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -070058namespace android {
59
Jeff Brownace13b12011-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 Brown46b9ac0a2010-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 Brownace13b12011-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 Brown46b9ac0a2010-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 Brownfd0358292010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700152};
Jeff Brown9626b142011-03-03 02:09:54 -0800153static const size_t keyCodeRotationMapSize =
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700227
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brownaa3855d2011-03-17 01:34:19 -0700234 mGlobalMetaState(0), mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX) {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700235 configureExcludedDevices();
Jeff Brown6d0fec22010-07-23 21:28:06 -0700236 updateGlobalMetaState();
237 updateInputConfiguration();
Jeff Brown46b9ac0a2010-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() {
Jeff Brownaa3855d2011-03-17 01:34:19 -0700247 int32_t timeoutMillis = -1;
248 if (mNextTimeout != LLONG_MAX) {
249 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
250 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
251 }
252
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700253 RawEvent rawEvent;
Jeff Brownaa3855d2011-03-17 01:34:19 -0700254 if (mEventHub->getEvent(timeoutMillis, &rawEvent)) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700255#if DEBUG_RAW_EVENTS
Jeff Brownaa3855d2011-03-17 01:34:19 -0700256 LOGD("Input event: device=%d type=0x%04x scancode=0x%04x keycode=0x%04x value=0x%04x",
257 rawEvent.deviceId, rawEvent.type, rawEvent.scanCode, rawEvent.keyCode,
258 rawEvent.value);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700259#endif
Jeff Brownaa3855d2011-03-17 01:34:19 -0700260 process(&rawEvent);
261 } else {
262 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
263#if DEBUG_RAW_EVENTS
264 LOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
265#endif
266 mNextTimeout = LLONG_MAX;
267 timeoutExpired(now);
268 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700269}
270
271void InputReader::process(const RawEvent* rawEvent) {
272 switch (rawEvent->type) {
273 case EventHubInterface::DEVICE_ADDED:
Jeff Brown7342bb92010-10-01 18:55:43 -0700274 addDevice(rawEvent->deviceId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700275 break;
276
277 case EventHubInterface::DEVICE_REMOVED:
Jeff Brown7342bb92010-10-01 18:55:43 -0700278 removeDevice(rawEvent->deviceId);
279 break;
280
281 case EventHubInterface::FINISHED_DEVICE_SCAN:
Jeff Brownc3db8582010-10-20 15:33:38 -0700282 handleConfigurationChanged(rawEvent->when);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700283 break;
284
Jeff Brown6d0fec22010-07-23 21:28:06 -0700285 default:
286 consumeEvent(rawEvent);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700287 break;
288 }
289}
290
Jeff Brown7342bb92010-10-01 18:55:43 -0700291void InputReader::addDevice(int32_t deviceId) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700292 String8 name = mEventHub->getDeviceName(deviceId);
293 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
294
295 InputDevice* device = createDevice(deviceId, name, classes);
296 device->configure();
297
Jeff Brown8d608662010-08-30 03:02:23 -0700298 if (device->isIgnored()) {
Jeff Brown90655042010-12-02 13:50:46 -0800299 LOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, name.string());
Jeff Brown8d608662010-08-30 03:02:23 -0700300 } else {
Jeff Brown90655042010-12-02 13:50:46 -0800301 LOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, name.string(),
Jeff Brownef3d7e82010-09-30 14:33:04 -0700302 device->getSources());
Jeff Brown8d608662010-08-30 03:02:23 -0700303 }
304
Jeff Brown6d0fec22010-07-23 21:28:06 -0700305 bool added = false;
306 { // acquire device registry writer lock
307 RWLock::AutoWLock _wl(mDeviceRegistryLock);
308
309 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
310 if (deviceIndex < 0) {
311 mDevices.add(deviceId, device);
312 added = true;
313 }
314 } // release device registry writer lock
315
316 if (! added) {
317 LOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
318 delete device;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700319 return;
320 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700321}
322
Jeff Brown7342bb92010-10-01 18:55:43 -0700323void InputReader::removeDevice(int32_t deviceId) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700324 bool removed = false;
325 InputDevice* device = NULL;
326 { // acquire device registry writer lock
327 RWLock::AutoWLock _wl(mDeviceRegistryLock);
328
329 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
330 if (deviceIndex >= 0) {
331 device = mDevices.valueAt(deviceIndex);
332 mDevices.removeItemsAt(deviceIndex, 1);
333 removed = true;
334 }
335 } // release device registry writer lock
336
337 if (! removed) {
338 LOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700339 return;
340 }
341
Jeff Brown6d0fec22010-07-23 21:28:06 -0700342 if (device->isIgnored()) {
Jeff Brown90655042010-12-02 13:50:46 -0800343 LOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Jeff Brown6d0fec22010-07-23 21:28:06 -0700344 device->getId(), device->getName().string());
345 } else {
Jeff Brown90655042010-12-02 13:50:46 -0800346 LOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Jeff Brown6d0fec22010-07-23 21:28:06 -0700347 device->getId(), device->getName().string(), device->getSources());
348 }
349
Jeff Brown8d608662010-08-30 03:02:23 -0700350 device->reset();
351
Jeff Brown6d0fec22010-07-23 21:28:06 -0700352 delete device;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700353}
354
Jeff Brown6d0fec22010-07-23 21:28:06 -0700355InputDevice* InputReader::createDevice(int32_t deviceId, const String8& name, uint32_t classes) {
356 InputDevice* device = new InputDevice(this, deviceId, name);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700357
Jeff Brown56194eb2011-03-02 19:23:13 -0800358 // External devices.
359 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
360 device->setExternal(true);
361 }
362
Jeff Brown6d0fec22010-07-23 21:28:06 -0700363 // Switch-like devices.
364 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
365 device->addMapper(new SwitchInputMapper(device));
366 }
367
368 // Keyboard-like devices.
Jeff Brownefd32662011-03-08 15:13:06 -0800369 uint32_t keyboardSource = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700370 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
371 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800372 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700373 }
374 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
375 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
376 }
377 if (classes & INPUT_DEVICE_CLASS_DPAD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800378 keyboardSource |= AINPUT_SOURCE_DPAD;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700379 }
Jeff Browncb1404e2011-01-15 18:14:15 -0800380 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800381 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
Jeff Browncb1404e2011-01-15 18:14:15 -0800382 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700383
Jeff Brownefd32662011-03-08 15:13:06 -0800384 if (keyboardSource != 0) {
385 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700386 }
387
Jeff Brown83c09682010-12-23 17:50:18 -0800388 // Cursor-like devices.
389 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
390 device->addMapper(new CursorInputMapper(device));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700391 }
392
Jeff Brown58a2da82011-01-25 16:02:22 -0800393 // Touchscreens and touchpad devices.
394 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800395 device->addMapper(new MultiTouchInputMapper(device));
Jeff Brown58a2da82011-01-25 16:02:22 -0800396 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800397 device->addMapper(new SingleTouchInputMapper(device));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700398 }
399
Jeff Browncb1404e2011-01-15 18:14:15 -0800400 // Joystick-like devices.
401 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
402 device->addMapper(new JoystickInputMapper(device));
403 }
404
Jeff Brown6d0fec22010-07-23 21:28:06 -0700405 return device;
406}
407
408void InputReader::consumeEvent(const RawEvent* rawEvent) {
409 int32_t deviceId = rawEvent->deviceId;
410
411 { // acquire device registry reader lock
412 RWLock::AutoRLock _rl(mDeviceRegistryLock);
413
414 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
415 if (deviceIndex < 0) {
416 LOGW("Discarding event for unknown deviceId %d.", deviceId);
417 return;
418 }
419
420 InputDevice* device = mDevices.valueAt(deviceIndex);
421 if (device->isIgnored()) {
422 //LOGD("Discarding event for ignored deviceId %d.", deviceId);
423 return;
424 }
425
426 device->process(rawEvent);
427 } // release device registry reader lock
428}
429
Jeff Brownaa3855d2011-03-17 01:34:19 -0700430void InputReader::timeoutExpired(nsecs_t when) {
431 { // acquire device registry reader lock
432 RWLock::AutoRLock _rl(mDeviceRegistryLock);
433
434 for (size_t i = 0; i < mDevices.size(); i++) {
435 InputDevice* device = mDevices.valueAt(i);
436 if (!device->isIgnored()) {
437 device->timeoutExpired(when);
438 }
439 }
440 } // release device registry reader lock
441}
442
Jeff Brownc3db8582010-10-20 15:33:38 -0700443void InputReader::handleConfigurationChanged(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700444 // Reset global meta state because it depends on the list of all configured devices.
445 updateGlobalMetaState();
446
447 // Update input configuration.
448 updateInputConfiguration();
449
450 // Enqueue configuration changed.
451 mDispatcher->notifyConfigurationChanged(when);
452}
453
454void InputReader::configureExcludedDevices() {
455 Vector<String8> excludedDeviceNames;
456 mPolicy->getExcludedDeviceNames(excludedDeviceNames);
457
458 for (size_t i = 0; i < excludedDeviceNames.size(); i++) {
459 mEventHub->addExcludedDevice(excludedDeviceNames[i]);
460 }
461}
462
463void InputReader::updateGlobalMetaState() {
464 { // acquire state lock
465 AutoMutex _l(mStateLock);
466
467 mGlobalMetaState = 0;
468
469 { // acquire device registry reader lock
470 RWLock::AutoRLock _rl(mDeviceRegistryLock);
471
472 for (size_t i = 0; i < mDevices.size(); i++) {
473 InputDevice* device = mDevices.valueAt(i);
474 mGlobalMetaState |= device->getMetaState();
475 }
476 } // release device registry reader lock
477 } // release state lock
478}
479
480int32_t InputReader::getGlobalMetaState() {
481 { // acquire state lock
482 AutoMutex _l(mStateLock);
483
484 return mGlobalMetaState;
485 } // release state lock
486}
487
488void InputReader::updateInputConfiguration() {
489 { // acquire state lock
490 AutoMutex _l(mStateLock);
491
492 int32_t touchScreenConfig = InputConfiguration::TOUCHSCREEN_NOTOUCH;
493 int32_t keyboardConfig = InputConfiguration::KEYBOARD_NOKEYS;
494 int32_t navigationConfig = InputConfiguration::NAVIGATION_NONAV;
495 { // acquire device registry reader lock
496 RWLock::AutoRLock _rl(mDeviceRegistryLock);
497
498 InputDeviceInfo deviceInfo;
499 for (size_t i = 0; i < mDevices.size(); i++) {
500 InputDevice* device = mDevices.valueAt(i);
501 device->getDeviceInfo(& deviceInfo);
502 uint32_t sources = deviceInfo.getSources();
503
504 if ((sources & AINPUT_SOURCE_TOUCHSCREEN) == AINPUT_SOURCE_TOUCHSCREEN) {
505 touchScreenConfig = InputConfiguration::TOUCHSCREEN_FINGER;
506 }
507 if ((sources & AINPUT_SOURCE_TRACKBALL) == AINPUT_SOURCE_TRACKBALL) {
508 navigationConfig = InputConfiguration::NAVIGATION_TRACKBALL;
509 } else if ((sources & AINPUT_SOURCE_DPAD) == AINPUT_SOURCE_DPAD) {
510 navigationConfig = InputConfiguration::NAVIGATION_DPAD;
511 }
512 if (deviceInfo.getKeyboardType() == AINPUT_KEYBOARD_TYPE_ALPHABETIC) {
513 keyboardConfig = InputConfiguration::KEYBOARD_QWERTY;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700514 }
515 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700516 } // release device registry reader lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700517
Jeff Brown6d0fec22010-07-23 21:28:06 -0700518 mInputConfiguration.touchScreen = touchScreenConfig;
519 mInputConfiguration.keyboard = keyboardConfig;
520 mInputConfiguration.navigation = navigationConfig;
521 } // release state lock
522}
523
Jeff Brownfe508922011-01-18 15:10:10 -0800524void InputReader::disableVirtualKeysUntil(nsecs_t time) {
525 mDisableVirtualKeysTimeout = time;
526}
527
528bool InputReader::shouldDropVirtualKey(nsecs_t now,
529 InputDevice* device, int32_t keyCode, int32_t scanCode) {
530 if (now < mDisableVirtualKeysTimeout) {
531 LOGI("Dropping virtual key from device %s because virtual keys are "
532 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
533 device->getName().string(),
534 (mDisableVirtualKeysTimeout - now) * 0.000001,
535 keyCode, scanCode);
536 return true;
537 } else {
538 return false;
539 }
540}
541
Jeff Brown05dc66a2011-03-02 14:41:58 -0800542void InputReader::fadePointer() {
543 { // acquire device registry reader lock
544 RWLock::AutoRLock _rl(mDeviceRegistryLock);
545
546 for (size_t i = 0; i < mDevices.size(); i++) {
547 InputDevice* device = mDevices.valueAt(i);
548 device->fadePointer();
549 }
550 } // release device registry reader lock
551}
552
Jeff Brownaa3855d2011-03-17 01:34:19 -0700553void InputReader::requestTimeoutAtTime(nsecs_t when) {
554 if (when < mNextTimeout) {
555 mNextTimeout = when;
556 }
557}
558
Jeff Brown6d0fec22010-07-23 21:28:06 -0700559void InputReader::getInputConfiguration(InputConfiguration* outConfiguration) {
560 { // acquire state lock
561 AutoMutex _l(mStateLock);
562
563 *outConfiguration = mInputConfiguration;
564 } // release state lock
565}
566
567status_t InputReader::getInputDeviceInfo(int32_t deviceId, InputDeviceInfo* outDeviceInfo) {
568 { // acquire device registry reader lock
569 RWLock::AutoRLock _rl(mDeviceRegistryLock);
570
571 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
572 if (deviceIndex < 0) {
573 return NAME_NOT_FOUND;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700574 }
575
Jeff Brown6d0fec22010-07-23 21:28:06 -0700576 InputDevice* device = mDevices.valueAt(deviceIndex);
577 if (device->isIgnored()) {
578 return NAME_NOT_FOUND;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700579 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700580
581 device->getDeviceInfo(outDeviceInfo);
582 return OK;
583 } // release device registy reader lock
584}
585
586void InputReader::getInputDeviceIds(Vector<int32_t>& outDeviceIds) {
587 outDeviceIds.clear();
588
589 { // acquire device registry reader lock
590 RWLock::AutoRLock _rl(mDeviceRegistryLock);
591
592 size_t numDevices = mDevices.size();
593 for (size_t i = 0; i < numDevices; i++) {
594 InputDevice* device = mDevices.valueAt(i);
595 if (! device->isIgnored()) {
596 outDeviceIds.add(device->getId());
597 }
598 }
599 } // release device registy reader lock
600}
601
602int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
603 int32_t keyCode) {
604 return getState(deviceId, sourceMask, keyCode, & InputDevice::getKeyCodeState);
605}
606
607int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
608 int32_t scanCode) {
609 return getState(deviceId, sourceMask, scanCode, & InputDevice::getScanCodeState);
610}
611
612int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
613 return getState(deviceId, sourceMask, switchCode, & InputDevice::getSwitchState);
614}
615
616int32_t InputReader::getState(int32_t deviceId, uint32_t sourceMask, int32_t code,
617 GetStateFunc getStateFunc) {
618 { // acquire device registry reader lock
619 RWLock::AutoRLock _rl(mDeviceRegistryLock);
620
621 int32_t result = AKEY_STATE_UNKNOWN;
622 if (deviceId >= 0) {
623 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
624 if (deviceIndex >= 0) {
625 InputDevice* device = mDevices.valueAt(deviceIndex);
626 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
627 result = (device->*getStateFunc)(sourceMask, code);
628 }
629 }
630 } else {
631 size_t numDevices = mDevices.size();
632 for (size_t i = 0; i < numDevices; i++) {
633 InputDevice* device = mDevices.valueAt(i);
634 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
635 result = (device->*getStateFunc)(sourceMask, code);
636 if (result >= AKEY_STATE_DOWN) {
637 return result;
638 }
639 }
640 }
641 }
642 return result;
643 } // release device registy reader lock
644}
645
646bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
647 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
648 memset(outFlags, 0, numCodes);
649 return markSupportedKeyCodes(deviceId, sourceMask, numCodes, keyCodes, outFlags);
650}
651
652bool InputReader::markSupportedKeyCodes(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
653 const int32_t* keyCodes, uint8_t* outFlags) {
654 { // acquire device registry reader lock
655 RWLock::AutoRLock _rl(mDeviceRegistryLock);
656 bool result = false;
657 if (deviceId >= 0) {
658 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
659 if (deviceIndex >= 0) {
660 InputDevice* device = mDevices.valueAt(deviceIndex);
661 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
662 result = device->markSupportedKeyCodes(sourceMask,
663 numCodes, keyCodes, outFlags);
664 }
665 }
666 } else {
667 size_t numDevices = mDevices.size();
668 for (size_t i = 0; i < numDevices; i++) {
669 InputDevice* device = mDevices.valueAt(i);
670 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
671 result |= device->markSupportedKeyCodes(sourceMask,
672 numCodes, keyCodes, outFlags);
673 }
674 }
675 }
676 return result;
677 } // release device registy reader lock
678}
679
Jeff Brownb88102f2010-09-08 11:49:43 -0700680void InputReader::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -0700681 mEventHub->dump(dump);
682 dump.append("\n");
683
684 dump.append("Input Reader State:\n");
685
Jeff Brownef3d7e82010-09-30 14:33:04 -0700686 { // acquire device registry reader lock
687 RWLock::AutoRLock _rl(mDeviceRegistryLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700688
Jeff Brownef3d7e82010-09-30 14:33:04 -0700689 for (size_t i = 0; i < mDevices.size(); i++) {
690 mDevices.valueAt(i)->dump(dump);
Jeff Brownb88102f2010-09-08 11:49:43 -0700691 }
Jeff Brownef3d7e82010-09-30 14:33:04 -0700692 } // release device registy reader lock
Jeff Brownb88102f2010-09-08 11:49:43 -0700693}
694
Jeff Brown6d0fec22010-07-23 21:28:06 -0700695
696// --- InputReaderThread ---
697
698InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
699 Thread(/*canCallJava*/ true), mReader(reader) {
700}
701
702InputReaderThread::~InputReaderThread() {
703}
704
705bool InputReaderThread::threadLoop() {
706 mReader->loopOnce();
707 return true;
708}
709
710
711// --- InputDevice ---
712
713InputDevice::InputDevice(InputReaderContext* context, int32_t id, const String8& name) :
Jeff Brown56194eb2011-03-02 19:23:13 -0800714 mContext(context), mId(id), mName(name), mSources(0), mIsExternal(false) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700715}
716
717InputDevice::~InputDevice() {
718 size_t numMappers = mMappers.size();
719 for (size_t i = 0; i < numMappers; i++) {
720 delete mMappers[i];
721 }
722 mMappers.clear();
723}
724
Jeff Brownef3d7e82010-09-30 14:33:04 -0700725void InputDevice::dump(String8& dump) {
726 InputDeviceInfo deviceInfo;
727 getDeviceInfo(& deviceInfo);
728
Jeff Brown90655042010-12-02 13:50:46 -0800729 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
Jeff Brownef3d7e82010-09-30 14:33:04 -0700730 deviceInfo.getName().string());
Jeff Brown56194eb2011-03-02 19:23:13 -0800731 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Jeff Brownef3d7e82010-09-30 14:33:04 -0700732 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
733 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Jeff Browncc0c1592011-02-19 05:07:28 -0800734
Jeff Brownefd32662011-03-08 15:13:06 -0800735 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
Jeff Browncc0c1592011-02-19 05:07:28 -0800736 if (!ranges.isEmpty()) {
Jeff Brownef3d7e82010-09-30 14:33:04 -0700737 dump.append(INDENT2 "Motion Ranges:\n");
Jeff Browncc0c1592011-02-19 05:07:28 -0800738 for (size_t i = 0; i < ranges.size(); i++) {
Jeff Brownefd32662011-03-08 15:13:06 -0800739 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
740 const char* label = getAxisLabel(range.axis);
Jeff Browncc0c1592011-02-19 05:07:28 -0800741 char name[32];
742 if (label) {
743 strncpy(name, label, sizeof(name));
744 name[sizeof(name) - 1] = '\0';
745 } else {
Jeff Brownefd32662011-03-08 15:13:06 -0800746 snprintf(name, sizeof(name), "%d", range.axis);
Jeff Browncc0c1592011-02-19 05:07:28 -0800747 }
Jeff Brownefd32662011-03-08 15:13:06 -0800748 dump.appendFormat(INDENT3 "%s: source=0x%08x, "
749 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f\n",
750 name, range.source, range.min, range.max, range.flat, range.fuzz);
Jeff Browncc0c1592011-02-19 05:07:28 -0800751 }
Jeff Brownef3d7e82010-09-30 14:33:04 -0700752 }
753
754 size_t numMappers = mMappers.size();
755 for (size_t i = 0; i < numMappers; i++) {
756 InputMapper* mapper = mMappers[i];
757 mapper->dump(dump);
758 }
759}
760
Jeff Brown6d0fec22010-07-23 21:28:06 -0700761void InputDevice::addMapper(InputMapper* mapper) {
762 mMappers.add(mapper);
763}
764
765void InputDevice::configure() {
Jeff Brown8d608662010-08-30 03:02:23 -0700766 if (! isIgnored()) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800767 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
Jeff Brown8d608662010-08-30 03:02:23 -0700768 }
769
Jeff Brown6d0fec22010-07-23 21:28:06 -0700770 mSources = 0;
771
772 size_t numMappers = mMappers.size();
773 for (size_t i = 0; i < numMappers; i++) {
774 InputMapper* mapper = mMappers[i];
775 mapper->configure();
776 mSources |= mapper->getSources();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700777 }
778}
779
Jeff Brown6d0fec22010-07-23 21:28:06 -0700780void InputDevice::reset() {
781 size_t numMappers = mMappers.size();
782 for (size_t i = 0; i < numMappers; i++) {
783 InputMapper* mapper = mMappers[i];
784 mapper->reset();
785 }
786}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700787
Jeff Brown6d0fec22010-07-23 21:28:06 -0700788void InputDevice::process(const RawEvent* rawEvent) {
789 size_t numMappers = mMappers.size();
790 for (size_t i = 0; i < numMappers; i++) {
791 InputMapper* mapper = mMappers[i];
792 mapper->process(rawEvent);
793 }
794}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700795
Jeff Brownaa3855d2011-03-17 01:34:19 -0700796void InputDevice::timeoutExpired(nsecs_t when) {
797 size_t numMappers = mMappers.size();
798 for (size_t i = 0; i < numMappers; i++) {
799 InputMapper* mapper = mMappers[i];
800 mapper->timeoutExpired(when);
801 }
802}
803
Jeff Brown6d0fec22010-07-23 21:28:06 -0700804void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
805 outDeviceInfo->initialize(mId, mName);
806
807 size_t numMappers = mMappers.size();
808 for (size_t i = 0; i < numMappers; i++) {
809 InputMapper* mapper = mMappers[i];
810 mapper->populateDeviceInfo(outDeviceInfo);
811 }
812}
813
814int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
815 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
816}
817
818int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
819 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
820}
821
822int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
823 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
824}
825
826int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
827 int32_t result = AKEY_STATE_UNKNOWN;
828 size_t numMappers = mMappers.size();
829 for (size_t i = 0; i < numMappers; i++) {
830 InputMapper* mapper = mMappers[i];
831 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
832 result = (mapper->*getStateFunc)(sourceMask, code);
833 if (result >= AKEY_STATE_DOWN) {
834 return result;
835 }
836 }
837 }
838 return result;
839}
840
841bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
842 const int32_t* keyCodes, uint8_t* outFlags) {
843 bool result = false;
844 size_t numMappers = mMappers.size();
845 for (size_t i = 0; i < numMappers; i++) {
846 InputMapper* mapper = mMappers[i];
847 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
848 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
849 }
850 }
851 return result;
852}
853
854int32_t InputDevice::getMetaState() {
855 int32_t result = 0;
856 size_t numMappers = mMappers.size();
857 for (size_t i = 0; i < numMappers; i++) {
858 InputMapper* mapper = mMappers[i];
859 result |= mapper->getMetaState();
860 }
861 return result;
862}
863
Jeff Brown05dc66a2011-03-02 14:41:58 -0800864void InputDevice::fadePointer() {
865 size_t numMappers = mMappers.size();
866 for (size_t i = 0; i < numMappers; i++) {
867 InputMapper* mapper = mMappers[i];
868 mapper->fadePointer();
869 }
870}
871
Jeff Brown6d0fec22010-07-23 21:28:06 -0700872
873// --- InputMapper ---
874
875InputMapper::InputMapper(InputDevice* device) :
876 mDevice(device), mContext(device->getContext()) {
877}
878
879InputMapper::~InputMapper() {
880}
881
882void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
883 info->addSource(getSources());
884}
885
Jeff Brownef3d7e82010-09-30 14:33:04 -0700886void InputMapper::dump(String8& dump) {
887}
888
Jeff Brown6d0fec22010-07-23 21:28:06 -0700889void InputMapper::configure() {
890}
891
892void InputMapper::reset() {
893}
894
Jeff Brownaa3855d2011-03-17 01:34:19 -0700895void InputMapper::timeoutExpired(nsecs_t when) {
896}
897
Jeff Brown6d0fec22010-07-23 21:28:06 -0700898int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
899 return AKEY_STATE_UNKNOWN;
900}
901
902int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
903 return AKEY_STATE_UNKNOWN;
904}
905
906int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
907 return AKEY_STATE_UNKNOWN;
908}
909
910bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
911 const int32_t* keyCodes, uint8_t* outFlags) {
912 return false;
913}
914
915int32_t InputMapper::getMetaState() {
916 return 0;
917}
918
Jeff Brown05dc66a2011-03-02 14:41:58 -0800919void InputMapper::fadePointer() {
920}
921
Jeff Browncb1404e2011-01-15 18:14:15 -0800922void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
923 const RawAbsoluteAxisInfo& axis, const char* name) {
924 if (axis.valid) {
925 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d\n",
926 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz);
927 } else {
928 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
929 }
930}
931
Jeff Brown6d0fec22010-07-23 21:28:06 -0700932
933// --- SwitchInputMapper ---
934
935SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
936 InputMapper(device) {
937}
938
939SwitchInputMapper::~SwitchInputMapper() {
940}
941
942uint32_t SwitchInputMapper::getSources() {
Jeff Brown89de57a2011-01-19 18:41:38 -0800943 return AINPUT_SOURCE_SWITCH;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700944}
945
946void SwitchInputMapper::process(const RawEvent* rawEvent) {
947 switch (rawEvent->type) {
948 case EV_SW:
949 processSwitch(rawEvent->when, rawEvent->scanCode, rawEvent->value);
950 break;
951 }
952}
953
954void SwitchInputMapper::processSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue) {
Jeff Brownb6997262010-10-08 22:31:17 -0700955 getDispatcher()->notifySwitch(when, switchCode, switchValue, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -0700956}
957
958int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
959 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
960}
961
962
963// --- KeyboardInputMapper ---
964
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800965KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
Jeff Brownefd32662011-03-08 15:13:06 -0800966 uint32_t source, int32_t keyboardType) :
967 InputMapper(device), mSource(source),
Jeff Brown6d0fec22010-07-23 21:28:06 -0700968 mKeyboardType(keyboardType) {
Jeff Brown6328cdc2010-07-29 18:18:33 -0700969 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -0700970}
971
972KeyboardInputMapper::~KeyboardInputMapper() {
973}
974
Jeff Brown6328cdc2010-07-29 18:18:33 -0700975void KeyboardInputMapper::initializeLocked() {
976 mLocked.metaState = AMETA_NONE;
977 mLocked.downTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700978}
979
980uint32_t KeyboardInputMapper::getSources() {
Jeff Brownefd32662011-03-08 15:13:06 -0800981 return mSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700982}
983
984void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
985 InputMapper::populateDeviceInfo(info);
986
987 info->setKeyboardType(mKeyboardType);
988}
989
Jeff Brownef3d7e82010-09-30 14:33:04 -0700990void KeyboardInputMapper::dump(String8& dump) {
991 { // acquire lock
992 AutoMutex _l(mLock);
993 dump.append(INDENT2 "Keyboard Input Mapper:\n");
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800994 dumpParameters(dump);
Jeff Brownef3d7e82010-09-30 14:33:04 -0700995 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
996 dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mLocked.keyDowns.size());
997 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mLocked.metaState);
998 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
999 } // release lock
1000}
1001
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001002
1003void KeyboardInputMapper::configure() {
1004 InputMapper::configure();
1005
1006 // Configure basic parameters.
1007 configureParameters();
Jeff Brown49ed71d2010-12-06 17:13:33 -08001008
1009 // Reset LEDs.
1010 {
1011 AutoMutex _l(mLock);
1012 resetLedStateLocked();
1013 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001014}
1015
1016void KeyboardInputMapper::configureParameters() {
1017 mParameters.orientationAware = false;
1018 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
1019 mParameters.orientationAware);
1020
1021 mParameters.associatedDisplayId = mParameters.orientationAware ? 0 : -1;
1022}
1023
1024void KeyboardInputMapper::dumpParameters(String8& dump) {
1025 dump.append(INDENT3 "Parameters:\n");
1026 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1027 mParameters.associatedDisplayId);
1028 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1029 toString(mParameters.orientationAware));
1030}
1031
Jeff Brown6d0fec22010-07-23 21:28:06 -07001032void KeyboardInputMapper::reset() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001033 for (;;) {
1034 int32_t keyCode, scanCode;
1035 { // acquire lock
1036 AutoMutex _l(mLock);
1037
1038 // Synthesize key up event on reset if keys are currently down.
1039 if (mLocked.keyDowns.isEmpty()) {
1040 initializeLocked();
Jeff Brown49ed71d2010-12-06 17:13:33 -08001041 resetLedStateLocked();
Jeff Brown6328cdc2010-07-29 18:18:33 -07001042 break; // done
1043 }
1044
1045 const KeyDown& keyDown = mLocked.keyDowns.top();
1046 keyCode = keyDown.keyCode;
1047 scanCode = keyDown.scanCode;
1048 } // release lock
1049
Jeff Brown6d0fec22010-07-23 21:28:06 -07001050 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown6328cdc2010-07-29 18:18:33 -07001051 processKey(when, false, keyCode, scanCode, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001052 }
1053
1054 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001055 getContext()->updateGlobalMetaState();
1056}
1057
1058void KeyboardInputMapper::process(const RawEvent* rawEvent) {
1059 switch (rawEvent->type) {
1060 case EV_KEY: {
1061 int32_t scanCode = rawEvent->scanCode;
1062 if (isKeyboardOrGamepadKey(scanCode)) {
1063 processKey(rawEvent->when, rawEvent->value != 0, rawEvent->keyCode, scanCode,
1064 rawEvent->flags);
1065 }
1066 break;
1067 }
1068 }
1069}
1070
1071bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
1072 return scanCode < BTN_MOUSE
1073 || scanCode >= KEY_OK
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001074 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
Jeff Browncb1404e2011-01-15 18:14:15 -08001075 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001076}
1077
Jeff Brown6328cdc2010-07-29 18:18:33 -07001078void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode,
1079 int32_t scanCode, uint32_t policyFlags) {
1080 int32_t newMetaState;
1081 nsecs_t downTime;
1082 bool metaStateChanged = false;
1083
1084 { // acquire lock
1085 AutoMutex _l(mLock);
1086
1087 if (down) {
1088 // Rotate key codes according to orientation if needed.
1089 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001090 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001091 int32_t orientation;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001092 if (!getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1093 NULL, NULL, & orientation)) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001094 orientation = DISPLAY_ORIENTATION_0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001095 }
1096
1097 keyCode = rotateKeyCode(keyCode, orientation);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001098 }
1099
Jeff Brown6328cdc2010-07-29 18:18:33 -07001100 // Add key down.
1101 ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1102 if (keyDownIndex >= 0) {
1103 // key repeat, be sure to use same keycode as before in case of rotation
Jeff Brown6b53e8d2010-11-10 16:03:06 -08001104 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001105 } else {
1106 // key down
Jeff Brownfe508922011-01-18 15:10:10 -08001107 if ((policyFlags & POLICY_FLAG_VIRTUAL)
1108 && mContext->shouldDropVirtualKey(when,
1109 getDevice(), keyCode, scanCode)) {
1110 return;
1111 }
1112
Jeff Brown6328cdc2010-07-29 18:18:33 -07001113 mLocked.keyDowns.push();
1114 KeyDown& keyDown = mLocked.keyDowns.editTop();
1115 keyDown.keyCode = keyCode;
1116 keyDown.scanCode = scanCode;
1117 }
1118
1119 mLocked.downTime = when;
1120 } else {
1121 // Remove key down.
1122 ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1123 if (keyDownIndex >= 0) {
1124 // key up, be sure to use same keycode as before in case of rotation
Jeff Brown6b53e8d2010-11-10 16:03:06 -08001125 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001126 mLocked.keyDowns.removeAt(size_t(keyDownIndex));
1127 } else {
1128 // key was not actually down
1129 LOGI("Dropping key up from device %s because the key was not down. "
1130 "keyCode=%d, scanCode=%d",
1131 getDeviceName().string(), keyCode, scanCode);
1132 return;
1133 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001134 }
1135
Jeff Brown6328cdc2010-07-29 18:18:33 -07001136 int32_t oldMetaState = mLocked.metaState;
1137 newMetaState = updateMetaState(keyCode, down, oldMetaState);
1138 if (oldMetaState != newMetaState) {
1139 mLocked.metaState = newMetaState;
1140 metaStateChanged = true;
Jeff Brown497a92c2010-09-12 17:55:08 -07001141 updateLedStateLocked(false);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001142 }
Jeff Brownfd0358292010-06-30 16:10:35 -07001143
Jeff Brown6328cdc2010-07-29 18:18:33 -07001144 downTime = mLocked.downTime;
1145 } // release lock
1146
Jeff Brown56194eb2011-03-02 19:23:13 -08001147 // Key down on external an keyboard should wake the device.
1148 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
1149 // For internal keyboards, the key layout file should specify the policy flags for
1150 // each wake key individually.
1151 // TODO: Use the input device configuration to control this behavior more finely.
1152 if (down && getDevice()->isExternal()
1153 && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) {
1154 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1155 }
1156
Jeff Brown6328cdc2010-07-29 18:18:33 -07001157 if (metaStateChanged) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001158 getContext()->updateGlobalMetaState();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001159 }
1160
Jeff Brown05dc66a2011-03-02 14:41:58 -08001161 if (down && !isMetaKey(keyCode)) {
1162 getContext()->fadePointer();
1163 }
1164
Jeff Brownefd32662011-03-08 15:13:06 -08001165 getDispatcher()->notifyKey(when, getDeviceId(), mSource, policyFlags,
Jeff Brownb6997262010-10-08 22:31:17 -07001166 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
1167 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001168}
1169
Jeff Brown6328cdc2010-07-29 18:18:33 -07001170ssize_t KeyboardInputMapper::findKeyDownLocked(int32_t scanCode) {
1171 size_t n = mLocked.keyDowns.size();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001172 for (size_t i = 0; i < n; i++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001173 if (mLocked.keyDowns[i].scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001174 return i;
1175 }
1176 }
1177 return -1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001178}
1179
Jeff Brown6d0fec22010-07-23 21:28:06 -07001180int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1181 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
1182}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001183
Jeff Brown6d0fec22010-07-23 21:28:06 -07001184int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1185 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1186}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001187
Jeff Brown6d0fec22010-07-23 21:28:06 -07001188bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1189 const int32_t* keyCodes, uint8_t* outFlags) {
1190 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
1191}
1192
1193int32_t KeyboardInputMapper::getMetaState() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001194 { // acquire lock
1195 AutoMutex _l(mLock);
1196 return mLocked.metaState;
1197 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001198}
1199
Jeff Brown49ed71d2010-12-06 17:13:33 -08001200void KeyboardInputMapper::resetLedStateLocked() {
1201 initializeLedStateLocked(mLocked.capsLockLedState, LED_CAPSL);
1202 initializeLedStateLocked(mLocked.numLockLedState, LED_NUML);
1203 initializeLedStateLocked(mLocked.scrollLockLedState, LED_SCROLLL);
1204
1205 updateLedStateLocked(true);
1206}
1207
1208void KeyboardInputMapper::initializeLedStateLocked(LockedState::LedState& ledState, int32_t led) {
1209 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
1210 ledState.on = false;
1211}
1212
Jeff Brown497a92c2010-09-12 17:55:08 -07001213void KeyboardInputMapper::updateLedStateLocked(bool reset) {
1214 updateLedStateForModifierLocked(mLocked.capsLockLedState, LED_CAPSL,
Jeff Brown51e7fe752010-10-29 22:19:53 -07001215 AMETA_CAPS_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001216 updateLedStateForModifierLocked(mLocked.numLockLedState, LED_NUML,
Jeff Brown51e7fe752010-10-29 22:19:53 -07001217 AMETA_NUM_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001218 updateLedStateForModifierLocked(mLocked.scrollLockLedState, LED_SCROLLL,
Jeff Brown51e7fe752010-10-29 22:19:53 -07001219 AMETA_SCROLL_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001220}
1221
1222void KeyboardInputMapper::updateLedStateForModifierLocked(LockedState::LedState& ledState,
1223 int32_t led, int32_t modifier, bool reset) {
1224 if (ledState.avail) {
1225 bool desiredState = (mLocked.metaState & modifier) != 0;
Jeff Brown49ed71d2010-12-06 17:13:33 -08001226 if (reset || ledState.on != desiredState) {
Jeff Brown497a92c2010-09-12 17:55:08 -07001227 getEventHub()->setLedState(getDeviceId(), led, desiredState);
1228 ledState.on = desiredState;
1229 }
1230 }
1231}
1232
Jeff Brown6d0fec22010-07-23 21:28:06 -07001233
Jeff Brown83c09682010-12-23 17:50:18 -08001234// --- CursorInputMapper ---
Jeff Brown6d0fec22010-07-23 21:28:06 -07001235
Jeff Brown83c09682010-12-23 17:50:18 -08001236CursorInputMapper::CursorInputMapper(InputDevice* device) :
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001237 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001238 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001239}
1240
Jeff Brown83c09682010-12-23 17:50:18 -08001241CursorInputMapper::~CursorInputMapper() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001242}
1243
Jeff Brown83c09682010-12-23 17:50:18 -08001244uint32_t CursorInputMapper::getSources() {
Jeff Brownefd32662011-03-08 15:13:06 -08001245 return mSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001246}
1247
Jeff Brown83c09682010-12-23 17:50:18 -08001248void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001249 InputMapper::populateDeviceInfo(info);
1250
Jeff Brown83c09682010-12-23 17:50:18 -08001251 if (mParameters.mode == Parameters::MODE_POINTER) {
1252 float minX, minY, maxX, maxY;
1253 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
Jeff Brownefd32662011-03-08 15:13:06 -08001254 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f);
1255 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f);
Jeff Brown83c09682010-12-23 17:50:18 -08001256 }
1257 } else {
Jeff Brownefd32662011-03-08 15:13:06 -08001258 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale);
1259 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale);
Jeff Brown83c09682010-12-23 17:50:18 -08001260 }
Jeff Brownefd32662011-03-08 15:13:06 -08001261 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001262
1263 if (mHaveVWheel) {
Jeff Brownefd32662011-03-08 15:13:06 -08001264 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001265 }
1266 if (mHaveHWheel) {
Jeff Brownefd32662011-03-08 15:13:06 -08001267 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001268 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001269}
1270
Jeff Brown83c09682010-12-23 17:50:18 -08001271void CursorInputMapper::dump(String8& dump) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07001272 { // acquire lock
1273 AutoMutex _l(mLock);
Jeff Brown83c09682010-12-23 17:50:18 -08001274 dump.append(INDENT2 "Cursor Input Mapper:\n");
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001275 dumpParameters(dump);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001276 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
1277 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
Jeff Brownef3d7e82010-09-30 14:33:04 -07001278 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
1279 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001280 dump.appendFormat(INDENT3 "HaveVWheel: %s\n", toString(mHaveVWheel));
1281 dump.appendFormat(INDENT3 "HaveHWheel: %s\n", toString(mHaveHWheel));
1282 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
1283 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001284 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mLocked.buttonState);
1285 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mLocked.buttonState)));
Jeff Brownef3d7e82010-09-30 14:33:04 -07001286 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
1287 } // release lock
1288}
1289
Jeff Brown83c09682010-12-23 17:50:18 -08001290void CursorInputMapper::configure() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001291 InputMapper::configure();
1292
1293 // Configure basic parameters.
1294 configureParameters();
Jeff Brown83c09682010-12-23 17:50:18 -08001295
1296 // Configure device mode.
1297 switch (mParameters.mode) {
1298 case Parameters::MODE_POINTER:
Jeff Brownefd32662011-03-08 15:13:06 -08001299 mSource = AINPUT_SOURCE_MOUSE;
Jeff Brown83c09682010-12-23 17:50:18 -08001300 mXPrecision = 1.0f;
1301 mYPrecision = 1.0f;
1302 mXScale = 1.0f;
1303 mYScale = 1.0f;
1304 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
1305 break;
1306 case Parameters::MODE_NAVIGATION:
Jeff Brownefd32662011-03-08 15:13:06 -08001307 mSource = AINPUT_SOURCE_TRACKBALL;
Jeff Brown83c09682010-12-23 17:50:18 -08001308 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1309 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1310 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1311 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1312 break;
1313 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08001314
1315 mVWheelScale = 1.0f;
1316 mHWheelScale = 1.0f;
Jeff Browncc0c1592011-02-19 05:07:28 -08001317
1318 mHaveVWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_WHEEL);
1319 mHaveHWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_HWHEEL);
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001320}
1321
Jeff Brown83c09682010-12-23 17:50:18 -08001322void CursorInputMapper::configureParameters() {
1323 mParameters.mode = Parameters::MODE_POINTER;
1324 String8 cursorModeString;
1325 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
1326 if (cursorModeString == "navigation") {
1327 mParameters.mode = Parameters::MODE_NAVIGATION;
1328 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
1329 LOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
1330 }
1331 }
1332
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001333 mParameters.orientationAware = false;
Jeff Brown83c09682010-12-23 17:50:18 -08001334 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001335 mParameters.orientationAware);
1336
Jeff Brown83c09682010-12-23 17:50:18 -08001337 mParameters.associatedDisplayId = mParameters.mode == Parameters::MODE_POINTER
1338 || mParameters.orientationAware ? 0 : -1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001339}
1340
Jeff Brown83c09682010-12-23 17:50:18 -08001341void CursorInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001342 dump.append(INDENT3 "Parameters:\n");
1343 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1344 mParameters.associatedDisplayId);
Jeff Brown83c09682010-12-23 17:50:18 -08001345
1346 switch (mParameters.mode) {
1347 case Parameters::MODE_POINTER:
1348 dump.append(INDENT4 "Mode: pointer\n");
1349 break;
1350 case Parameters::MODE_NAVIGATION:
1351 dump.append(INDENT4 "Mode: navigation\n");
1352 break;
1353 default:
1354 assert(false);
1355 }
1356
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001357 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1358 toString(mParameters.orientationAware));
1359}
1360
Jeff Brown83c09682010-12-23 17:50:18 -08001361void CursorInputMapper::initializeLocked() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001362 mAccumulator.clear();
1363
Jeff Brownefd32662011-03-08 15:13:06 -08001364 mLocked.buttonState = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001365 mLocked.downTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001366}
1367
Jeff Brown83c09682010-12-23 17:50:18 -08001368void CursorInputMapper::reset() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001369 for (;;) {
Jeff Brownefd32662011-03-08 15:13:06 -08001370 uint32_t buttonState;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001371 { // acquire lock
1372 AutoMutex _l(mLock);
1373
Jeff Brownefd32662011-03-08 15:13:06 -08001374 buttonState = mLocked.buttonState;
1375 if (!buttonState) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001376 initializeLocked();
1377 break; // done
1378 }
1379 } // release lock
1380
Jeff Brown83c09682010-12-23 17:50:18 -08001381 // Synthesize button up event on reset.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001382 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brownefd32662011-03-08 15:13:06 -08001383 mAccumulator.clear();
1384 mAccumulator.buttonDown = 0;
1385 mAccumulator.buttonUp = buttonState;
1386 mAccumulator.fields = Accumulator::FIELD_BUTTONS;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001387 sync(when);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001388 }
1389
Jeff Brown6d0fec22010-07-23 21:28:06 -07001390 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001391}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001392
Jeff Brown83c09682010-12-23 17:50:18 -08001393void CursorInputMapper::process(const RawEvent* rawEvent) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001394 switch (rawEvent->type) {
Jeff Brownefd32662011-03-08 15:13:06 -08001395 case EV_KEY: {
1396 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
1397 if (buttonState) {
1398 if (rawEvent->value) {
1399 mAccumulator.buttonDown = buttonState;
1400 mAccumulator.buttonUp = 0;
1401 } else {
1402 mAccumulator.buttonDown = 0;
1403 mAccumulator.buttonUp = buttonState;
1404 }
1405 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
1406
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001407 // Sync now since BTN_MOUSE is not necessarily followed by SYN_REPORT and
1408 // we need to ensure that we report the up/down promptly.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001409 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001410 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001411 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001412 break;
Jeff Brownefd32662011-03-08 15:13:06 -08001413 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001414
Jeff Brown6d0fec22010-07-23 21:28:06 -07001415 case EV_REL:
1416 switch (rawEvent->scanCode) {
1417 case REL_X:
1418 mAccumulator.fields |= Accumulator::FIELD_REL_X;
1419 mAccumulator.relX = rawEvent->value;
1420 break;
1421 case REL_Y:
1422 mAccumulator.fields |= Accumulator::FIELD_REL_Y;
1423 mAccumulator.relY = rawEvent->value;
1424 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001425 case REL_WHEEL:
1426 mAccumulator.fields |= Accumulator::FIELD_REL_WHEEL;
1427 mAccumulator.relWheel = rawEvent->value;
1428 break;
1429 case REL_HWHEEL:
1430 mAccumulator.fields |= Accumulator::FIELD_REL_HWHEEL;
1431 mAccumulator.relHWheel = rawEvent->value;
1432 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001433 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001434 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001435
Jeff Brown6d0fec22010-07-23 21:28:06 -07001436 case EV_SYN:
1437 switch (rawEvent->scanCode) {
1438 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001439 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001440 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001441 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001442 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001443 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001444}
1445
Jeff Brown83c09682010-12-23 17:50:18 -08001446void CursorInputMapper::sync(nsecs_t when) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001447 uint32_t fields = mAccumulator.fields;
1448 if (fields == 0) {
1449 return; // no new state changes, so nothing to do
1450 }
1451
Jeff Brown9626b142011-03-03 02:09:54 -08001452 int32_t motionEventAction;
1453 int32_t motionEventEdgeFlags;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001454 PointerCoords pointerCoords;
1455 nsecs_t downTime;
Jeff Brown33bbfd22011-02-24 20:55:35 -08001456 float vscroll, hscroll;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001457 { // acquire lock
1458 AutoMutex _l(mLock);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001459
Jeff Brownefd32662011-03-08 15:13:06 -08001460 bool down, downChanged;
1461 bool wasDown = isPointerDown(mLocked.buttonState);
1462 bool buttonsChanged = fields & Accumulator::FIELD_BUTTONS;
1463 if (buttonsChanged) {
1464 mLocked.buttonState = (mLocked.buttonState | mAccumulator.buttonDown)
1465 & ~mAccumulator.buttonUp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001466
Jeff Brownefd32662011-03-08 15:13:06 -08001467 down = isPointerDown(mLocked.buttonState);
1468
1469 if (!wasDown && down) {
1470 mLocked.downTime = when;
1471 downChanged = true;
1472 } else if (wasDown && !down) {
1473 downChanged = true;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001474 } else {
Jeff Brownefd32662011-03-08 15:13:06 -08001475 downChanged = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001476 }
Jeff Brownefd32662011-03-08 15:13:06 -08001477 } else {
1478 down = wasDown;
1479 downChanged = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001480 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001481
Jeff Brown6328cdc2010-07-29 18:18:33 -07001482 downTime = mLocked.downTime;
Jeff Brown83c09682010-12-23 17:50:18 -08001483 float deltaX = fields & Accumulator::FIELD_REL_X ? mAccumulator.relX * mXScale : 0.0f;
1484 float deltaY = fields & Accumulator::FIELD_REL_Y ? mAccumulator.relY * mYScale : 0.0f;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001485
Jeff Brown6328cdc2010-07-29 18:18:33 -07001486 if (downChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08001487 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
1488 } else if (down || mPointerController == NULL) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001489 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
Jeff Browncc0c1592011-02-19 05:07:28 -08001490 } else {
1491 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001492 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001493
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001494 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0
Jeff Brown83c09682010-12-23 17:50:18 -08001495 && (deltaX != 0.0f || deltaY != 0.0f)) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001496 // Rotate motion based on display orientation if needed.
1497 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
1498 int32_t orientation;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001499 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1500 NULL, NULL, & orientation)) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001501 orientation = DISPLAY_ORIENTATION_0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001502 }
1503
1504 float temp;
1505 switch (orientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001506 case DISPLAY_ORIENTATION_90:
Jeff Brown83c09682010-12-23 17:50:18 -08001507 temp = deltaX;
1508 deltaX = deltaY;
1509 deltaY = -temp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001510 break;
1511
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001512 case DISPLAY_ORIENTATION_180:
Jeff Brown83c09682010-12-23 17:50:18 -08001513 deltaX = -deltaX;
1514 deltaY = -deltaY;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001515 break;
1516
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001517 case DISPLAY_ORIENTATION_270:
Jeff Brown83c09682010-12-23 17:50:18 -08001518 temp = deltaX;
1519 deltaX = -deltaY;
1520 deltaY = temp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001521 break;
1522 }
1523 }
Jeff Brown83c09682010-12-23 17:50:18 -08001524
Jeff Brown91c69ab2011-02-14 17:03:18 -08001525 pointerCoords.clear();
1526
Jeff Brown9626b142011-03-03 02:09:54 -08001527 motionEventEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
1528
Jeff Brown83c09682010-12-23 17:50:18 -08001529 if (mPointerController != NULL) {
1530 mPointerController->move(deltaX, deltaY);
Jeff Brownefd32662011-03-08 15:13:06 -08001531 if (buttonsChanged) {
1532 mPointerController->setButtonState(mLocked.buttonState);
Jeff Brown83c09682010-12-23 17:50:18 -08001533 }
Jeff Brownefd32662011-03-08 15:13:06 -08001534
Jeff Brown91c69ab2011-02-14 17:03:18 -08001535 float x, y;
1536 mPointerController->getPosition(&x, &y);
Jeff Brownebbd5d12011-02-17 13:01:34 -08001537 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
1538 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jeff Brown9626b142011-03-03 02:09:54 -08001539
1540 if (motionEventAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownefd32662011-03-08 15:13:06 -08001541 motionEventEdgeFlags = calculateEdgeFlagsUsingPointerBounds(
1542 mPointerController, x, y);
Jeff Brown9626b142011-03-03 02:09:54 -08001543 }
Jeff Brown83c09682010-12-23 17:50:18 -08001544 } else {
Jeff Brownebbd5d12011-02-17 13:01:34 -08001545 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
1546 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
Jeff Brown83c09682010-12-23 17:50:18 -08001547 }
1548
Jeff Brownefd32662011-03-08 15:13:06 -08001549 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001550
1551 if (mHaveVWheel && (fields & Accumulator::FIELD_REL_WHEEL)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001552 vscroll = mAccumulator.relWheel;
1553 } else {
1554 vscroll = 0;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001555 }
1556 if (mHaveHWheel && (fields & Accumulator::FIELD_REL_HWHEEL)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001557 hscroll = mAccumulator.relHWheel;
1558 } else {
1559 hscroll = 0;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001560 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001561 if (hscroll != 0 || vscroll != 0) {
1562 mPointerController->unfade();
1563 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001564 } // release lock
1565
Jeff Brown56194eb2011-03-02 19:23:13 -08001566 // Moving an external trackball or mouse should wake the device.
1567 // We don't do this for internal cursor devices to prevent them from waking up
1568 // the device in your pocket.
1569 // TODO: Use the input device configuration to control this behavior more finely.
1570 uint32_t policyFlags = 0;
1571 if (getDevice()->isExternal()) {
1572 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1573 }
1574
Jeff Brown6d0fec22010-07-23 21:28:06 -07001575 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown6328cdc2010-07-29 18:18:33 -07001576 int32_t pointerId = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08001577 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brown9626b142011-03-03 02:09:54 -08001578 motionEventAction, 0, metaState, motionEventEdgeFlags,
Jeff Brownb6997262010-10-08 22:31:17 -07001579 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1580
1581 mAccumulator.clear();
Jeff Brown33bbfd22011-02-24 20:55:35 -08001582
1583 if (vscroll != 0 || hscroll != 0) {
1584 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
1585 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
1586
Jeff Brownefd32662011-03-08 15:13:06 -08001587 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brown33bbfd22011-02-24 20:55:35 -08001588 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
1589 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1590 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001591}
1592
Jeff Brown83c09682010-12-23 17:50:18 -08001593int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brownc3fc2d02010-08-10 15:47:53 -07001594 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
1595 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1596 } else {
1597 return AKEY_STATE_UNKNOWN;
1598 }
1599}
1600
Jeff Brown05dc66a2011-03-02 14:41:58 -08001601void CursorInputMapper::fadePointer() {
1602 { // acquire lock
1603 AutoMutex _l(mLock);
Jeff Brownefd32662011-03-08 15:13:06 -08001604 if (mPointerController != NULL) {
1605 mPointerController->fade();
1606 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001607 } // release lock
1608}
1609
Jeff Brown6d0fec22010-07-23 21:28:06 -07001610
1611// --- TouchInputMapper ---
1612
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001613TouchInputMapper::TouchInputMapper(InputDevice* device) :
1614 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001615 mLocked.surfaceOrientation = -1;
1616 mLocked.surfaceWidth = -1;
1617 mLocked.surfaceHeight = -1;
1618
1619 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001620}
1621
1622TouchInputMapper::~TouchInputMapper() {
1623}
1624
1625uint32_t TouchInputMapper::getSources() {
Jeff Brownace13b12011-03-09 17:39:48 -08001626 return mTouchSource | mPointerSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001627}
1628
1629void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1630 InputMapper::populateDeviceInfo(info);
1631
Jeff Brown6328cdc2010-07-29 18:18:33 -07001632 { // acquire lock
1633 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001634
Jeff Brown6328cdc2010-07-29 18:18:33 -07001635 // Ensure surface information is up to date so that orientation changes are
1636 // noticed immediately.
Jeff Brownefd32662011-03-08 15:13:06 -08001637 if (!configureSurfaceLocked()) {
1638 return;
1639 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001640
Jeff Brownefd32662011-03-08 15:13:06 -08001641 info->addMotionRange(mLocked.orientedRanges.x);
1642 info->addMotionRange(mLocked.orientedRanges.y);
Jeff Brown8d608662010-08-30 03:02:23 -07001643
1644 if (mLocked.orientedRanges.havePressure) {
Jeff Brownefd32662011-03-08 15:13:06 -08001645 info->addMotionRange(mLocked.orientedRanges.pressure);
Jeff Brown8d608662010-08-30 03:02:23 -07001646 }
1647
1648 if (mLocked.orientedRanges.haveSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001649 info->addMotionRange(mLocked.orientedRanges.size);
Jeff Brown8d608662010-08-30 03:02:23 -07001650 }
1651
Jeff Brownc6d282b2010-10-14 21:42:15 -07001652 if (mLocked.orientedRanges.haveTouchSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001653 info->addMotionRange(mLocked.orientedRanges.touchMajor);
1654 info->addMotionRange(mLocked.orientedRanges.touchMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001655 }
1656
Jeff Brownc6d282b2010-10-14 21:42:15 -07001657 if (mLocked.orientedRanges.haveToolSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001658 info->addMotionRange(mLocked.orientedRanges.toolMajor);
1659 info->addMotionRange(mLocked.orientedRanges.toolMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001660 }
1661
1662 if (mLocked.orientedRanges.haveOrientation) {
Jeff Brownefd32662011-03-08 15:13:06 -08001663 info->addMotionRange(mLocked.orientedRanges.orientation);
Jeff Brown8d608662010-08-30 03:02:23 -07001664 }
Jeff Brownace13b12011-03-09 17:39:48 -08001665
1666 if (mPointerController != NULL) {
1667 float minX, minY, maxX, maxY;
1668 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
1669 info->addMotionRange(AMOTION_EVENT_AXIS_X, mPointerSource,
1670 minX, maxX, 0.0f, 0.0f);
1671 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mPointerSource,
1672 minY, maxY, 0.0f, 0.0f);
1673 }
1674 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mPointerSource,
1675 0.0f, 1.0f, 0.0f, 0.0f);
1676 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001677 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001678}
1679
Jeff Brownef3d7e82010-09-30 14:33:04 -07001680void TouchInputMapper::dump(String8& dump) {
1681 { // acquire lock
1682 AutoMutex _l(mLock);
1683 dump.append(INDENT2 "Touch Input Mapper:\n");
Jeff Brownef3d7e82010-09-30 14:33:04 -07001684 dumpParameters(dump);
1685 dumpVirtualKeysLocked(dump);
1686 dumpRawAxes(dump);
1687 dumpCalibration(dump);
1688 dumpSurfaceLocked(dump);
Jeff Brownefd32662011-03-08 15:13:06 -08001689
Jeff Brown511ee5f2010-10-18 13:32:20 -07001690 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
Jeff Brownc6d282b2010-10-14 21:42:15 -07001691 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mLocked.xScale);
1692 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mLocked.yScale);
1693 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mLocked.xPrecision);
1694 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mLocked.yPrecision);
1695 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mLocked.geometricScale);
1696 dump.appendFormat(INDENT4 "ToolSizeLinearScale: %0.3f\n", mLocked.toolSizeLinearScale);
1697 dump.appendFormat(INDENT4 "ToolSizeLinearBias: %0.3f\n", mLocked.toolSizeLinearBias);
1698 dump.appendFormat(INDENT4 "ToolSizeAreaScale: %0.3f\n", mLocked.toolSizeAreaScale);
1699 dump.appendFormat(INDENT4 "ToolSizeAreaBias: %0.3f\n", mLocked.toolSizeAreaBias);
1700 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mLocked.pressureScale);
1701 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mLocked.sizeScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001702 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mLocked.orientationScale);
1703
1704 dump.appendFormat(INDENT3 "Last Touch:\n");
1705 dump.appendFormat(INDENT4 "Pointer Count: %d\n", mLastTouch.pointerCount);
Jeff Brownace13b12011-03-09 17:39:48 -08001706 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", mLastTouch.buttonState);
1707
1708 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
1709 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
1710 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
1711 mLocked.pointerGestureXMovementScale);
1712 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
1713 mLocked.pointerGestureYMovementScale);
1714 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
1715 mLocked.pointerGestureXZoomScale);
1716 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
1717 mLocked.pointerGestureYZoomScale);
1718 dump.appendFormat(INDENT4 "MaxSwipeWidthSquared: %d\n",
1719 mLocked.pointerGestureMaxSwipeWidthSquared);
1720 }
Jeff Brownef3d7e82010-09-30 14:33:04 -07001721 } // release lock
1722}
1723
Jeff Brown6328cdc2010-07-29 18:18:33 -07001724void TouchInputMapper::initializeLocked() {
1725 mCurrentTouch.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001726 mLastTouch.clear();
1727 mDownTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001728
1729 for (uint32_t i = 0; i < MAX_POINTERS; i++) {
1730 mAveragingTouchFilter.historyStart[i] = 0;
1731 mAveragingTouchFilter.historyEnd[i] = 0;
1732 }
1733
1734 mJumpyTouchFilter.jumpyPointsDropped = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001735
1736 mLocked.currentVirtualKey.down = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001737
1738 mLocked.orientedRanges.havePressure = false;
1739 mLocked.orientedRanges.haveSize = false;
Jeff Brownc6d282b2010-10-14 21:42:15 -07001740 mLocked.orientedRanges.haveTouchSize = false;
1741 mLocked.orientedRanges.haveToolSize = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001742 mLocked.orientedRanges.haveOrientation = false;
Jeff Brownace13b12011-03-09 17:39:48 -08001743
1744 mPointerGesture.reset();
Jeff Brown8d608662010-08-30 03:02:23 -07001745}
1746
Jeff Brown6d0fec22010-07-23 21:28:06 -07001747void TouchInputMapper::configure() {
1748 InputMapper::configure();
1749
1750 // Configure basic parameters.
Jeff Brown8d608662010-08-30 03:02:23 -07001751 configureParameters();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001752
Jeff Brown83c09682010-12-23 17:50:18 -08001753 // Configure sources.
1754 switch (mParameters.deviceType) {
1755 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Jeff Brownefd32662011-03-08 15:13:06 -08001756 mTouchSource = AINPUT_SOURCE_TOUCHSCREEN;
Jeff Brownace13b12011-03-09 17:39:48 -08001757 mPointerSource = 0;
Jeff Brown83c09682010-12-23 17:50:18 -08001758 break;
1759 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Jeff Brownefd32662011-03-08 15:13:06 -08001760 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
Jeff Brownace13b12011-03-09 17:39:48 -08001761 mPointerSource = 0;
1762 break;
1763 case Parameters::DEVICE_TYPE_POINTER:
1764 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
1765 mPointerSource = AINPUT_SOURCE_MOUSE;
Jeff Brown83c09682010-12-23 17:50:18 -08001766 break;
1767 default:
1768 assert(false);
1769 }
1770
Jeff Brown6d0fec22010-07-23 21:28:06 -07001771 // Configure absolute axis information.
Jeff Brown8d608662010-08-30 03:02:23 -07001772 configureRawAxes();
Jeff Brown8d608662010-08-30 03:02:23 -07001773
1774 // Prepare input device calibration.
1775 parseCalibration();
1776 resolveCalibration();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001777
Jeff Brown6328cdc2010-07-29 18:18:33 -07001778 { // acquire lock
1779 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001780
Jeff Brown8d608662010-08-30 03:02:23 -07001781 // Configure surface dimensions and orientation.
Jeff Brown6328cdc2010-07-29 18:18:33 -07001782 configureSurfaceLocked();
1783 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001784}
1785
Jeff Brown8d608662010-08-30 03:02:23 -07001786void TouchInputMapper::configureParameters() {
1787 mParameters.useBadTouchFilter = getPolicy()->filterTouchEvents();
1788 mParameters.useAveragingTouchFilter = getPolicy()->filterTouchEvents();
1789 mParameters.useJumpyTouchFilter = getPolicy()->filterJumpyTouchEvents();
Jeff Brownfe508922011-01-18 15:10:10 -08001790 mParameters.virtualKeyQuietTime = getPolicy()->getVirtualKeyQuietTime();
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001791
Jeff Brownace13b12011-03-09 17:39:48 -08001792 if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
1793 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
1794 // The device is a cursor device with a touch pad attached.
1795 // By default don't use the touch pad to move the pointer.
1796 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
1797 } else {
1798 // The device is just a touch pad.
1799 // By default use the touch pad to move the pointer and to perform related gestures.
1800 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
1801 }
1802
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001803 String8 deviceTypeString;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001804 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
1805 deviceTypeString)) {
Jeff Brown58a2da82011-01-25 16:02:22 -08001806 if (deviceTypeString == "touchScreen") {
1807 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brownefd32662011-03-08 15:13:06 -08001808 } else if (deviceTypeString == "touchPad") {
1809 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
Jeff Brownace13b12011-03-09 17:39:48 -08001810 } else if (deviceTypeString == "pointer") {
1811 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
Jeff Brownefd32662011-03-08 15:13:06 -08001812 } else {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001813 LOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
1814 }
1815 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001816
Jeff Brownefd32662011-03-08 15:13:06 -08001817 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001818 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
1819 mParameters.orientationAware);
1820
Jeff Brownefd32662011-03-08 15:13:06 -08001821 mParameters.associatedDisplayId = mParameters.orientationAware
1822 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
Jeff Brownace13b12011-03-09 17:39:48 -08001823 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
Jeff Brownefd32662011-03-08 15:13:06 -08001824 ? 0 : -1;
Jeff Brown8d608662010-08-30 03:02:23 -07001825}
1826
Jeff Brownef3d7e82010-09-30 14:33:04 -07001827void TouchInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001828 dump.append(INDENT3 "Parameters:\n");
1829
1830 switch (mParameters.deviceType) {
1831 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
1832 dump.append(INDENT4 "DeviceType: touchScreen\n");
1833 break;
1834 case Parameters::DEVICE_TYPE_TOUCH_PAD:
1835 dump.append(INDENT4 "DeviceType: touchPad\n");
1836 break;
Jeff Brownace13b12011-03-09 17:39:48 -08001837 case Parameters::DEVICE_TYPE_POINTER:
1838 dump.append(INDENT4 "DeviceType: pointer\n");
1839 break;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001840 default:
1841 assert(false);
1842 }
1843
1844 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1845 mParameters.associatedDisplayId);
1846 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1847 toString(mParameters.orientationAware));
1848
1849 dump.appendFormat(INDENT4 "UseBadTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001850 toString(mParameters.useBadTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001851 dump.appendFormat(INDENT4 "UseAveragingTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001852 toString(mParameters.useAveragingTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001853 dump.appendFormat(INDENT4 "UseJumpyTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001854 toString(mParameters.useJumpyTouchFilter));
Jeff Brownb88102f2010-09-08 11:49:43 -07001855}
1856
Jeff Brown8d608662010-08-30 03:02:23 -07001857void TouchInputMapper::configureRawAxes() {
1858 mRawAxes.x.clear();
1859 mRawAxes.y.clear();
1860 mRawAxes.pressure.clear();
1861 mRawAxes.touchMajor.clear();
1862 mRawAxes.touchMinor.clear();
1863 mRawAxes.toolMajor.clear();
1864 mRawAxes.toolMinor.clear();
1865 mRawAxes.orientation.clear();
1866}
1867
Jeff Brownef3d7e82010-09-30 14:33:04 -07001868void TouchInputMapper::dumpRawAxes(String8& dump) {
1869 dump.append(INDENT3 "Raw Axes:\n");
Jeff Browncb1404e2011-01-15 18:14:15 -08001870 dumpRawAbsoluteAxisInfo(dump, mRawAxes.x, "X");
1871 dumpRawAbsoluteAxisInfo(dump, mRawAxes.y, "Y");
1872 dumpRawAbsoluteAxisInfo(dump, mRawAxes.pressure, "Pressure");
1873 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMajor, "TouchMajor");
1874 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMinor, "TouchMinor");
1875 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMajor, "ToolMajor");
1876 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMinor, "ToolMinor");
1877 dumpRawAbsoluteAxisInfo(dump, mRawAxes.orientation, "Orientation");
Jeff Brown6d0fec22010-07-23 21:28:06 -07001878}
1879
Jeff Brown6328cdc2010-07-29 18:18:33 -07001880bool TouchInputMapper::configureSurfaceLocked() {
Jeff Brown9626b142011-03-03 02:09:54 -08001881 // Ensure we have valid X and Y axes.
1882 if (!mRawAxes.x.valid || !mRawAxes.y.valid) {
1883 LOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
1884 "The device will be inoperable.", getDeviceName().string());
1885 return false;
1886 }
1887
Jeff Brown6d0fec22010-07-23 21:28:06 -07001888 // Update orientation and dimensions if needed.
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001889 int32_t orientation = DISPLAY_ORIENTATION_0;
Jeff Brown9626b142011-03-03 02:09:54 -08001890 int32_t width = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
1891 int32_t height = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001892
1893 if (mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001894 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001895 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
Jeff Brownefd32662011-03-08 15:13:06 -08001896 &mLocked.associatedDisplayWidth, &mLocked.associatedDisplayHeight,
1897 &mLocked.associatedDisplayOrientation)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001898 return false;
1899 }
Jeff Brownefd32662011-03-08 15:13:06 -08001900
1901 // A touch screen inherits the dimensions of the display.
1902 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
1903 width = mLocked.associatedDisplayWidth;
1904 height = mLocked.associatedDisplayHeight;
1905 }
1906
1907 // The device inherits the orientation of the display if it is orientation aware.
1908 if (mParameters.orientationAware) {
1909 orientation = mLocked.associatedDisplayOrientation;
1910 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001911 }
1912
Jeff Brownace13b12011-03-09 17:39:48 -08001913 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
1914 && mPointerController == NULL) {
1915 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
1916 }
1917
Jeff Brown6328cdc2010-07-29 18:18:33 -07001918 bool orientationChanged = mLocked.surfaceOrientation != orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001919 if (orientationChanged) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001920 mLocked.surfaceOrientation = orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001921 }
1922
Jeff Brown6328cdc2010-07-29 18:18:33 -07001923 bool sizeChanged = mLocked.surfaceWidth != width || mLocked.surfaceHeight != height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001924 if (sizeChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08001925 LOGI("Device reconfigured: id=%d, name='%s', surface size is now %dx%d",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001926 getDeviceId(), getDeviceName().string(), width, height);
Jeff Brown8d608662010-08-30 03:02:23 -07001927
Jeff Brown6328cdc2010-07-29 18:18:33 -07001928 mLocked.surfaceWidth = width;
1929 mLocked.surfaceHeight = height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001930
Jeff Brown8d608662010-08-30 03:02:23 -07001931 // Configure X and Y factors.
Jeff Brown9626b142011-03-03 02:09:54 -08001932 mLocked.xScale = float(width) / (mRawAxes.x.maxValue - mRawAxes.x.minValue + 1);
1933 mLocked.yScale = float(height) / (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1);
1934 mLocked.xPrecision = 1.0f / mLocked.xScale;
1935 mLocked.yPrecision = 1.0f / mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001936
Jeff Brownefd32662011-03-08 15:13:06 -08001937 mLocked.orientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
1938 mLocked.orientedRanges.x.source = mTouchSource;
1939 mLocked.orientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
1940 mLocked.orientedRanges.y.source = mTouchSource;
1941
Jeff Brown9626b142011-03-03 02:09:54 -08001942 configureVirtualKeysLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001943
Jeff Brown8d608662010-08-30 03:02:23 -07001944 // Scale factor for terms that are not oriented in a particular axis.
1945 // If the pixels are square then xScale == yScale otherwise we fake it
1946 // by choosing an average.
1947 mLocked.geometricScale = avg(mLocked.xScale, mLocked.yScale);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001948
Jeff Brown8d608662010-08-30 03:02:23 -07001949 // Size of diagonal axis.
1950 float diagonalSize = pythag(width, height);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001951
Jeff Brown8d608662010-08-30 03:02:23 -07001952 // TouchMajor and TouchMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07001953 if (mCalibration.touchSizeCalibration != Calibration::TOUCH_SIZE_CALIBRATION_NONE) {
1954 mLocked.orientedRanges.haveTouchSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08001955
1956 mLocked.orientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
1957 mLocked.orientedRanges.touchMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07001958 mLocked.orientedRanges.touchMajor.min = 0;
1959 mLocked.orientedRanges.touchMajor.max = diagonalSize;
1960 mLocked.orientedRanges.touchMajor.flat = 0;
1961 mLocked.orientedRanges.touchMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08001962
Jeff Brown8d608662010-08-30 03:02:23 -07001963 mLocked.orientedRanges.touchMinor = mLocked.orientedRanges.touchMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08001964 mLocked.orientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07001965 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001966
Jeff Brown8d608662010-08-30 03:02:23 -07001967 // ToolMajor and ToolMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07001968 mLocked.toolSizeLinearScale = 0;
1969 mLocked.toolSizeLinearBias = 0;
1970 mLocked.toolSizeAreaScale = 0;
1971 mLocked.toolSizeAreaBias = 0;
1972 if (mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
1973 if (mCalibration.toolSizeCalibration == Calibration::TOOL_SIZE_CALIBRATION_LINEAR) {
1974 if (mCalibration.haveToolSizeLinearScale) {
1975 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
Jeff Brown8d608662010-08-30 03:02:23 -07001976 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07001977 mLocked.toolSizeLinearScale = float(min(width, height))
Jeff Brown8d608662010-08-30 03:02:23 -07001978 / mRawAxes.toolMajor.maxValue;
1979 }
1980
Jeff Brownc6d282b2010-10-14 21:42:15 -07001981 if (mCalibration.haveToolSizeLinearBias) {
1982 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
1983 }
1984 } else if (mCalibration.toolSizeCalibration ==
1985 Calibration::TOOL_SIZE_CALIBRATION_AREA) {
1986 if (mCalibration.haveToolSizeLinearScale) {
1987 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
1988 } else {
1989 mLocked.toolSizeLinearScale = min(width, height);
1990 }
1991
1992 if (mCalibration.haveToolSizeLinearBias) {
1993 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
1994 }
1995
1996 if (mCalibration.haveToolSizeAreaScale) {
1997 mLocked.toolSizeAreaScale = mCalibration.toolSizeAreaScale;
1998 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
1999 mLocked.toolSizeAreaScale = 1.0f / mRawAxes.toolMajor.maxValue;
2000 }
2001
2002 if (mCalibration.haveToolSizeAreaBias) {
2003 mLocked.toolSizeAreaBias = mCalibration.toolSizeAreaBias;
Jeff Brown8d608662010-08-30 03:02:23 -07002004 }
2005 }
2006
Jeff Brownc6d282b2010-10-14 21:42:15 -07002007 mLocked.orientedRanges.haveToolSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002008
2009 mLocked.orientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
2010 mLocked.orientedRanges.toolMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002011 mLocked.orientedRanges.toolMajor.min = 0;
2012 mLocked.orientedRanges.toolMajor.max = diagonalSize;
2013 mLocked.orientedRanges.toolMajor.flat = 0;
2014 mLocked.orientedRanges.toolMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08002015
Jeff Brown8d608662010-08-30 03:02:23 -07002016 mLocked.orientedRanges.toolMinor = mLocked.orientedRanges.toolMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08002017 mLocked.orientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002018 }
2019
2020 // Pressure factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002021 mLocked.pressureScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002022 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE) {
2023 RawAbsoluteAxisInfo rawPressureAxis;
2024 switch (mCalibration.pressureSource) {
2025 case Calibration::PRESSURE_SOURCE_PRESSURE:
2026 rawPressureAxis = mRawAxes.pressure;
2027 break;
2028 case Calibration::PRESSURE_SOURCE_TOUCH:
2029 rawPressureAxis = mRawAxes.touchMajor;
2030 break;
2031 default:
2032 rawPressureAxis.clear();
2033 }
2034
Jeff Brown8d608662010-08-30 03:02:23 -07002035 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
2036 || mCalibration.pressureCalibration
2037 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
2038 if (mCalibration.havePressureScale) {
2039 mLocked.pressureScale = mCalibration.pressureScale;
2040 } else if (rawPressureAxis.valid && rawPressureAxis.maxValue != 0) {
2041 mLocked.pressureScale = 1.0f / rawPressureAxis.maxValue;
2042 }
2043 }
2044
2045 mLocked.orientedRanges.havePressure = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002046
2047 mLocked.orientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
2048 mLocked.orientedRanges.pressure.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002049 mLocked.orientedRanges.pressure.min = 0;
2050 mLocked.orientedRanges.pressure.max = 1.0;
2051 mLocked.orientedRanges.pressure.flat = 0;
2052 mLocked.orientedRanges.pressure.fuzz = 0;
2053 }
2054
2055 // Size factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002056 mLocked.sizeScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002057 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002058 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_NORMALIZED) {
2059 if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2060 mLocked.sizeScale = 1.0f / mRawAxes.toolMajor.maxValue;
2061 }
2062 }
2063
2064 mLocked.orientedRanges.haveSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002065
2066 mLocked.orientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
2067 mLocked.orientedRanges.size.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002068 mLocked.orientedRanges.size.min = 0;
2069 mLocked.orientedRanges.size.max = 1.0;
2070 mLocked.orientedRanges.size.flat = 0;
2071 mLocked.orientedRanges.size.fuzz = 0;
2072 }
2073
2074 // Orientation
Jeff Brownc6d282b2010-10-14 21:42:15 -07002075 mLocked.orientationScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002076 if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002077 if (mCalibration.orientationCalibration
2078 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
2079 if (mRawAxes.orientation.valid && mRawAxes.orientation.maxValue != 0) {
2080 mLocked.orientationScale = float(M_PI_2) / mRawAxes.orientation.maxValue;
2081 }
2082 }
2083
Jeff Brownefd32662011-03-08 15:13:06 -08002084 mLocked.orientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
2085 mLocked.orientedRanges.orientation.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002086 mLocked.orientedRanges.orientation.min = - M_PI_2;
2087 mLocked.orientedRanges.orientation.max = M_PI_2;
2088 mLocked.orientedRanges.orientation.flat = 0;
2089 mLocked.orientedRanges.orientation.fuzz = 0;
2090 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002091 }
2092
2093 if (orientationChanged || sizeChanged) {
Jeff Brown9626b142011-03-03 02:09:54 -08002094 // Compute oriented surface dimensions, precision, scales and ranges.
2095 // Note that the maximum value reported is an inclusive maximum value so it is one
2096 // unit less than the total width or height of surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002097 switch (mLocked.surfaceOrientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08002098 case DISPLAY_ORIENTATION_90:
2099 case DISPLAY_ORIENTATION_270:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002100 mLocked.orientedSurfaceWidth = mLocked.surfaceHeight;
2101 mLocked.orientedSurfaceHeight = mLocked.surfaceWidth;
Jeff Brown9626b142011-03-03 02:09:54 -08002102
Jeff Brown6328cdc2010-07-29 18:18:33 -07002103 mLocked.orientedXPrecision = mLocked.yPrecision;
2104 mLocked.orientedYPrecision = mLocked.xPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002105
2106 mLocked.orientedRanges.x.min = 0;
2107 mLocked.orientedRanges.x.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2108 * mLocked.yScale;
2109 mLocked.orientedRanges.x.flat = 0;
2110 mLocked.orientedRanges.x.fuzz = mLocked.yScale;
2111
2112 mLocked.orientedRanges.y.min = 0;
2113 mLocked.orientedRanges.y.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2114 * mLocked.xScale;
2115 mLocked.orientedRanges.y.flat = 0;
2116 mLocked.orientedRanges.y.fuzz = mLocked.xScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002117 break;
Jeff Brown9626b142011-03-03 02:09:54 -08002118
Jeff Brown6d0fec22010-07-23 21:28:06 -07002119 default:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002120 mLocked.orientedSurfaceWidth = mLocked.surfaceWidth;
2121 mLocked.orientedSurfaceHeight = mLocked.surfaceHeight;
Jeff Brown9626b142011-03-03 02:09:54 -08002122
Jeff Brown6328cdc2010-07-29 18:18:33 -07002123 mLocked.orientedXPrecision = mLocked.xPrecision;
2124 mLocked.orientedYPrecision = mLocked.yPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002125
2126 mLocked.orientedRanges.x.min = 0;
2127 mLocked.orientedRanges.x.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2128 * mLocked.xScale;
2129 mLocked.orientedRanges.x.flat = 0;
2130 mLocked.orientedRanges.x.fuzz = mLocked.xScale;
2131
2132 mLocked.orientedRanges.y.min = 0;
2133 mLocked.orientedRanges.y.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2134 * mLocked.yScale;
2135 mLocked.orientedRanges.y.flat = 0;
2136 mLocked.orientedRanges.y.fuzz = mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002137 break;
2138 }
Jeff Brownace13b12011-03-09 17:39:48 -08002139
2140 // Compute pointer gesture detection parameters.
2141 // TODO: These factors should not be hardcoded.
2142 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
2143 int32_t rawWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2144 int32_t rawHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
2145
2146 // Scale movements such that one whole swipe of the touch pad covers a portion
2147 // of the display along whichever axis of the touch pad is longer.
2148 // Assume that the touch pad has a square aspect ratio such that movements in
2149 // X and Y of the same number of raw units cover the same physical distance.
2150 const float scaleFactor = 0.8f;
2151
2152 mLocked.pointerGestureXMovementScale = rawWidth > rawHeight
2153 ? scaleFactor * float(mLocked.associatedDisplayWidth) / rawWidth
2154 : scaleFactor * float(mLocked.associatedDisplayHeight) / rawHeight;
2155 mLocked.pointerGestureYMovementScale = mLocked.pointerGestureXMovementScale;
2156
2157 // Scale zooms to cover a smaller range of the display than movements do.
2158 // This value determines the area around the pointer that is affected by freeform
2159 // pointer gestures.
2160 mLocked.pointerGestureXZoomScale = mLocked.pointerGestureXMovementScale * 0.4f;
2161 mLocked.pointerGestureYZoomScale = mLocked.pointerGestureYMovementScale * 0.4f;
2162
2163 // Max width between pointers to detect a swipe gesture is 3/4 of the short
2164 // axis of the touch pad. Touches that are wider than this are translated
2165 // into freeform gestures.
2166 mLocked.pointerGestureMaxSwipeWidthSquared = min(rawWidth, rawHeight) * 3 / 4;
2167 mLocked.pointerGestureMaxSwipeWidthSquared *=
2168 mLocked.pointerGestureMaxSwipeWidthSquared;
2169 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002170 }
2171
2172 return true;
2173}
2174
Jeff Brownef3d7e82010-09-30 14:33:04 -07002175void TouchInputMapper::dumpSurfaceLocked(String8& dump) {
2176 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mLocked.surfaceWidth);
2177 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mLocked.surfaceHeight);
2178 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mLocked.surfaceOrientation);
Jeff Brownb88102f2010-09-08 11:49:43 -07002179}
2180
Jeff Brown6328cdc2010-07-29 18:18:33 -07002181void TouchInputMapper::configureVirtualKeysLocked() {
Jeff Brown8d608662010-08-30 03:02:23 -07002182 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
Jeff Brown90655042010-12-02 13:50:46 -08002183 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002184
Jeff Brown6328cdc2010-07-29 18:18:33 -07002185 mLocked.virtualKeys.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002186
Jeff Brown6328cdc2010-07-29 18:18:33 -07002187 if (virtualKeyDefinitions.size() == 0) {
2188 return;
2189 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002190
Jeff Brown6328cdc2010-07-29 18:18:33 -07002191 mLocked.virtualKeys.setCapacity(virtualKeyDefinitions.size());
2192
Jeff Brown8d608662010-08-30 03:02:23 -07002193 int32_t touchScreenLeft = mRawAxes.x.minValue;
2194 int32_t touchScreenTop = mRawAxes.y.minValue;
Jeff Brown9626b142011-03-03 02:09:54 -08002195 int32_t touchScreenWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2196 int32_t touchScreenHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002197
2198 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002199 const VirtualKeyDefinition& virtualKeyDefinition =
Jeff Brown6328cdc2010-07-29 18:18:33 -07002200 virtualKeyDefinitions[i];
2201
2202 mLocked.virtualKeys.add();
2203 VirtualKey& virtualKey = mLocked.virtualKeys.editTop();
2204
2205 virtualKey.scanCode = virtualKeyDefinition.scanCode;
2206 int32_t keyCode;
2207 uint32_t flags;
Jeff Brown6f2fba42011-02-19 01:08:02 -08002208 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode,
Jeff Brown6328cdc2010-07-29 18:18:33 -07002209 & keyCode, & flags)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002210 LOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
2211 virtualKey.scanCode);
Jeff Brown6328cdc2010-07-29 18:18:33 -07002212 mLocked.virtualKeys.pop(); // drop the key
2213 continue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002214 }
2215
Jeff Brown6328cdc2010-07-29 18:18:33 -07002216 virtualKey.keyCode = keyCode;
2217 virtualKey.flags = flags;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002218
Jeff Brown6328cdc2010-07-29 18:18:33 -07002219 // convert the key definition's display coordinates into touch coordinates for a hit box
2220 int32_t halfWidth = virtualKeyDefinition.width / 2;
2221 int32_t halfHeight = virtualKeyDefinition.height / 2;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002222
Jeff Brown6328cdc2010-07-29 18:18:33 -07002223 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
2224 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2225 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
2226 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2227 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
2228 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
2229 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
2230 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
Jeff Brownef3d7e82010-09-30 14:33:04 -07002231 }
2232}
2233
2234void TouchInputMapper::dumpVirtualKeysLocked(String8& dump) {
2235 if (!mLocked.virtualKeys.isEmpty()) {
2236 dump.append(INDENT3 "Virtual Keys:\n");
2237
2238 for (size_t i = 0; i < mLocked.virtualKeys.size(); i++) {
2239 const VirtualKey& virtualKey = mLocked.virtualKeys.itemAt(i);
2240 dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, "
2241 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
2242 i, virtualKey.scanCode, virtualKey.keyCode,
2243 virtualKey.hitLeft, virtualKey.hitRight,
2244 virtualKey.hitTop, virtualKey.hitBottom);
2245 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002246 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002247}
2248
Jeff Brown8d608662010-08-30 03:02:23 -07002249void TouchInputMapper::parseCalibration() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002250 const PropertyMap& in = getDevice()->getConfiguration();
Jeff Brown8d608662010-08-30 03:02:23 -07002251 Calibration& out = mCalibration;
2252
Jeff Brownc6d282b2010-10-14 21:42:15 -07002253 // Touch Size
2254 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT;
2255 String8 touchSizeCalibrationString;
2256 if (in.tryGetProperty(String8("touch.touchSize.calibration"), touchSizeCalibrationString)) {
2257 if (touchSizeCalibrationString == "none") {
2258 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
2259 } else if (touchSizeCalibrationString == "geometric") {
2260 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC;
2261 } else if (touchSizeCalibrationString == "pressure") {
2262 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
2263 } else if (touchSizeCalibrationString != "default") {
2264 LOGW("Invalid value for touch.touchSize.calibration: '%s'",
2265 touchSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002266 }
2267 }
2268
Jeff Brownc6d282b2010-10-14 21:42:15 -07002269 // Tool Size
2270 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_DEFAULT;
2271 String8 toolSizeCalibrationString;
2272 if (in.tryGetProperty(String8("touch.toolSize.calibration"), toolSizeCalibrationString)) {
2273 if (toolSizeCalibrationString == "none") {
2274 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
2275 } else if (toolSizeCalibrationString == "geometric") {
2276 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC;
2277 } else if (toolSizeCalibrationString == "linear") {
2278 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
2279 } else if (toolSizeCalibrationString == "area") {
2280 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_AREA;
2281 } else if (toolSizeCalibrationString != "default") {
2282 LOGW("Invalid value for touch.toolSize.calibration: '%s'",
2283 toolSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002284 }
2285 }
2286
Jeff Brownc6d282b2010-10-14 21:42:15 -07002287 out.haveToolSizeLinearScale = in.tryGetProperty(String8("touch.toolSize.linearScale"),
2288 out.toolSizeLinearScale);
2289 out.haveToolSizeLinearBias = in.tryGetProperty(String8("touch.toolSize.linearBias"),
2290 out.toolSizeLinearBias);
2291 out.haveToolSizeAreaScale = in.tryGetProperty(String8("touch.toolSize.areaScale"),
2292 out.toolSizeAreaScale);
2293 out.haveToolSizeAreaBias = in.tryGetProperty(String8("touch.toolSize.areaBias"),
2294 out.toolSizeAreaBias);
2295 out.haveToolSizeIsSummed = in.tryGetProperty(String8("touch.toolSize.isSummed"),
2296 out.toolSizeIsSummed);
Jeff Brown8d608662010-08-30 03:02:23 -07002297
2298 // Pressure
2299 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
2300 String8 pressureCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002301 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002302 if (pressureCalibrationString == "none") {
2303 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2304 } else if (pressureCalibrationString == "physical") {
2305 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
2306 } else if (pressureCalibrationString == "amplitude") {
2307 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2308 } else if (pressureCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002309 LOGW("Invalid value for touch.pressure.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002310 pressureCalibrationString.string());
2311 }
2312 }
2313
2314 out.pressureSource = Calibration::PRESSURE_SOURCE_DEFAULT;
2315 String8 pressureSourceString;
2316 if (in.tryGetProperty(String8("touch.pressure.source"), pressureSourceString)) {
2317 if (pressureSourceString == "pressure") {
2318 out.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2319 } else if (pressureSourceString == "touch") {
2320 out.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2321 } else if (pressureSourceString != "default") {
2322 LOGW("Invalid value for touch.pressure.source: '%s'",
2323 pressureSourceString.string());
2324 }
2325 }
2326
2327 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
2328 out.pressureScale);
2329
2330 // Size
2331 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
2332 String8 sizeCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002333 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002334 if (sizeCalibrationString == "none") {
2335 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2336 } else if (sizeCalibrationString == "normalized") {
2337 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2338 } else if (sizeCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002339 LOGW("Invalid value for touch.size.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002340 sizeCalibrationString.string());
2341 }
2342 }
2343
2344 // Orientation
2345 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
2346 String8 orientationCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002347 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002348 if (orientationCalibrationString == "none") {
2349 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2350 } else if (orientationCalibrationString == "interpolated") {
2351 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002352 } else if (orientationCalibrationString == "vector") {
2353 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002354 } else if (orientationCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002355 LOGW("Invalid value for touch.orientation.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002356 orientationCalibrationString.string());
2357 }
2358 }
2359}
2360
2361void TouchInputMapper::resolveCalibration() {
2362 // Pressure
2363 switch (mCalibration.pressureSource) {
2364 case Calibration::PRESSURE_SOURCE_DEFAULT:
2365 if (mRawAxes.pressure.valid) {
2366 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2367 } else if (mRawAxes.touchMajor.valid) {
2368 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2369 }
2370 break;
2371
2372 case Calibration::PRESSURE_SOURCE_PRESSURE:
2373 if (! mRawAxes.pressure.valid) {
2374 LOGW("Calibration property touch.pressure.source is 'pressure' but "
2375 "the pressure axis is not available.");
2376 }
2377 break;
2378
2379 case Calibration::PRESSURE_SOURCE_TOUCH:
2380 if (! mRawAxes.touchMajor.valid) {
2381 LOGW("Calibration property touch.pressure.source is 'touch' but "
2382 "the touchMajor axis is not available.");
2383 }
2384 break;
2385
2386 default:
2387 break;
2388 }
2389
2390 switch (mCalibration.pressureCalibration) {
2391 case Calibration::PRESSURE_CALIBRATION_DEFAULT:
2392 if (mCalibration.pressureSource != Calibration::PRESSURE_SOURCE_DEFAULT) {
2393 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2394 } else {
2395 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2396 }
2397 break;
2398
2399 default:
2400 break;
2401 }
2402
Jeff Brownc6d282b2010-10-14 21:42:15 -07002403 // Tool Size
2404 switch (mCalibration.toolSizeCalibration) {
2405 case Calibration::TOOL_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002406 if (mRawAxes.toolMajor.valid) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002407 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
Jeff Brown8d608662010-08-30 03:02:23 -07002408 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002409 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002410 }
2411 break;
2412
2413 default:
2414 break;
2415 }
2416
Jeff Brownc6d282b2010-10-14 21:42:15 -07002417 // Touch Size
2418 switch (mCalibration.touchSizeCalibration) {
2419 case Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002420 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE
Jeff Brownc6d282b2010-10-14 21:42:15 -07002421 && mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2422 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
Jeff Brown8d608662010-08-30 03:02:23 -07002423 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002424 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002425 }
2426 break;
2427
2428 default:
2429 break;
2430 }
2431
2432 // Size
2433 switch (mCalibration.sizeCalibration) {
2434 case Calibration::SIZE_CALIBRATION_DEFAULT:
2435 if (mRawAxes.toolMajor.valid) {
2436 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2437 } else {
2438 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2439 }
2440 break;
2441
2442 default:
2443 break;
2444 }
2445
2446 // Orientation
2447 switch (mCalibration.orientationCalibration) {
2448 case Calibration::ORIENTATION_CALIBRATION_DEFAULT:
2449 if (mRawAxes.orientation.valid) {
2450 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
2451 } else {
2452 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2453 }
2454 break;
2455
2456 default:
2457 break;
2458 }
2459}
2460
Jeff Brownef3d7e82010-09-30 14:33:04 -07002461void TouchInputMapper::dumpCalibration(String8& dump) {
2462 dump.append(INDENT3 "Calibration:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002463
Jeff Brownc6d282b2010-10-14 21:42:15 -07002464 // Touch Size
2465 switch (mCalibration.touchSizeCalibration) {
2466 case Calibration::TOUCH_SIZE_CALIBRATION_NONE:
2467 dump.append(INDENT4 "touch.touchSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002468 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002469 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
2470 dump.append(INDENT4 "touch.touchSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002471 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002472 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
2473 dump.append(INDENT4 "touch.touchSize.calibration: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002474 break;
2475 default:
2476 assert(false);
2477 }
2478
Jeff Brownc6d282b2010-10-14 21:42:15 -07002479 // Tool Size
2480 switch (mCalibration.toolSizeCalibration) {
2481 case Calibration::TOOL_SIZE_CALIBRATION_NONE:
2482 dump.append(INDENT4 "touch.toolSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002483 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002484 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
2485 dump.append(INDENT4 "touch.toolSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002486 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002487 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
2488 dump.append(INDENT4 "touch.toolSize.calibration: linear\n");
2489 break;
2490 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
2491 dump.append(INDENT4 "touch.toolSize.calibration: area\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002492 break;
2493 default:
2494 assert(false);
2495 }
2496
Jeff Brownc6d282b2010-10-14 21:42:15 -07002497 if (mCalibration.haveToolSizeLinearScale) {
2498 dump.appendFormat(INDENT4 "touch.toolSize.linearScale: %0.3f\n",
2499 mCalibration.toolSizeLinearScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002500 }
2501
Jeff Brownc6d282b2010-10-14 21:42:15 -07002502 if (mCalibration.haveToolSizeLinearBias) {
2503 dump.appendFormat(INDENT4 "touch.toolSize.linearBias: %0.3f\n",
2504 mCalibration.toolSizeLinearBias);
Jeff Brown8d608662010-08-30 03:02:23 -07002505 }
2506
Jeff Brownc6d282b2010-10-14 21:42:15 -07002507 if (mCalibration.haveToolSizeAreaScale) {
2508 dump.appendFormat(INDENT4 "touch.toolSize.areaScale: %0.3f\n",
2509 mCalibration.toolSizeAreaScale);
2510 }
2511
2512 if (mCalibration.haveToolSizeAreaBias) {
2513 dump.appendFormat(INDENT4 "touch.toolSize.areaBias: %0.3f\n",
2514 mCalibration.toolSizeAreaBias);
2515 }
2516
2517 if (mCalibration.haveToolSizeIsSummed) {
Jeff Brown1f245102010-11-18 20:53:46 -08002518 dump.appendFormat(INDENT4 "touch.toolSize.isSummed: %s\n",
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002519 toString(mCalibration.toolSizeIsSummed));
Jeff Brown8d608662010-08-30 03:02:23 -07002520 }
2521
2522 // Pressure
2523 switch (mCalibration.pressureCalibration) {
2524 case Calibration::PRESSURE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002525 dump.append(INDENT4 "touch.pressure.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002526 break;
2527 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002528 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002529 break;
2530 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002531 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002532 break;
2533 default:
2534 assert(false);
2535 }
2536
2537 switch (mCalibration.pressureSource) {
2538 case Calibration::PRESSURE_SOURCE_PRESSURE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002539 dump.append(INDENT4 "touch.pressure.source: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002540 break;
2541 case Calibration::PRESSURE_SOURCE_TOUCH:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002542 dump.append(INDENT4 "touch.pressure.source: touch\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002543 break;
2544 case Calibration::PRESSURE_SOURCE_DEFAULT:
2545 break;
2546 default:
2547 assert(false);
2548 }
2549
2550 if (mCalibration.havePressureScale) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07002551 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
2552 mCalibration.pressureScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002553 }
2554
2555 // Size
2556 switch (mCalibration.sizeCalibration) {
2557 case Calibration::SIZE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002558 dump.append(INDENT4 "touch.size.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002559 break;
2560 case Calibration::SIZE_CALIBRATION_NORMALIZED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002561 dump.append(INDENT4 "touch.size.calibration: normalized\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002562 break;
2563 default:
2564 assert(false);
2565 }
2566
2567 // Orientation
2568 switch (mCalibration.orientationCalibration) {
2569 case Calibration::ORIENTATION_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002570 dump.append(INDENT4 "touch.orientation.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002571 break;
2572 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002573 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002574 break;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002575 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
2576 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
2577 break;
Jeff Brown8d608662010-08-30 03:02:23 -07002578 default:
2579 assert(false);
2580 }
2581}
2582
Jeff Brown6d0fec22010-07-23 21:28:06 -07002583void TouchInputMapper::reset() {
2584 // Synthesize touch up event if touch is currently down.
2585 // This will also take care of finishing virtual key processing if needed.
2586 if (mLastTouch.pointerCount != 0) {
2587 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
2588 mCurrentTouch.clear();
2589 syncTouch(when, true);
2590 }
2591
Jeff Brown6328cdc2010-07-29 18:18:33 -07002592 { // acquire lock
2593 AutoMutex _l(mLock);
2594 initializeLocked();
2595 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002596
Jeff Brown6328cdc2010-07-29 18:18:33 -07002597 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002598}
2599
2600void TouchInputMapper::syncTouch(nsecs_t when, bool havePointerIds) {
Jeff Brownaa3855d2011-03-17 01:34:19 -07002601#if DEBUG_RAW_EVENTS
2602 if (!havePointerIds) {
2603 LOGD("syncTouch: pointerCount=%d, no pointer ids", mCurrentTouch.pointerCount);
2604 } else {
2605 LOGD("syncTouch: pointerCount=%d, up=0x%08x, down=0x%08x, move=0x%08x, "
2606 "last=0x%08x, current=0x%08x", mCurrentTouch.pointerCount,
2607 mLastTouch.idBits.value & ~mCurrentTouch.idBits.value,
2608 mCurrentTouch.idBits.value & ~mLastTouch.idBits.value,
2609 mLastTouch.idBits.value & mCurrentTouch.idBits.value,
2610 mLastTouch.idBits.value, mCurrentTouch.idBits.value);
2611 }
2612#endif
2613
Jeff Brown6328cdc2010-07-29 18:18:33 -07002614 // Preprocess pointer data.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002615 if (mParameters.useBadTouchFilter) {
2616 if (applyBadTouchFilter()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002617 havePointerIds = false;
2618 }
2619 }
2620
Jeff Brown6d0fec22010-07-23 21:28:06 -07002621 if (mParameters.useJumpyTouchFilter) {
2622 if (applyJumpyTouchFilter()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002623 havePointerIds = false;
2624 }
2625 }
2626
Jeff Brownaa3855d2011-03-17 01:34:19 -07002627 if (!havePointerIds) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002628 calculatePointerIds();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002629 }
2630
Jeff Brown6d0fec22010-07-23 21:28:06 -07002631 TouchData temp;
2632 TouchData* savedTouch;
2633 if (mParameters.useAveragingTouchFilter) {
2634 temp.copyFrom(mCurrentTouch);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002635 savedTouch = & temp;
2636
Jeff Brown6d0fec22010-07-23 21:28:06 -07002637 applyAveragingTouchFilter();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002638 } else {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002639 savedTouch = & mCurrentTouch;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002640 }
2641
Jeff Brown56194eb2011-03-02 19:23:13 -08002642 uint32_t policyFlags = 0;
Jeff Brown05dc66a2011-03-02 14:41:58 -08002643 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
Jeff Brownefd32662011-03-08 15:13:06 -08002644 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
2645 // If this is a touch screen, hide the pointer on an initial down.
2646 getContext()->fadePointer();
2647 }
Jeff Brown56194eb2011-03-02 19:23:13 -08002648
2649 // Initial downs on external touch devices should wake the device.
2650 // We don't do this for internal touch screens to prevent them from waking
2651 // up in your pocket.
2652 // TODO: Use the input device configuration to control this behavior more finely.
2653 if (getDevice()->isExternal()) {
2654 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
2655 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08002656 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002657
Jeff Brown05dc66a2011-03-02 14:41:58 -08002658 // Process touches and virtual keys.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002659 TouchResult touchResult = consumeOffScreenTouches(when, policyFlags);
2660 if (touchResult == DISPATCH_TOUCH) {
Jeff Brownefd32662011-03-08 15:13:06 -08002661 suppressSwipeOntoVirtualKeys(when);
Jeff Brownace13b12011-03-09 17:39:48 -08002662 if (mPointerController != NULL) {
2663 dispatchPointerGestures(when, policyFlags);
2664 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002665 dispatchTouches(when, policyFlags);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002666 }
2667
Jeff Brown6328cdc2010-07-29 18:18:33 -07002668 // Copy current touch to last touch in preparation for the next cycle.
Jeff Brownace13b12011-03-09 17:39:48 -08002669 // Keep the button state so we can track edge-triggered button state changes.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002670 if (touchResult == DROP_STROKE) {
2671 mLastTouch.clear();
Jeff Brownace13b12011-03-09 17:39:48 -08002672 mLastTouch.buttonState = savedTouch->buttonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002673 } else {
2674 mLastTouch.copyFrom(*savedTouch);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002675 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002676}
2677
Jeff Brown6d0fec22010-07-23 21:28:06 -07002678TouchInputMapper::TouchResult TouchInputMapper::consumeOffScreenTouches(
2679 nsecs_t when, uint32_t policyFlags) {
2680 int32_t keyEventAction, keyEventFlags;
2681 int32_t keyCode, scanCode, downTime;
2682 TouchResult touchResult;
Jeff Brown349703e2010-06-22 01:27:15 -07002683
Jeff Brown6328cdc2010-07-29 18:18:33 -07002684 { // acquire lock
2685 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002686
Jeff Brown6328cdc2010-07-29 18:18:33 -07002687 // Update surface size and orientation, including virtual key positions.
2688 if (! configureSurfaceLocked()) {
2689 return DROP_STROKE;
2690 }
2691
2692 // Check for virtual key press.
2693 if (mLocked.currentVirtualKey.down) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002694 if (mCurrentTouch.pointerCount == 0) {
2695 // Pointer went up while virtual key was down.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002696 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002697#if DEBUG_VIRTUAL_KEYS
2698 LOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002699 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002700#endif
2701 keyEventAction = AKEY_EVENT_ACTION_UP;
2702 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2703 touchResult = SKIP_TOUCH;
2704 goto DispatchVirtualKey;
2705 }
2706
2707 if (mCurrentTouch.pointerCount == 1) {
2708 int32_t x = mCurrentTouch.pointers[0].x;
2709 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002710 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
2711 if (virtualKey && virtualKey->keyCode == mLocked.currentVirtualKey.keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002712 // Pointer is still within the space of the virtual key.
2713 return SKIP_TOUCH;
2714 }
2715 }
2716
2717 // Pointer left virtual key area or another pointer also went down.
2718 // Send key cancellation and drop the stroke so subsequent motions will be
2719 // considered fresh downs. This is useful when the user swipes away from the
2720 // virtual key area into the main display surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002721 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002722#if DEBUG_VIRTUAL_KEYS
2723 LOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002724 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002725#endif
2726 keyEventAction = AKEY_EVENT_ACTION_UP;
2727 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
2728 | AKEY_EVENT_FLAG_CANCELED;
Jeff Brownc3db8582010-10-20 15:33:38 -07002729
2730 // Check whether the pointer moved inside the display area where we should
2731 // start a new stroke.
2732 int32_t x = mCurrentTouch.pointers[0].x;
2733 int32_t y = mCurrentTouch.pointers[0].y;
2734 if (isPointInsideSurfaceLocked(x, y)) {
2735 mLastTouch.clear();
2736 touchResult = DISPATCH_TOUCH;
2737 } else {
2738 touchResult = DROP_STROKE;
2739 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002740 } else {
2741 if (mCurrentTouch.pointerCount >= 1 && mLastTouch.pointerCount == 0) {
2742 // Pointer just went down. Handle off-screen touches, if needed.
2743 int32_t x = mCurrentTouch.pointers[0].x;
2744 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002745 if (! isPointInsideSurfaceLocked(x, y)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002746 // If exactly one pointer went down, check for virtual key hit.
2747 // Otherwise we will drop the entire stroke.
2748 if (mCurrentTouch.pointerCount == 1) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002749 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002750 if (virtualKey) {
Jeff Brownfe508922011-01-18 15:10:10 -08002751 if (mContext->shouldDropVirtualKey(when, getDevice(),
2752 virtualKey->keyCode, virtualKey->scanCode)) {
2753 return DROP_STROKE;
2754 }
2755
Jeff Brown6328cdc2010-07-29 18:18:33 -07002756 mLocked.currentVirtualKey.down = true;
2757 mLocked.currentVirtualKey.downTime = when;
2758 mLocked.currentVirtualKey.keyCode = virtualKey->keyCode;
2759 mLocked.currentVirtualKey.scanCode = virtualKey->scanCode;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002760#if DEBUG_VIRTUAL_KEYS
2761 LOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002762 mLocked.currentVirtualKey.keyCode,
2763 mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002764#endif
2765 keyEventAction = AKEY_EVENT_ACTION_DOWN;
2766 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM
2767 | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2768 touchResult = SKIP_TOUCH;
2769 goto DispatchVirtualKey;
2770 }
2771 }
2772 return DROP_STROKE;
2773 }
2774 }
2775 return DISPATCH_TOUCH;
2776 }
2777
2778 DispatchVirtualKey:
2779 // Collect remaining state needed to dispatch virtual key.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002780 keyCode = mLocked.currentVirtualKey.keyCode;
2781 scanCode = mLocked.currentVirtualKey.scanCode;
2782 downTime = mLocked.currentVirtualKey.downTime;
2783 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002784
2785 // Dispatch virtual key.
2786 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown0eaf3932010-10-01 14:55:30 -07002787 policyFlags |= POLICY_FLAG_VIRTUAL;
Jeff Brownb6997262010-10-08 22:31:17 -07002788 getDispatcher()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
2789 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
2790 return touchResult;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002791}
2792
Jeff Brownefd32662011-03-08 15:13:06 -08002793void TouchInputMapper::suppressSwipeOntoVirtualKeys(nsecs_t when) {
Jeff Brownfe508922011-01-18 15:10:10 -08002794 // Disable all virtual key touches that happen within a short time interval of the
2795 // most recent touch. The idea is to filter out stray virtual key presses when
2796 // interacting with the touch screen.
2797 //
2798 // Problems we're trying to solve:
2799 //
2800 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
2801 // virtual key area that is implemented by a separate touch panel and accidentally
2802 // triggers a virtual key.
2803 //
2804 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
2805 // area and accidentally triggers a virtual key. This often happens when virtual keys
2806 // are layed out below the screen near to where the on screen keyboard's space bar
2807 // is displayed.
2808 if (mParameters.virtualKeyQuietTime > 0 && mCurrentTouch.pointerCount != 0) {
2809 mContext->disableVirtualKeysUntil(when + mParameters.virtualKeyQuietTime);
2810 }
2811}
2812
Jeff Brown6d0fec22010-07-23 21:28:06 -07002813void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
2814 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
2815 uint32_t lastPointerCount = mLastTouch.pointerCount;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002816 if (currentPointerCount == 0 && lastPointerCount == 0) {
2817 return; // nothing to do!
2818 }
2819
Jeff Brownace13b12011-03-09 17:39:48 -08002820 // Update current touch coordinates.
2821 int32_t edgeFlags;
2822 float xPrecision, yPrecision;
2823 prepareTouches(&edgeFlags, &xPrecision, &yPrecision);
2824
2825 // Dispatch motions.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002826 BitSet32 currentIdBits = mCurrentTouch.idBits;
2827 BitSet32 lastIdBits = mLastTouch.idBits;
Jeff Brownace13b12011-03-09 17:39:48 -08002828 uint32_t metaState = getContext()->getGlobalMetaState();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002829
2830 if (currentIdBits == lastIdBits) {
2831 // No pointer id changes so this is a move event.
2832 // The dispatcher takes care of batching moves so we don't have to deal with that here.
Jeff Brownace13b12011-03-09 17:39:48 -08002833 dispatchMotion(when, policyFlags, mTouchSource,
2834 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
2835 mCurrentTouchCoords, mCurrentTouch.idToIndex, currentIdBits, -1,
2836 xPrecision, yPrecision, mDownTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002837 } else {
Jeff Brownc3db8582010-10-20 15:33:38 -07002838 // There may be pointers going up and pointers going down and pointers moving
2839 // all at the same time.
Jeff Brownace13b12011-03-09 17:39:48 -08002840 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2841 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002842 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
Jeff Brownace13b12011-03-09 17:39:48 -08002843 BitSet32 dispatchedIdBits(lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002844
Jeff Brownace13b12011-03-09 17:39:48 -08002845 // Update last coordinates of pointers that have moved so that we observe the new
2846 // pointer positions at the same time as other pointers that have just gone up.
2847 bool moveNeeded = updateMovedPointerCoords(
2848 mCurrentTouchCoords, mCurrentTouch.idToIndex,
2849 mLastTouchCoords, mLastTouch.idToIndex,
2850 moveIdBits);
Jeff Brownc3db8582010-10-20 15:33:38 -07002851
Jeff Brownace13b12011-03-09 17:39:48 -08002852 // Dispatch pointer up events.
Jeff Brownc3db8582010-10-20 15:33:38 -07002853 while (!upIdBits.isEmpty()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002854 uint32_t upId = upIdBits.firstMarkedBit();
2855 upIdBits.clearBit(upId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002856
Jeff Brownace13b12011-03-09 17:39:48 -08002857 dispatchMotion(when, policyFlags, mTouchSource,
2858 AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, 0,
2859 mLastTouchCoords, mLastTouch.idToIndex, dispatchedIdBits, upId,
2860 xPrecision, yPrecision, mDownTime);
2861 dispatchedIdBits.clearBit(upId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002862 }
2863
Jeff Brownc3db8582010-10-20 15:33:38 -07002864 // Dispatch move events if any of the remaining pointers moved from their old locations.
2865 // Although applications receive new locations as part of individual pointer up
2866 // events, they do not generally handle them except when presented in a move event.
2867 if (moveNeeded) {
Jeff Brownace13b12011-03-09 17:39:48 -08002868 assert(moveIdBits.value == dispatchedIdBits.value);
2869 dispatchMotion(when, policyFlags, mTouchSource,
2870 AMOTION_EVENT_ACTION_MOVE, 0, metaState, 0,
2871 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, -1,
2872 xPrecision, yPrecision, mDownTime);
Jeff Brownc3db8582010-10-20 15:33:38 -07002873 }
2874
2875 // Dispatch pointer down events using the new pointer locations.
2876 while (!downIdBits.isEmpty()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002877 uint32_t downId = downIdBits.firstMarkedBit();
2878 downIdBits.clearBit(downId);
Jeff Brownace13b12011-03-09 17:39:48 -08002879 dispatchedIdBits.markBit(downId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002880
Jeff Brownace13b12011-03-09 17:39:48 -08002881 if (dispatchedIdBits.count() == 1) {
2882 // First pointer is going down. Set down time.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002883 mDownTime = when;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002884 } else {
Jeff Brownace13b12011-03-09 17:39:48 -08002885 // Only send edge flags with first pointer down.
2886 edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002887 }
2888
Jeff Brownace13b12011-03-09 17:39:48 -08002889 dispatchMotion(when, policyFlags, mTouchSource,
2890 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
2891 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, downId,
2892 xPrecision, yPrecision, mDownTime);
2893 }
2894 }
2895
2896 // Update state for next time.
2897 for (uint32_t i = 0; i < currentPointerCount; i++) {
2898 mLastTouchCoords[i].copyFrom(mCurrentTouchCoords[i]);
2899 }
2900}
2901
2902void TouchInputMapper::prepareTouches(int32_t* outEdgeFlags,
2903 float* outXPrecision, float* outYPrecision) {
2904 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
2905 uint32_t lastPointerCount = mLastTouch.pointerCount;
2906
2907 AutoMutex _l(mLock);
2908
2909 // Walk through the the active pointers and map touch screen coordinates (TouchData) into
2910 // display or surface coordinates (PointerCoords) and adjust for display orientation.
2911 for (uint32_t i = 0; i < currentPointerCount; i++) {
2912 const PointerData& in = mCurrentTouch.pointers[i];
2913
2914 // ToolMajor and ToolMinor
2915 float toolMajor, toolMinor;
2916 switch (mCalibration.toolSizeCalibration) {
2917 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
2918 toolMajor = in.toolMajor * mLocked.geometricScale;
2919 if (mRawAxes.toolMinor.valid) {
2920 toolMinor = in.toolMinor * mLocked.geometricScale;
2921 } else {
2922 toolMinor = toolMajor;
2923 }
2924 break;
2925 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
2926 toolMajor = in.toolMajor != 0
2927 ? in.toolMajor * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias
2928 : 0;
2929 if (mRawAxes.toolMinor.valid) {
2930 toolMinor = in.toolMinor != 0
2931 ? in.toolMinor * mLocked.toolSizeLinearScale
2932 + mLocked.toolSizeLinearBias
2933 : 0;
2934 } else {
2935 toolMinor = toolMajor;
2936 }
2937 break;
2938 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
2939 if (in.toolMajor != 0) {
2940 float diameter = sqrtf(in.toolMajor
2941 * mLocked.toolSizeAreaScale + mLocked.toolSizeAreaBias);
2942 toolMajor = diameter * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias;
2943 } else {
2944 toolMajor = 0;
2945 }
2946 toolMinor = toolMajor;
2947 break;
2948 default:
2949 toolMajor = 0;
2950 toolMinor = 0;
2951 break;
2952 }
2953
2954 if (mCalibration.haveToolSizeIsSummed && mCalibration.toolSizeIsSummed) {
2955 toolMajor /= currentPointerCount;
2956 toolMinor /= currentPointerCount;
2957 }
2958
2959 // Pressure
2960 float rawPressure;
2961 switch (mCalibration.pressureSource) {
2962 case Calibration::PRESSURE_SOURCE_PRESSURE:
2963 rawPressure = in.pressure;
2964 break;
2965 case Calibration::PRESSURE_SOURCE_TOUCH:
2966 rawPressure = in.touchMajor;
2967 break;
2968 default:
2969 rawPressure = 0;
2970 }
2971
2972 float pressure;
2973 switch (mCalibration.pressureCalibration) {
2974 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
2975 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
2976 pressure = rawPressure * mLocked.pressureScale;
2977 break;
2978 default:
2979 pressure = 1;
2980 break;
2981 }
2982
2983 // TouchMajor and TouchMinor
2984 float touchMajor, touchMinor;
2985 switch (mCalibration.touchSizeCalibration) {
2986 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
2987 touchMajor = in.touchMajor * mLocked.geometricScale;
2988 if (mRawAxes.touchMinor.valid) {
2989 touchMinor = in.touchMinor * mLocked.geometricScale;
2990 } else {
2991 touchMinor = touchMajor;
2992 }
2993 break;
2994 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
2995 touchMajor = toolMajor * pressure;
2996 touchMinor = toolMinor * pressure;
2997 break;
2998 default:
2999 touchMajor = 0;
3000 touchMinor = 0;
3001 break;
3002 }
3003
3004 if (touchMajor > toolMajor) {
3005 touchMajor = toolMajor;
3006 }
3007 if (touchMinor > toolMinor) {
3008 touchMinor = toolMinor;
3009 }
3010
3011 // Size
3012 float size;
3013 switch (mCalibration.sizeCalibration) {
3014 case Calibration::SIZE_CALIBRATION_NORMALIZED: {
3015 float rawSize = mRawAxes.toolMinor.valid
3016 ? avg(in.toolMajor, in.toolMinor)
3017 : in.toolMajor;
3018 size = rawSize * mLocked.sizeScale;
3019 break;
3020 }
3021 default:
3022 size = 0;
3023 break;
3024 }
3025
3026 // Orientation
3027 float orientation;
3028 switch (mCalibration.orientationCalibration) {
3029 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3030 orientation = in.orientation * mLocked.orientationScale;
3031 break;
3032 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
3033 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
3034 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
3035 if (c1 != 0 || c2 != 0) {
3036 orientation = atan2f(c1, c2) * 0.5f;
3037 float scale = 1.0f + pythag(c1, c2) / 16.0f;
3038 touchMajor *= scale;
3039 touchMinor /= scale;
3040 toolMajor *= scale;
3041 toolMinor /= scale;
3042 } else {
3043 orientation = 0;
3044 }
3045 break;
3046 }
3047 default:
3048 orientation = 0;
3049 }
3050
3051 // X and Y
3052 // Adjust coords for surface orientation.
3053 float x, y;
3054 switch (mLocked.surfaceOrientation) {
3055 case DISPLAY_ORIENTATION_90:
3056 x = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3057 y = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3058 orientation -= M_PI_2;
3059 if (orientation < - M_PI_2) {
3060 orientation += M_PI;
3061 }
3062 break;
3063 case DISPLAY_ORIENTATION_180:
3064 x = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3065 y = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3066 break;
3067 case DISPLAY_ORIENTATION_270:
3068 x = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3069 y = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3070 orientation += M_PI_2;
3071 if (orientation > M_PI_2) {
3072 orientation -= M_PI;
3073 }
3074 break;
3075 default:
3076 x = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3077 y = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3078 break;
3079 }
3080
3081 // Write output coords.
3082 PointerCoords& out = mCurrentTouchCoords[i];
3083 out.clear();
3084 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3085 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3086 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
3087 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
3088 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
3089 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
3090 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
3091 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
3092 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
3093 }
3094
3095 // Check edge flags by looking only at the first pointer since the flags are
3096 // global to the event.
3097 *outEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3098 if (lastPointerCount == 0 && currentPointerCount > 0) {
3099 const PointerData& in = mCurrentTouch.pointers[0];
3100
3101 if (in.x <= mRawAxes.x.minValue) {
3102 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_LEFT,
3103 mLocked.surfaceOrientation);
3104 } else if (in.x >= mRawAxes.x.maxValue) {
3105 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_RIGHT,
3106 mLocked.surfaceOrientation);
3107 }
3108 if (in.y <= mRawAxes.y.minValue) {
3109 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_TOP,
3110 mLocked.surfaceOrientation);
3111 } else if (in.y >= mRawAxes.y.maxValue) {
3112 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_BOTTOM,
3113 mLocked.surfaceOrientation);
3114 }
3115 }
3116
3117 *outXPrecision = mLocked.orientedXPrecision;
3118 *outYPrecision = mLocked.orientedYPrecision;
3119}
3120
3121void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags) {
3122 // Update current gesture coordinates.
3123 bool cancelPreviousGesture, finishPreviousGesture;
3124 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture);
3125
3126 // Send events!
3127 uint32_t metaState = getContext()->getGlobalMetaState();
3128
3129 // Update last coordinates of pointers that have moved so that we observe the new
3130 // pointer positions at the same time as other pointers that have just gone up.
3131 bool down = mPointerGesture.currentGestureMode == PointerGesture::CLICK_OR_DRAG
3132 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
3133 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
3134 bool moveNeeded = false;
3135 if (down && !cancelPreviousGesture && !finishPreviousGesture
3136 && mPointerGesture.lastGesturePointerCount != 0
3137 && mPointerGesture.currentGesturePointerCount != 0) {
3138 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
3139 & mPointerGesture.lastGestureIdBits.value);
3140 moveNeeded = updateMovedPointerCoords(
3141 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3142 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3143 movedGestureIdBits);
3144 }
3145
3146 // Send motion events for all pointers that went up or were canceled.
3147 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
3148 if (!dispatchedGestureIdBits.isEmpty()) {
3149 if (cancelPreviousGesture) {
3150 dispatchMotion(when, policyFlags, mPointerSource,
3151 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3152 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3153 dispatchedGestureIdBits, -1,
3154 0, 0, mPointerGesture.downTime);
3155
3156 dispatchedGestureIdBits.clear();
3157 } else {
3158 BitSet32 upGestureIdBits;
3159 if (finishPreviousGesture) {
3160 upGestureIdBits = dispatchedGestureIdBits;
3161 } else {
3162 upGestureIdBits.value = dispatchedGestureIdBits.value
3163 & ~mPointerGesture.currentGestureIdBits.value;
3164 }
3165 while (!upGestureIdBits.isEmpty()) {
3166 uint32_t id = upGestureIdBits.firstMarkedBit();
3167 upGestureIdBits.clearBit(id);
3168
3169 dispatchMotion(when, policyFlags, mPointerSource,
3170 AMOTION_EVENT_ACTION_POINTER_UP, 0,
3171 metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3172 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3173 dispatchedGestureIdBits, id,
3174 0, 0, mPointerGesture.downTime);
3175
3176 dispatchedGestureIdBits.clearBit(id);
3177 }
3178 }
3179 }
3180
3181 // Send motion events for all pointers that moved.
3182 if (moveNeeded) {
3183 dispatchMotion(when, policyFlags, mPointerSource,
3184 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3185 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3186 dispatchedGestureIdBits, -1,
3187 0, 0, mPointerGesture.downTime);
3188 }
3189
3190 // Send motion events for all pointers that went down.
3191 if (down) {
3192 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
3193 & ~dispatchedGestureIdBits.value);
3194 while (!downGestureIdBits.isEmpty()) {
3195 uint32_t id = downGestureIdBits.firstMarkedBit();
3196 downGestureIdBits.clearBit(id);
3197 dispatchedGestureIdBits.markBit(id);
3198
3199 int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3200 if (dispatchedGestureIdBits.count() == 1) {
3201 // First pointer is going down. Calculate edge flags and set down time.
3202 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3203 const PointerCoords& downCoords = mPointerGesture.currentGestureCoords[index];
3204 edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3205 downCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
3206 downCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3207 mPointerGesture.downTime = when;
3208 }
3209
3210 dispatchMotion(when, policyFlags, mPointerSource,
3211 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
3212 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3213 dispatchedGestureIdBits, id,
3214 0, 0, mPointerGesture.downTime);
3215 }
3216 }
3217
3218 // Send down and up for a tap.
3219 if (mPointerGesture.currentGestureMode == PointerGesture::TAP) {
3220 const PointerCoords& coords = mPointerGesture.currentGestureCoords[0];
3221 int32_t edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3222 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3223 coords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3224 nsecs_t downTime = mPointerGesture.downTime = mPointerGesture.tapTime;
3225 mPointerGesture.resetTapTime();
3226
3227 dispatchMotion(downTime, policyFlags, mPointerSource,
3228 AMOTION_EVENT_ACTION_DOWN, 0, metaState, edgeFlags,
3229 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3230 mPointerGesture.currentGestureIdBits, -1,
3231 0, 0, downTime);
3232 dispatchMotion(when, policyFlags, mPointerSource,
3233 AMOTION_EVENT_ACTION_UP, 0, metaState, edgeFlags,
3234 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3235 mPointerGesture.currentGestureIdBits, -1,
3236 0, 0, downTime);
3237 }
3238
3239 // Send motion events for hover.
3240 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
3241 dispatchMotion(when, policyFlags, mPointerSource,
3242 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3243 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3244 mPointerGesture.currentGestureIdBits, -1,
3245 0, 0, mPointerGesture.downTime);
3246 }
3247
3248 // Update state.
3249 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
3250 if (!down) {
3251 mPointerGesture.lastGesturePointerCount = 0;
3252 mPointerGesture.lastGestureIdBits.clear();
3253 } else {
3254 uint32_t currentGesturePointerCount = mPointerGesture.currentGesturePointerCount;
3255 mPointerGesture.lastGesturePointerCount = currentGesturePointerCount;
3256 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
3257 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
3258 uint32_t id = idBits.firstMarkedBit();
3259 idBits.clearBit(id);
3260 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3261 mPointerGesture.lastGestureCoords[index].copyFrom(
3262 mPointerGesture.currentGestureCoords[index]);
3263 mPointerGesture.lastGestureIdToIndex[id] = index;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003264 }
3265 }
3266}
3267
Jeff Brownace13b12011-03-09 17:39:48 -08003268void TouchInputMapper::preparePointerGestures(nsecs_t when,
3269 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture) {
3270 *outCancelPreviousGesture = false;
3271 *outFinishPreviousGesture = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003272
Jeff Brownace13b12011-03-09 17:39:48 -08003273 AutoMutex _l(mLock);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003274
Jeff Brownace13b12011-03-09 17:39:48 -08003275 // Update the velocity tracker.
3276 {
3277 VelocityTracker::Position positions[MAX_POINTERS];
3278 uint32_t count = 0;
3279 for (BitSet32 idBits(mCurrentTouch.idBits); !idBits.isEmpty(); count++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07003280 uint32_t id = idBits.firstMarkedBit();
3281 idBits.clearBit(id);
Jeff Brownace13b12011-03-09 17:39:48 -08003282 uint32_t index = mCurrentTouch.idToIndex[id];
3283 positions[count].x = mCurrentTouch.pointers[index].x
3284 * mLocked.pointerGestureXMovementScale;
3285 positions[count].y = mCurrentTouch.pointers[index].y
3286 * mLocked.pointerGestureYMovementScale;
3287 }
3288 mPointerGesture.velocityTracker.addMovement(when, mCurrentTouch.idBits, positions);
3289 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003290
Jeff Brownace13b12011-03-09 17:39:48 -08003291 // Pick a new active touch id if needed.
3292 // Choose an arbitrary pointer that just went down, if there is one.
3293 // Otherwise choose an arbitrary remaining pointer.
3294 // This guarantees we always have an active touch id when there is at least one pointer.
3295 // We always switch to the newest pointer down because that's usually where the user's
3296 // attention is focused.
3297 int32_t activeTouchId;
3298 BitSet32 downTouchIdBits(mCurrentTouch.idBits.value & ~mLastTouch.idBits.value);
3299 if (!downTouchIdBits.isEmpty()) {
3300 activeTouchId = mPointerGesture.activeTouchId = downTouchIdBits.firstMarkedBit();
3301 } else {
3302 activeTouchId = mPointerGesture.activeTouchId;
3303 if (activeTouchId < 0 || !mCurrentTouch.idBits.hasBit(activeTouchId)) {
3304 if (!mCurrentTouch.idBits.isEmpty()) {
3305 activeTouchId = mPointerGesture.activeTouchId =
3306 mCurrentTouch.idBits.firstMarkedBit();
3307 } else {
3308 activeTouchId = mPointerGesture.activeTouchId = -1;
3309 }
3310 }
3311 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003312
Jeff Brownace13b12011-03-09 17:39:48 -08003313 // Update the touch origin data to track where each finger originally went down.
3314 if (mCurrentTouch.pointerCount == 0 || mPointerGesture.touchOrigin.pointerCount == 0) {
3315 // Fast path when all fingers have gone up or down.
3316 mPointerGesture.touchOrigin.copyFrom(mCurrentTouch);
3317 } else {
3318 // Slow path when only some fingers have gone up or down.
3319 for (BitSet32 idBits(mPointerGesture.touchOrigin.idBits.value
3320 & ~mCurrentTouch.idBits.value); !idBits.isEmpty(); ) {
3321 uint32_t id = idBits.firstMarkedBit();
3322 idBits.clearBit(id);
3323 mPointerGesture.touchOrigin.idBits.clearBit(id);
3324 uint32_t index = mPointerGesture.touchOrigin.idToIndex[id];
3325 uint32_t count = --mPointerGesture.touchOrigin.pointerCount;
3326 while (index < count) {
3327 mPointerGesture.touchOrigin.pointers[index] =
3328 mPointerGesture.touchOrigin.pointers[index + 1];
3329 uint32_t movedId = mPointerGesture.touchOrigin.pointers[index].id;
3330 mPointerGesture.touchOrigin.idToIndex[movedId] = index;
3331 index += 1;
3332 }
3333 }
3334 for (BitSet32 idBits(mCurrentTouch.idBits.value
3335 & ~mPointerGesture.touchOrigin.idBits.value); !idBits.isEmpty(); ) {
3336 uint32_t id = idBits.firstMarkedBit();
3337 idBits.clearBit(id);
3338 mPointerGesture.touchOrigin.idBits.markBit(id);
3339 uint32_t index = mPointerGesture.touchOrigin.pointerCount++;
3340 mPointerGesture.touchOrigin.pointers[index] =
3341 mCurrentTouch.pointers[mCurrentTouch.idToIndex[id]];
3342 mPointerGesture.touchOrigin.idToIndex[id] = index;
3343 }
3344 }
3345
3346 // Determine whether we are in quiet time.
3347 bool isQuietTime = when < mPointerGesture.quietTime + QUIET_INTERVAL;
3348 if (!isQuietTime) {
3349 if ((mPointerGesture.lastGestureMode == PointerGesture::SWIPE
3350 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
3351 && mCurrentTouch.pointerCount < 2) {
3352 // Enter quiet time when exiting swipe or freeform state.
3353 // This is to prevent accidentally entering the hover state and flinging the
3354 // pointer when finishing a swipe and there is still one pointer left onscreen.
3355 isQuietTime = true;
3356 } else if (mPointerGesture.lastGestureMode == PointerGesture::CLICK_OR_DRAG
3357 && mCurrentTouch.pointerCount >= 2
3358 && !isPointerDown(mCurrentTouch.buttonState)) {
3359 // Enter quiet time when releasing the button and there are still two or more
3360 // fingers down. This may indicate that one finger was used to press the button
3361 // but it has not gone up yet.
3362 isQuietTime = true;
3363 }
3364 if (isQuietTime) {
3365 mPointerGesture.quietTime = when;
3366 }
3367 }
3368
3369 // Switch states based on button and pointer state.
3370 if (isQuietTime) {
3371 // Case 1: Quiet time. (QUIET)
3372#if DEBUG_GESTURES
3373 LOGD("Gestures: QUIET for next %0.3fms",
3374 (mPointerGesture.quietTime + QUIET_INTERVAL - when) * 0.000001f);
3375#endif
3376 *outFinishPreviousGesture = true;
3377
3378 mPointerGesture.activeGestureId = -1;
3379 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
3380 mPointerGesture.currentGesturePointerCount = 0;
3381 mPointerGesture.currentGestureIdBits.clear();
3382 } else if (isPointerDown(mCurrentTouch.buttonState)) {
3383 // Case 2: Button is pressed. (DRAG)
3384 // The pointer follows the active touch point.
3385 // Emit DOWN, MOVE, UP events at the pointer location.
3386 //
3387 // Only the active touch matters; other fingers are ignored. This policy helps
3388 // to handle the case where the user places a second finger on the touch pad
3389 // to apply the necessary force to depress an integrated button below the surface.
3390 // We don't want the second finger to be delivered to applications.
3391 //
3392 // For this to work well, we need to make sure to track the pointer that is really
3393 // active. If the user first puts one finger down to click then adds another
3394 // finger to drag then the active pointer should switch to the finger that is
3395 // being dragged.
3396#if DEBUG_GESTURES
3397 LOGD("Gestures: CLICK_OR_DRAG activeTouchId=%d, "
3398 "currentTouchPointerCount=%d", activeTouchId, mCurrentTouch.pointerCount);
3399#endif
3400 // Reset state when just starting.
3401 if (mPointerGesture.lastGestureMode != PointerGesture::CLICK_OR_DRAG) {
3402 *outFinishPreviousGesture = true;
3403 mPointerGesture.activeGestureId = 0;
3404 }
3405
3406 // Switch pointers if needed.
3407 // Find the fastest pointer and follow it.
3408 if (activeTouchId >= 0) {
3409 if (mCurrentTouch.pointerCount > 1) {
3410 int32_t bestId = -1;
3411 float bestSpeed = DRAG_MIN_SWITCH_SPEED;
3412 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3413 uint32_t id = mCurrentTouch.pointers[i].id;
3414 float vx, vy;
3415 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
3416 float speed = pythag(vx, vy);
3417 if (speed > bestSpeed) {
3418 bestId = id;
3419 bestSpeed = speed;
3420 }
3421 }
Jeff Brown8d608662010-08-30 03:02:23 -07003422 }
Jeff Brownace13b12011-03-09 17:39:48 -08003423 if (bestId >= 0 && bestId != activeTouchId) {
3424 mPointerGesture.activeTouchId = activeTouchId = bestId;
3425#if DEBUG_GESTURES
3426 LOGD("Gestures: CLICK_OR_DRAG switched pointers, "
3427 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
3428#endif
Jeff Brown8d608662010-08-30 03:02:23 -07003429 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003430 }
3431
Jeff Brownace13b12011-03-09 17:39:48 -08003432 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3433 const PointerData& currentPointer =
3434 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3435 const PointerData& lastPointer =
3436 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3437 float deltaX = (currentPointer.x - lastPointer.x)
3438 * mLocked.pointerGestureXMovementScale;
3439 float deltaY = (currentPointer.y - lastPointer.y)
3440 * mLocked.pointerGestureYMovementScale;
3441 mPointerController->move(deltaX, deltaY);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003442 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003443 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003444
Jeff Brownace13b12011-03-09 17:39:48 -08003445 float x, y;
3446 mPointerController->getPosition(&x, &y);
Jeff Brown91c69ab2011-02-14 17:03:18 -08003447
Jeff Brownace13b12011-03-09 17:39:48 -08003448 mPointerGesture.currentGestureMode = PointerGesture::CLICK_OR_DRAG;
3449 mPointerGesture.currentGesturePointerCount = 1;
3450 mPointerGesture.currentGestureIdBits.clear();
3451 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3452 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3453 mPointerGesture.currentGestureCoords[0].clear();
3454 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3455 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3456 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3457 } else if (mCurrentTouch.pointerCount == 0) {
3458 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
3459 *outFinishPreviousGesture = true;
3460
3461 // Watch for taps coming out of HOVER or INDETERMINATE_MULTITOUCH mode.
3462 bool tapped = false;
3463 if (mPointerGesture.lastGestureMode == PointerGesture::HOVER
3464 || mPointerGesture.lastGestureMode
3465 == PointerGesture::INDETERMINATE_MULTITOUCH) {
3466 if (when <= mPointerGesture.tapTime + TAP_INTERVAL) {
3467 float x, y;
3468 mPointerController->getPosition(&x, &y);
3469 if (fabs(x - mPointerGesture.initialPointerX) <= TAP_SLOP
3470 && fabs(y - mPointerGesture.initialPointerY) <= TAP_SLOP) {
3471#if DEBUG_GESTURES
3472 LOGD("Gestures: TAP");
3473#endif
3474 mPointerGesture.activeGestureId = 0;
3475 mPointerGesture.currentGestureMode = PointerGesture::TAP;
3476 mPointerGesture.currentGesturePointerCount = 1;
3477 mPointerGesture.currentGestureIdBits.clear();
3478 mPointerGesture.currentGestureIdBits.markBit(
3479 mPointerGesture.activeGestureId);
3480 mPointerGesture.currentGestureIdToIndex[
3481 mPointerGesture.activeGestureId] = 0;
3482 mPointerGesture.currentGestureCoords[0].clear();
3483 mPointerGesture.currentGestureCoords[0].setAxisValue(
3484 AMOTION_EVENT_AXIS_X, mPointerGesture.initialPointerX);
3485 mPointerGesture.currentGestureCoords[0].setAxisValue(
3486 AMOTION_EVENT_AXIS_Y, mPointerGesture.initialPointerY);
3487 mPointerGesture.currentGestureCoords[0].setAxisValue(
3488 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3489 tapped = true;
3490 } else {
3491#if DEBUG_GESTURES
3492 LOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
3493 x - mPointerGesture.initialPointerX,
3494 y - mPointerGesture.initialPointerY);
3495#endif
3496 }
3497 } else {
3498#if DEBUG_GESTURES
3499 LOGD("Gestures: Not a TAP, delay=%lld",
3500 when - mPointerGesture.tapTime);
3501#endif
Jeff Brown6328cdc2010-07-29 18:18:33 -07003502 }
Jeff Brownace13b12011-03-09 17:39:48 -08003503 }
3504 if (!tapped) {
3505#if DEBUG_GESTURES
3506 LOGD("Gestures: NEUTRAL");
3507#endif
3508 mPointerGesture.activeGestureId = -1;
3509 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
3510 mPointerGesture.currentGesturePointerCount = 0;
3511 mPointerGesture.currentGestureIdBits.clear();
3512 }
3513 } else if (mCurrentTouch.pointerCount == 1) {
3514 // Case 4. Exactly one finger down, button is not pressed. (HOVER)
3515 // The pointer follows the active touch point.
3516 // Emit HOVER_MOVE events at the pointer location.
3517 assert(activeTouchId >= 0);
3518
3519#if DEBUG_GESTURES
3520 LOGD("Gestures: HOVER");
3521#endif
3522
3523 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3524 const PointerData& currentPointer =
3525 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3526 const PointerData& lastPointer =
3527 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3528 float deltaX = (currentPointer.x - lastPointer.x)
3529 * mLocked.pointerGestureXMovementScale;
3530 float deltaY = (currentPointer.y - lastPointer.y)
3531 * mLocked.pointerGestureYMovementScale;
3532 mPointerController->move(deltaX, deltaY);
3533 }
3534
3535 *outFinishPreviousGesture = true;
3536 mPointerGesture.activeGestureId = 0;
3537
3538 float x, y;
3539 mPointerController->getPosition(&x, &y);
3540
3541 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
3542 mPointerGesture.currentGesturePointerCount = 1;
3543 mPointerGesture.currentGestureIdBits.clear();
3544 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3545 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3546 mPointerGesture.currentGestureCoords[0].clear();
3547 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3548 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3549 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 0.0f);
3550
3551 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
3552 mPointerGesture.tapTime = when;
3553 mPointerGesture.initialPointerX = x;
3554 mPointerGesture.initialPointerY = y;
3555 }
3556 } else {
3557 // Case 5. At least two fingers down, button is not pressed. (SWIPE or FREEFORM
3558 // or INDETERMINATE_MULTITOUCH)
3559 // Initially we watch and wait for something interesting to happen so as to
3560 // avoid making a spurious guess as to the nature of the gesture. For example,
3561 // the fingers may be in transition to some other state such as pressing or
3562 // releasing the button or we may be performing a two finger tap.
3563 //
3564 // Fix the centroid of the figure when the gesture actually starts.
3565 // We do not recalculate the centroid at any other time during the gesture because
3566 // it would affect the relationship of the touch points relative to the pointer location.
3567 assert(activeTouchId >= 0);
3568
3569 uint32_t currentTouchPointerCount = mCurrentTouch.pointerCount;
3570 if (currentTouchPointerCount > MAX_POINTERS) {
3571 currentTouchPointerCount = MAX_POINTERS;
3572 }
3573
3574 if (mPointerGesture.lastGestureMode != PointerGesture::INDETERMINATE_MULTITOUCH
3575 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
3576 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
3577 mPointerGesture.currentGestureMode = PointerGesture::INDETERMINATE_MULTITOUCH;
3578
3579 *outFinishPreviousGesture = true;
3580 mPointerGesture.activeGestureId = -1;
3581
3582 // Remember the initial pointer location.
3583 // Everything we do will be relative to this location.
3584 mPointerController->getPosition(&mPointerGesture.initialPointerX,
3585 &mPointerGesture.initialPointerY);
3586
3587 // Track taps.
3588 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
3589 mPointerGesture.tapTime = when;
3590 }
3591
3592 // Reset the touch origin to be relative to exactly where the fingers are now
3593 // in case they have moved some distance away as part of a previous gesture.
3594 // We want to know how far the fingers have traveled since we started considering
3595 // a multitouch gesture.
3596 mPointerGesture.touchOrigin.copyFrom(mCurrentTouch);
3597 } else {
3598 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3599 }
3600
3601 if (mPointerGesture.currentGestureMode == PointerGesture::INDETERMINATE_MULTITOUCH) {
3602 // Wait for the pointers to start moving before doing anything.
3603 bool decideNow = true;
3604 for (uint32_t i = 0; i < currentTouchPointerCount; i++) {
3605 const PointerData& current = mCurrentTouch.pointers[i];
3606 const PointerData& origin = mPointerGesture.touchOrigin.pointers[
3607 mPointerGesture.touchOrigin.idToIndex[current.id]];
3608 float distance = pythag(
3609 (current.x - origin.x) * mLocked.pointerGestureXZoomScale,
3610 (current.y - origin.y) * mLocked.pointerGestureYZoomScale);
3611 if (distance < MULTITOUCH_MIN_TRAVEL) {
3612 decideNow = false;
3613 break;
3614 }
3615 }
3616
3617 if (decideNow) {
3618 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
3619 if (currentTouchPointerCount == 2
3620 && distanceSquared(
3621 mCurrentTouch.pointers[0].x, mCurrentTouch.pointers[0].y,
3622 mCurrentTouch.pointers[1].x, mCurrentTouch.pointers[1].y)
3623 <= mLocked.pointerGestureMaxSwipeWidthSquared) {
3624 const PointerData& current1 = mCurrentTouch.pointers[0];
3625 const PointerData& current2 = mCurrentTouch.pointers[1];
3626 const PointerData& origin1 = mPointerGesture.touchOrigin.pointers[
3627 mPointerGesture.touchOrigin.idToIndex[current1.id]];
3628 const PointerData& origin2 = mPointerGesture.touchOrigin.pointers[
3629 mPointerGesture.touchOrigin.idToIndex[current2.id]];
3630
3631 float x1 = (current1.x - origin1.x) * mLocked.pointerGestureXZoomScale;
3632 float y1 = (current1.y - origin1.y) * mLocked.pointerGestureYZoomScale;
3633 float x2 = (current2.x - origin2.x) * mLocked.pointerGestureXZoomScale;
3634 float y2 = (current2.y - origin2.y) * mLocked.pointerGestureYZoomScale;
3635 float magnitude1 = pythag(x1, y1);
3636 float magnitude2 = pythag(x2, y2);
3637
3638 // Calculate the dot product of the vectors.
3639 // When the vectors are oriented in approximately the same direction,
3640 // the angle betweeen them is near zero and the cosine of the angle
3641 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
3642 // We know that the magnitude is at least MULTITOUCH_MIN_TRAVEL because
3643 // we checked it above.
3644 float dot = x1 * x2 + y1 * y2;
3645 float cosine = dot / (magnitude1 * magnitude2); // denominator always > 0
3646 if (cosine > SWIPE_TRANSITION_ANGLE_COSINE) {
3647 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
3648 }
3649 }
3650
3651 // Remember the initial centroid for the duration of the gesture.
3652 mPointerGesture.initialCentroidX = 0;
3653 mPointerGesture.initialCentroidY = 0;
3654 for (uint32_t i = 0; i < currentTouchPointerCount; i++) {
3655 const PointerData& touch = mCurrentTouch.pointers[i];
3656 mPointerGesture.initialCentroidX += touch.x;
3657 mPointerGesture.initialCentroidY += touch.y;
3658 }
3659 mPointerGesture.initialCentroidX /= int32_t(currentTouchPointerCount);
3660 mPointerGesture.initialCentroidY /= int32_t(currentTouchPointerCount);
3661
3662 mPointerGesture.activeGestureId = 0;
3663 }
3664 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
3665 // Switch to FREEFORM if additional pointers go down.
3666 if (currentTouchPointerCount > 2) {
3667 *outCancelPreviousGesture = true;
3668 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003669 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003670 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003671
Jeff Brownace13b12011-03-09 17:39:48 -08003672 if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
3673 // SWIPE mode.
3674#if DEBUG_GESTURES
3675 LOGD("Gestures: SWIPE activeTouchId=%d,"
3676 "activeGestureId=%d, currentTouchPointerCount=%d",
3677 activeTouchId, mPointerGesture.activeGestureId, currentTouchPointerCount);
3678#endif
3679 assert(mPointerGesture.activeGestureId >= 0);
3680
3681 float x = (mCurrentTouch.pointers[0].x + mCurrentTouch.pointers[1].x
3682 - mPointerGesture.initialCentroidX * 2) * 0.5f
3683 * mLocked.pointerGestureXMovementScale + mPointerGesture.initialPointerX;
3684 float y = (mCurrentTouch.pointers[0].y + mCurrentTouch.pointers[1].y
3685 - mPointerGesture.initialCentroidY * 2) * 0.5f
3686 * mLocked.pointerGestureYMovementScale + mPointerGesture.initialPointerY;
3687
3688 mPointerGesture.currentGesturePointerCount = 1;
3689 mPointerGesture.currentGestureIdBits.clear();
3690 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3691 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3692 mPointerGesture.currentGestureCoords[0].clear();
3693 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3694 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3695 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3696 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
3697 // FREEFORM mode.
3698#if DEBUG_GESTURES
3699 LOGD("Gestures: FREEFORM activeTouchId=%d,"
3700 "activeGestureId=%d, currentTouchPointerCount=%d",
3701 activeTouchId, mPointerGesture.activeGestureId, currentTouchPointerCount);
3702#endif
3703 assert(mPointerGesture.activeGestureId >= 0);
3704
3705 mPointerGesture.currentGesturePointerCount = currentTouchPointerCount;
3706 mPointerGesture.currentGestureIdBits.clear();
3707
3708 BitSet32 mappedTouchIdBits;
3709 BitSet32 usedGestureIdBits;
3710 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
3711 // Initially, assign the active gesture id to the active touch point
3712 // if there is one. No other touch id bits are mapped yet.
3713 if (!*outCancelPreviousGesture) {
3714 mappedTouchIdBits.markBit(activeTouchId);
3715 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3716 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3717 mPointerGesture.activeGestureId;
3718 } else {
3719 mPointerGesture.activeGestureId = -1;
3720 }
3721 } else {
3722 // Otherwise, assume we mapped all touches from the previous frame.
3723 // Reuse all mappings that are still applicable.
3724 mappedTouchIdBits.value = mLastTouch.idBits.value & mCurrentTouch.idBits.value;
3725 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3726
3727 // Check whether we need to choose a new active gesture id because the
3728 // current went went up.
3729 for (BitSet32 upTouchIdBits(mLastTouch.idBits.value & ~mCurrentTouch.idBits.value);
3730 !upTouchIdBits.isEmpty(); ) {
3731 uint32_t upTouchId = upTouchIdBits.firstMarkedBit();
3732 upTouchIdBits.clearBit(upTouchId);
3733 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3734 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3735 mPointerGesture.activeGestureId = -1;
3736 break;
3737 }
3738 }
3739 }
3740
3741#if DEBUG_GESTURES
3742 LOGD("Gestures: FREEFORM follow up "
3743 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3744 "activeGestureId=%d",
3745 mappedTouchIdBits.value, usedGestureIdBits.value,
3746 mPointerGesture.activeGestureId);
3747#endif
3748
3749 for (uint32_t i = 0; i < currentTouchPointerCount; i++) {
3750 uint32_t touchId = mCurrentTouch.pointers[i].id;
3751 uint32_t gestureId;
3752 if (!mappedTouchIdBits.hasBit(touchId)) {
3753 gestureId = usedGestureIdBits.firstUnmarkedBit();
3754 usedGestureIdBits.markBit(gestureId);
3755 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3756#if DEBUG_GESTURES
3757 LOGD("Gestures: FREEFORM "
3758 "new mapping for touch id %d -> gesture id %d",
3759 touchId, gestureId);
3760#endif
3761 } else {
3762 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3763#if DEBUG_GESTURES
3764 LOGD("Gestures: FREEFORM "
3765 "existing mapping for touch id %d -> gesture id %d",
3766 touchId, gestureId);
3767#endif
3768 }
3769 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3770 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3771
3772 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.initialCentroidX)
3773 * mLocked.pointerGestureXZoomScale + mPointerGesture.initialPointerX;
3774 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.initialCentroidY)
3775 * mLocked.pointerGestureYZoomScale + mPointerGesture.initialPointerY;
3776
3777 mPointerGesture.currentGestureCoords[i].clear();
3778 mPointerGesture.currentGestureCoords[i].setAxisValue(
3779 AMOTION_EVENT_AXIS_X, x);
3780 mPointerGesture.currentGestureCoords[i].setAxisValue(
3781 AMOTION_EVENT_AXIS_Y, y);
3782 mPointerGesture.currentGestureCoords[i].setAxisValue(
3783 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3784 }
3785
3786 if (mPointerGesture.activeGestureId < 0) {
3787 mPointerGesture.activeGestureId =
3788 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3789#if DEBUG_GESTURES
3790 LOGD("Gestures: FREEFORM new "
3791 "activeGestureId=%d", mPointerGesture.activeGestureId);
3792#endif
3793 }
3794 } else {
3795 // INDETERMINATE_MULTITOUCH mode.
3796 // Do nothing.
3797#if DEBUG_GESTURES
3798 LOGD("Gestures: INDETERMINATE_MULTITOUCH");
3799#endif
3800 }
3801 }
3802
3803 // Unfade the pointer if the user is doing anything with the touch pad.
3804 mPointerController->setButtonState(mCurrentTouch.buttonState);
3805 if (mCurrentTouch.buttonState || mCurrentTouch.pointerCount != 0) {
3806 mPointerController->unfade();
3807 }
3808
3809#if DEBUG_GESTURES
3810 LOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3811 "currentGestureMode=%d, currentGesturePointerCount=%d, currentGestureIdBits=0x%08x, "
3812 "lastGestureMode=%d, lastGesturePointerCount=%d, lastGestureIdBits=0x%08x",
3813 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3814 mPointerGesture.currentGestureMode, mPointerGesture.currentGesturePointerCount,
3815 mPointerGesture.currentGestureIdBits.value,
3816 mPointerGesture.lastGestureMode, mPointerGesture.lastGesturePointerCount,
3817 mPointerGesture.lastGestureIdBits.value);
3818 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
3819 uint32_t id = idBits.firstMarkedBit();
3820 idBits.clearBit(id);
3821 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3822 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3823 LOGD(" currentGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
3824 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3825 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3826 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3827 }
3828 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
3829 uint32_t id = idBits.firstMarkedBit();
3830 idBits.clearBit(id);
3831 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3832 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3833 LOGD(" lastGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
3834 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3835 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3836 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3837 }
3838#endif
3839}
3840
3841void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3842 int32_t action, int32_t flags, uint32_t metaState, int32_t edgeFlags,
3843 const PointerCoords* coords, const uint32_t* idToIndex, BitSet32 idBits,
3844 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
3845 PointerCoords pointerCoords[MAX_POINTERS];
3846 int32_t pointerIds[MAX_POINTERS];
3847 uint32_t pointerCount = 0;
3848 while (!idBits.isEmpty()) {
3849 uint32_t id = idBits.firstMarkedBit();
3850 idBits.clearBit(id);
3851 uint32_t index = idToIndex[id];
3852 pointerIds[pointerCount] = id;
3853 pointerCoords[pointerCount].copyFrom(coords[index]);
3854
3855 if (changedId >= 0 && id == uint32_t(changedId)) {
3856 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3857 }
3858
3859 pointerCount += 1;
3860 }
3861
3862 assert(pointerCount != 0);
3863
3864 if (changedId >= 0 && pointerCount == 1) {
3865 // Replace initial down and final up action.
3866 // We can compare the action without masking off the changed pointer index
3867 // because we know the index is 0.
3868 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3869 action = AMOTION_EVENT_ACTION_DOWN;
3870 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
3871 action = AMOTION_EVENT_ACTION_UP;
3872 } else {
3873 // Can't happen.
3874 assert(false);
3875 }
3876 }
3877
3878 getDispatcher()->notifyMotion(when, getDeviceId(), source, policyFlags,
3879 action, flags, metaState, edgeFlags,
3880 pointerCount, pointerIds, pointerCoords, xPrecision, yPrecision, downTime);
3881}
3882
3883bool TouchInputMapper::updateMovedPointerCoords(
3884 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
3885 PointerCoords* outCoords, const uint32_t* outIdToIndex, BitSet32 idBits) const {
3886 bool changed = false;
3887 while (!idBits.isEmpty()) {
3888 uint32_t id = idBits.firstMarkedBit();
3889 idBits.clearBit(id);
3890
3891 uint32_t inIndex = inIdToIndex[id];
3892 uint32_t outIndex = outIdToIndex[id];
3893 const PointerCoords& curInCoords = inCoords[inIndex];
3894 PointerCoords& curOutCoords = outCoords[outIndex];
3895
3896 if (curInCoords != curOutCoords) {
3897 curOutCoords.copyFrom(curInCoords);
3898 changed = true;
3899 }
3900 }
3901 return changed;
3902}
3903
3904void TouchInputMapper::fadePointer() {
3905 { // acquire lock
3906 AutoMutex _l(mLock);
3907 if (mPointerController != NULL) {
3908 mPointerController->fade();
3909 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003910 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003911}
3912
Jeff Brown6328cdc2010-07-29 18:18:33 -07003913bool TouchInputMapper::isPointInsideSurfaceLocked(int32_t x, int32_t y) {
Jeff Brown9626b142011-03-03 02:09:54 -08003914 return x >= mRawAxes.x.minValue && x <= mRawAxes.x.maxValue
3915 && y >= mRawAxes.y.minValue && y <= mRawAxes.y.maxValue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07003916}
3917
Jeff Brown6328cdc2010-07-29 18:18:33 -07003918const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHitLocked(
3919 int32_t x, int32_t y) {
3920 size_t numVirtualKeys = mLocked.virtualKeys.size();
3921 for (size_t i = 0; i < numVirtualKeys; i++) {
3922 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07003923
3924#if DEBUG_VIRTUAL_KEYS
3925 LOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3926 "left=%d, top=%d, right=%d, bottom=%d",
3927 x, y,
3928 virtualKey.keyCode, virtualKey.scanCode,
3929 virtualKey.hitLeft, virtualKey.hitTop,
3930 virtualKey.hitRight, virtualKey.hitBottom);
3931#endif
3932
3933 if (virtualKey.isHit(x, y)) {
3934 return & virtualKey;
3935 }
3936 }
3937
3938 return NULL;
3939}
3940
3941void TouchInputMapper::calculatePointerIds() {
3942 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
3943 uint32_t lastPointerCount = mLastTouch.pointerCount;
3944
3945 if (currentPointerCount == 0) {
3946 // No pointers to assign.
3947 mCurrentTouch.idBits.clear();
3948 } else if (lastPointerCount == 0) {
3949 // All pointers are new.
3950 mCurrentTouch.idBits.clear();
3951 for (uint32_t i = 0; i < currentPointerCount; i++) {
3952 mCurrentTouch.pointers[i].id = i;
3953 mCurrentTouch.idToIndex[i] = i;
3954 mCurrentTouch.idBits.markBit(i);
3955 }
3956 } else if (currentPointerCount == 1 && lastPointerCount == 1) {
3957 // Only one pointer and no change in count so it must have the same id as before.
3958 uint32_t id = mLastTouch.pointers[0].id;
3959 mCurrentTouch.pointers[0].id = id;
3960 mCurrentTouch.idToIndex[id] = 0;
3961 mCurrentTouch.idBits.value = BitSet32::valueForBit(id);
3962 } else {
3963 // General case.
3964 // We build a heap of squared euclidean distances between current and last pointers
3965 // associated with the current and last pointer indices. Then, we find the best
3966 // match (by distance) for each current pointer.
3967 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3968
3969 uint32_t heapSize = 0;
3970 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3971 currentPointerIndex++) {
3972 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3973 lastPointerIndex++) {
3974 int64_t deltaX = mCurrentTouch.pointers[currentPointerIndex].x
3975 - mLastTouch.pointers[lastPointerIndex].x;
3976 int64_t deltaY = mCurrentTouch.pointers[currentPointerIndex].y
3977 - mLastTouch.pointers[lastPointerIndex].y;
3978
3979 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3980
3981 // Insert new element into the heap (sift up).
3982 heap[heapSize].currentPointerIndex = currentPointerIndex;
3983 heap[heapSize].lastPointerIndex = lastPointerIndex;
3984 heap[heapSize].distance = distance;
3985 heapSize += 1;
3986 }
3987 }
3988
3989 // Heapify
3990 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
3991 startIndex -= 1;
3992 for (uint32_t parentIndex = startIndex; ;) {
3993 uint32_t childIndex = parentIndex * 2 + 1;
3994 if (childIndex >= heapSize) {
3995 break;
3996 }
3997
3998 if (childIndex + 1 < heapSize
3999 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4000 childIndex += 1;
4001 }
4002
4003 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4004 break;
4005 }
4006
4007 swap(heap[parentIndex], heap[childIndex]);
4008 parentIndex = childIndex;
4009 }
4010 }
4011
4012#if DEBUG_POINTER_ASSIGNMENT
4013 LOGD("calculatePointerIds - initial distance min-heap: size=%d", heapSize);
4014 for (size_t i = 0; i < heapSize; i++) {
4015 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4016 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4017 heap[i].distance);
4018 }
4019#endif
4020
4021 // Pull matches out by increasing order of distance.
4022 // To avoid reassigning pointers that have already been matched, the loop keeps track
4023 // of which last and current pointers have been matched using the matchedXXXBits variables.
4024 // It also tracks the used pointer id bits.
4025 BitSet32 matchedLastBits(0);
4026 BitSet32 matchedCurrentBits(0);
4027 BitSet32 usedIdBits(0);
4028 bool first = true;
4029 for (uint32_t i = min(currentPointerCount, lastPointerCount); i > 0; i--) {
4030 for (;;) {
4031 if (first) {
4032 // The first time through the loop, we just consume the root element of
4033 // the heap (the one with smallest distance).
4034 first = false;
4035 } else {
4036 // Previous iterations consumed the root element of the heap.
4037 // Pop root element off of the heap (sift down).
4038 heapSize -= 1;
4039 assert(heapSize > 0);
4040
4041 // Sift down.
4042 heap[0] = heap[heapSize];
4043 for (uint32_t parentIndex = 0; ;) {
4044 uint32_t childIndex = parentIndex * 2 + 1;
4045 if (childIndex >= heapSize) {
4046 break;
4047 }
4048
4049 if (childIndex + 1 < heapSize
4050 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4051 childIndex += 1;
4052 }
4053
4054 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4055 break;
4056 }
4057
4058 swap(heap[parentIndex], heap[childIndex]);
4059 parentIndex = childIndex;
4060 }
4061
4062#if DEBUG_POINTER_ASSIGNMENT
4063 LOGD("calculatePointerIds - reduced distance min-heap: size=%d", heapSize);
4064 for (size_t i = 0; i < heapSize; i++) {
4065 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4066 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4067 heap[i].distance);
4068 }
4069#endif
4070 }
4071
4072 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4073 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4074
4075 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4076 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4077
4078 matchedCurrentBits.markBit(currentPointerIndex);
4079 matchedLastBits.markBit(lastPointerIndex);
4080
4081 uint32_t id = mLastTouch.pointers[lastPointerIndex].id;
4082 mCurrentTouch.pointers[currentPointerIndex].id = id;
4083 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4084 usedIdBits.markBit(id);
4085
4086#if DEBUG_POINTER_ASSIGNMENT
4087 LOGD("calculatePointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
4088 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
4089#endif
4090 break;
4091 }
4092 }
4093
4094 // Assign fresh ids to new pointers.
4095 if (currentPointerCount > lastPointerCount) {
4096 for (uint32_t i = currentPointerCount - lastPointerCount; ;) {
4097 uint32_t currentPointerIndex = matchedCurrentBits.firstUnmarkedBit();
4098 uint32_t id = usedIdBits.firstUnmarkedBit();
4099
4100 mCurrentTouch.pointers[currentPointerIndex].id = id;
4101 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4102 usedIdBits.markBit(id);
4103
4104#if DEBUG_POINTER_ASSIGNMENT
4105 LOGD("calculatePointerIds - assigned: cur=%d, id=%d",
4106 currentPointerIndex, id);
4107#endif
4108
4109 if (--i == 0) break; // done
4110 matchedCurrentBits.markBit(currentPointerIndex);
4111 }
4112 }
4113
4114 // Fix id bits.
4115 mCurrentTouch.idBits = usedIdBits;
4116 }
4117}
4118
4119/* Special hack for devices that have bad screen data: if one of the
4120 * points has moved more than a screen height from the last position,
4121 * then drop it. */
4122bool TouchInputMapper::applyBadTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004123 uint32_t pointerCount = mCurrentTouch.pointerCount;
4124
4125 // Nothing to do if there are no points.
4126 if (pointerCount == 0) {
4127 return false;
4128 }
4129
4130 // Don't do anything if a finger is going down or up. We run
4131 // here before assigning pointer IDs, so there isn't a good
4132 // way to do per-finger matching.
4133 if (pointerCount != mLastTouch.pointerCount) {
4134 return false;
4135 }
4136
4137 // We consider a single movement across more than a 7/16 of
4138 // the long size of the screen to be bad. This was a magic value
4139 // determined by looking at the maximum distance it is feasible
4140 // to actually move in one sample.
Jeff Brown9626b142011-03-03 02:09:54 -08004141 int32_t maxDeltaY = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) * 7 / 16;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004142
4143 // XXX The original code in InputDevice.java included commented out
4144 // code for testing the X axis. Note that when we drop a point
4145 // we don't actually restore the old X either. Strange.
4146 // The old code also tries to track when bad points were previously
4147 // detected but it turns out that due to the placement of a "break"
4148 // at the end of the loop, we never set mDroppedBadPoint to true
4149 // so it is effectively dead code.
4150 // Need to figure out if the old code is busted or just overcomplicated
4151 // but working as intended.
4152
4153 // Look through all new points and see if any are farther than
4154 // acceptable from all previous points.
4155 for (uint32_t i = pointerCount; i-- > 0; ) {
4156 int32_t y = mCurrentTouch.pointers[i].y;
4157 int32_t closestY = INT_MAX;
4158 int32_t closestDeltaY = 0;
4159
4160#if DEBUG_HACKS
4161 LOGD("BadTouchFilter: Looking at next point #%d: y=%d", i, y);
4162#endif
4163
4164 for (uint32_t j = pointerCount; j-- > 0; ) {
4165 int32_t lastY = mLastTouch.pointers[j].y;
4166 int32_t deltaY = abs(y - lastY);
4167
4168#if DEBUG_HACKS
4169 LOGD("BadTouchFilter: Comparing with last point #%d: y=%d deltaY=%d",
4170 j, lastY, deltaY);
4171#endif
4172
4173 if (deltaY < maxDeltaY) {
4174 goto SkipSufficientlyClosePoint;
4175 }
4176 if (deltaY < closestDeltaY) {
4177 closestDeltaY = deltaY;
4178 closestY = lastY;
4179 }
4180 }
4181
4182 // Must not have found a close enough match.
4183#if DEBUG_HACKS
4184 LOGD("BadTouchFilter: Dropping bad point #%d: newY=%d oldY=%d deltaY=%d maxDeltaY=%d",
4185 i, y, closestY, closestDeltaY, maxDeltaY);
4186#endif
4187
4188 mCurrentTouch.pointers[i].y = closestY;
4189 return true; // XXX original code only corrects one point
4190
4191 SkipSufficientlyClosePoint: ;
4192 }
4193
4194 // No change.
4195 return false;
4196}
4197
4198/* Special hack for devices that have bad screen data: drop points where
4199 * the coordinate value for one axis has jumped to the other pointer's location.
4200 */
4201bool TouchInputMapper::applyJumpyTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004202 uint32_t pointerCount = mCurrentTouch.pointerCount;
4203 if (mLastTouch.pointerCount != pointerCount) {
4204#if DEBUG_HACKS
4205 LOGD("JumpyTouchFilter: Different pointer count %d -> %d",
4206 mLastTouch.pointerCount, pointerCount);
4207 for (uint32_t i = 0; i < pointerCount; i++) {
4208 LOGD(" Pointer %d (%d, %d)", i,
4209 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4210 }
4211#endif
4212
4213 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_TRANSITION_DROPS) {
4214 if (mLastTouch.pointerCount == 1 && pointerCount == 2) {
4215 // Just drop the first few events going from 1 to 2 pointers.
4216 // They're bad often enough that they're not worth considering.
4217 mCurrentTouch.pointerCount = 1;
4218 mJumpyTouchFilter.jumpyPointsDropped += 1;
4219
4220#if DEBUG_HACKS
4221 LOGD("JumpyTouchFilter: Pointer 2 dropped");
4222#endif
4223 return true;
4224 } else if (mLastTouch.pointerCount == 2 && pointerCount == 1) {
4225 // The event when we go from 2 -> 1 tends to be messed up too
4226 mCurrentTouch.pointerCount = 2;
4227 mCurrentTouch.pointers[0] = mLastTouch.pointers[0];
4228 mCurrentTouch.pointers[1] = mLastTouch.pointers[1];
4229 mJumpyTouchFilter.jumpyPointsDropped += 1;
4230
4231#if DEBUG_HACKS
4232 for (int32_t i = 0; i < 2; i++) {
4233 LOGD("JumpyTouchFilter: Pointer %d replaced (%d, %d)", i,
4234 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4235 }
4236#endif
4237 return true;
4238 }
4239 }
4240 // Reset jumpy points dropped on other transitions or if limit exceeded.
4241 mJumpyTouchFilter.jumpyPointsDropped = 0;
4242
4243#if DEBUG_HACKS
4244 LOGD("JumpyTouchFilter: Transition - drop limit reset");
4245#endif
4246 return false;
4247 }
4248
4249 // We have the same number of pointers as last time.
4250 // A 'jumpy' point is one where the coordinate value for one axis
4251 // has jumped to the other pointer's location. No need to do anything
4252 // else if we only have one pointer.
4253 if (pointerCount < 2) {
4254 return false;
4255 }
4256
4257 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_DROP_LIMIT) {
Jeff Brown9626b142011-03-03 02:09:54 -08004258 int jumpyEpsilon = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) / JUMPY_EPSILON_DIVISOR;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004259
4260 // We only replace the single worst jumpy point as characterized by pointer distance
4261 // in a single axis.
4262 int32_t badPointerIndex = -1;
4263 int32_t badPointerReplacementIndex = -1;
4264 int32_t badPointerDistance = INT_MIN; // distance to be corrected
4265
4266 for (uint32_t i = pointerCount; i-- > 0; ) {
4267 int32_t x = mCurrentTouch.pointers[i].x;
4268 int32_t y = mCurrentTouch.pointers[i].y;
4269
4270#if DEBUG_HACKS
4271 LOGD("JumpyTouchFilter: Point %d (%d, %d)", i, x, y);
4272#endif
4273
4274 // Check if a touch point is too close to another's coordinates
4275 bool dropX = false, dropY = false;
4276 for (uint32_t j = 0; j < pointerCount; j++) {
4277 if (i == j) {
4278 continue;
4279 }
4280
4281 if (abs(x - mCurrentTouch.pointers[j].x) <= jumpyEpsilon) {
4282 dropX = true;
4283 break;
4284 }
4285
4286 if (abs(y - mCurrentTouch.pointers[j].y) <= jumpyEpsilon) {
4287 dropY = true;
4288 break;
4289 }
4290 }
4291 if (! dropX && ! dropY) {
4292 continue; // not jumpy
4293 }
4294
4295 // Find a replacement candidate by comparing with older points on the
4296 // complementary (non-jumpy) axis.
4297 int32_t distance = INT_MIN; // distance to be corrected
4298 int32_t replacementIndex = -1;
4299
4300 if (dropX) {
4301 // X looks too close. Find an older replacement point with a close Y.
4302 int32_t smallestDeltaY = INT_MAX;
4303 for (uint32_t j = 0; j < pointerCount; j++) {
4304 int32_t deltaY = abs(y - mLastTouch.pointers[j].y);
4305 if (deltaY < smallestDeltaY) {
4306 smallestDeltaY = deltaY;
4307 replacementIndex = j;
4308 }
4309 }
4310 distance = abs(x - mLastTouch.pointers[replacementIndex].x);
4311 } else {
4312 // Y looks too close. Find an older replacement point with a close X.
4313 int32_t smallestDeltaX = INT_MAX;
4314 for (uint32_t j = 0; j < pointerCount; j++) {
4315 int32_t deltaX = abs(x - mLastTouch.pointers[j].x);
4316 if (deltaX < smallestDeltaX) {
4317 smallestDeltaX = deltaX;
4318 replacementIndex = j;
4319 }
4320 }
4321 distance = abs(y - mLastTouch.pointers[replacementIndex].y);
4322 }
4323
4324 // If replacing this pointer would correct a worse error than the previous ones
4325 // considered, then use this replacement instead.
4326 if (distance > badPointerDistance) {
4327 badPointerIndex = i;
4328 badPointerReplacementIndex = replacementIndex;
4329 badPointerDistance = distance;
4330 }
4331 }
4332
4333 // Correct the jumpy pointer if one was found.
4334 if (badPointerIndex >= 0) {
4335#if DEBUG_HACKS
4336 LOGD("JumpyTouchFilter: Replacing bad pointer %d with (%d, %d)",
4337 badPointerIndex,
4338 mLastTouch.pointers[badPointerReplacementIndex].x,
4339 mLastTouch.pointers[badPointerReplacementIndex].y);
4340#endif
4341
4342 mCurrentTouch.pointers[badPointerIndex].x =
4343 mLastTouch.pointers[badPointerReplacementIndex].x;
4344 mCurrentTouch.pointers[badPointerIndex].y =
4345 mLastTouch.pointers[badPointerReplacementIndex].y;
4346 mJumpyTouchFilter.jumpyPointsDropped += 1;
4347 return true;
4348 }
4349 }
4350
4351 mJumpyTouchFilter.jumpyPointsDropped = 0;
4352 return false;
4353}
4354
4355/* Special hack for devices that have bad screen data: aggregate and
4356 * compute averages of the coordinate data, to reduce the amount of
4357 * jitter seen by applications. */
4358void TouchInputMapper::applyAveragingTouchFilter() {
4359 for (uint32_t currentIndex = 0; currentIndex < mCurrentTouch.pointerCount; currentIndex++) {
4360 uint32_t id = mCurrentTouch.pointers[currentIndex].id;
4361 int32_t x = mCurrentTouch.pointers[currentIndex].x;
4362 int32_t y = mCurrentTouch.pointers[currentIndex].y;
Jeff Brown8d608662010-08-30 03:02:23 -07004363 int32_t pressure;
4364 switch (mCalibration.pressureSource) {
4365 case Calibration::PRESSURE_SOURCE_PRESSURE:
4366 pressure = mCurrentTouch.pointers[currentIndex].pressure;
4367 break;
4368 case Calibration::PRESSURE_SOURCE_TOUCH:
4369 pressure = mCurrentTouch.pointers[currentIndex].touchMajor;
4370 break;
4371 default:
4372 pressure = 1;
4373 break;
4374 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004375
4376 if (mLastTouch.idBits.hasBit(id)) {
4377 // Pointer was down before and is still down now.
4378 // Compute average over history trace.
4379 uint32_t start = mAveragingTouchFilter.historyStart[id];
4380 uint32_t end = mAveragingTouchFilter.historyEnd[id];
4381
4382 int64_t deltaX = x - mAveragingTouchFilter.historyData[end].pointers[id].x;
4383 int64_t deltaY = y - mAveragingTouchFilter.historyData[end].pointers[id].y;
4384 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4385
4386#if DEBUG_HACKS
4387 LOGD("AveragingTouchFilter: Pointer id %d - Distance from last sample: %lld",
4388 id, distance);
4389#endif
4390
4391 if (distance < AVERAGING_DISTANCE_LIMIT) {
4392 // Increment end index in preparation for recording new historical data.
4393 end += 1;
4394 if (end > AVERAGING_HISTORY_SIZE) {
4395 end = 0;
4396 }
4397
4398 // If the end index has looped back to the start index then we have filled
4399 // the historical trace up to the desired size so we drop the historical
4400 // data at the start of the trace.
4401 if (end == start) {
4402 start += 1;
4403 if (start > AVERAGING_HISTORY_SIZE) {
4404 start = 0;
4405 }
4406 }
4407
4408 // Add the raw data to the historical trace.
4409 mAveragingTouchFilter.historyStart[id] = start;
4410 mAveragingTouchFilter.historyEnd[id] = end;
4411 mAveragingTouchFilter.historyData[end].pointers[id].x = x;
4412 mAveragingTouchFilter.historyData[end].pointers[id].y = y;
4413 mAveragingTouchFilter.historyData[end].pointers[id].pressure = pressure;
4414
4415 // Average over all historical positions in the trace by total pressure.
4416 int32_t averagedX = 0;
4417 int32_t averagedY = 0;
4418 int32_t totalPressure = 0;
4419 for (;;) {
4420 int32_t historicalX = mAveragingTouchFilter.historyData[start].pointers[id].x;
4421 int32_t historicalY = mAveragingTouchFilter.historyData[start].pointers[id].y;
4422 int32_t historicalPressure = mAveragingTouchFilter.historyData[start]
4423 .pointers[id].pressure;
4424
4425 averagedX += historicalX * historicalPressure;
4426 averagedY += historicalY * historicalPressure;
4427 totalPressure += historicalPressure;
4428
4429 if (start == end) {
4430 break;
4431 }
4432
4433 start += 1;
4434 if (start > AVERAGING_HISTORY_SIZE) {
4435 start = 0;
4436 }
4437 }
4438
Jeff Brown8d608662010-08-30 03:02:23 -07004439 if (totalPressure != 0) {
4440 averagedX /= totalPressure;
4441 averagedY /= totalPressure;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004442
4443#if DEBUG_HACKS
Jeff Brown8d608662010-08-30 03:02:23 -07004444 LOGD("AveragingTouchFilter: Pointer id %d - "
4445 "totalPressure=%d, averagedX=%d, averagedY=%d", id, totalPressure,
4446 averagedX, averagedY);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004447#endif
4448
Jeff Brown8d608662010-08-30 03:02:23 -07004449 mCurrentTouch.pointers[currentIndex].x = averagedX;
4450 mCurrentTouch.pointers[currentIndex].y = averagedY;
4451 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004452 } else {
4453#if DEBUG_HACKS
4454 LOGD("AveragingTouchFilter: Pointer id %d - Exceeded max distance", id);
4455#endif
4456 }
4457 } else {
4458#if DEBUG_HACKS
4459 LOGD("AveragingTouchFilter: Pointer id %d - Pointer went up", id);
4460#endif
4461 }
4462
4463 // Reset pointer history.
4464 mAveragingTouchFilter.historyStart[id] = 0;
4465 mAveragingTouchFilter.historyEnd[id] = 0;
4466 mAveragingTouchFilter.historyData[0].pointers[id].x = x;
4467 mAveragingTouchFilter.historyData[0].pointers[id].y = y;
4468 mAveragingTouchFilter.historyData[0].pointers[id].pressure = pressure;
4469 }
4470}
4471
4472int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004473 { // acquire lock
4474 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004475
Jeff Brown6328cdc2010-07-29 18:18:33 -07004476 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.keyCode == keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004477 return AKEY_STATE_VIRTUAL;
4478 }
4479
Jeff Brown6328cdc2010-07-29 18:18:33 -07004480 size_t numVirtualKeys = mLocked.virtualKeys.size();
4481 for (size_t i = 0; i < numVirtualKeys; i++) {
4482 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004483 if (virtualKey.keyCode == keyCode) {
4484 return AKEY_STATE_UP;
4485 }
4486 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004487 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004488
4489 return AKEY_STATE_UNKNOWN;
4490}
4491
4492int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004493 { // acquire lock
4494 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004495
Jeff Brown6328cdc2010-07-29 18:18:33 -07004496 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004497 return AKEY_STATE_VIRTUAL;
4498 }
4499
Jeff Brown6328cdc2010-07-29 18:18:33 -07004500 size_t numVirtualKeys = mLocked.virtualKeys.size();
4501 for (size_t i = 0; i < numVirtualKeys; i++) {
4502 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004503 if (virtualKey.scanCode == scanCode) {
4504 return AKEY_STATE_UP;
4505 }
4506 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004507 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004508
4509 return AKEY_STATE_UNKNOWN;
4510}
4511
4512bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4513 const int32_t* keyCodes, uint8_t* outFlags) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004514 { // acquire lock
4515 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004516
Jeff Brown6328cdc2010-07-29 18:18:33 -07004517 size_t numVirtualKeys = mLocked.virtualKeys.size();
4518 for (size_t i = 0; i < numVirtualKeys; i++) {
4519 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004520
4521 for (size_t i = 0; i < numCodes; i++) {
4522 if (virtualKey.keyCode == keyCodes[i]) {
4523 outFlags[i] = 1;
4524 }
4525 }
4526 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004527 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004528
4529 return true;
4530}
4531
4532
4533// --- SingleTouchInputMapper ---
4534
Jeff Brown47e6b1b2010-11-29 17:37:49 -08004535SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
4536 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004537 initialize();
4538}
4539
4540SingleTouchInputMapper::~SingleTouchInputMapper() {
4541}
4542
4543void SingleTouchInputMapper::initialize() {
4544 mAccumulator.clear();
4545
4546 mDown = false;
4547 mX = 0;
4548 mY = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07004549 mPressure = 0; // default to 0 for devices that don't report pressure
4550 mToolWidth = 0; // default to 0 for devices that don't report tool width
Jeff Brownace13b12011-03-09 17:39:48 -08004551 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004552}
4553
4554void SingleTouchInputMapper::reset() {
4555 TouchInputMapper::reset();
4556
Jeff Brown6d0fec22010-07-23 21:28:06 -07004557 initialize();
4558 }
4559
4560void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
4561 switch (rawEvent->type) {
4562 case EV_KEY:
4563 switch (rawEvent->scanCode) {
4564 case BTN_TOUCH:
4565 mAccumulator.fields |= Accumulator::FIELD_BTN_TOUCH;
4566 mAccumulator.btnTouch = rawEvent->value != 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004567 // Don't sync immediately. Wait until the next SYN_REPORT since we might
4568 // not have received valid position information yet. This logic assumes that
4569 // BTN_TOUCH is always followed by SYN_REPORT as part of a complete packet.
Jeff Brown6d0fec22010-07-23 21:28:06 -07004570 break;
Jeff Brownace13b12011-03-09 17:39:48 -08004571 default:
4572 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
4573 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
4574 if (buttonState) {
4575 if (rawEvent->value) {
4576 mAccumulator.buttonDown |= buttonState;
4577 } else {
4578 mAccumulator.buttonUp |= buttonState;
4579 }
4580 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
4581 }
4582 }
4583 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004584 }
4585 break;
4586
4587 case EV_ABS:
4588 switch (rawEvent->scanCode) {
4589 case ABS_X:
4590 mAccumulator.fields |= Accumulator::FIELD_ABS_X;
4591 mAccumulator.absX = rawEvent->value;
4592 break;
4593 case ABS_Y:
4594 mAccumulator.fields |= Accumulator::FIELD_ABS_Y;
4595 mAccumulator.absY = rawEvent->value;
4596 break;
4597 case ABS_PRESSURE:
4598 mAccumulator.fields |= Accumulator::FIELD_ABS_PRESSURE;
4599 mAccumulator.absPressure = rawEvent->value;
4600 break;
4601 case ABS_TOOL_WIDTH:
4602 mAccumulator.fields |= Accumulator::FIELD_ABS_TOOL_WIDTH;
4603 mAccumulator.absToolWidth = rawEvent->value;
4604 break;
4605 }
4606 break;
4607
4608 case EV_SYN:
4609 switch (rawEvent->scanCode) {
4610 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004611 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004612 break;
4613 }
4614 break;
4615 }
4616}
4617
4618void SingleTouchInputMapper::sync(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004619 uint32_t fields = mAccumulator.fields;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004620 if (fields == 0) {
4621 return; // no new state changes, so nothing to do
4622 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004623
4624 if (fields & Accumulator::FIELD_BTN_TOUCH) {
4625 mDown = mAccumulator.btnTouch;
4626 }
4627
4628 if (fields & Accumulator::FIELD_ABS_X) {
4629 mX = mAccumulator.absX;
4630 }
4631
4632 if (fields & Accumulator::FIELD_ABS_Y) {
4633 mY = mAccumulator.absY;
4634 }
4635
4636 if (fields & Accumulator::FIELD_ABS_PRESSURE) {
4637 mPressure = mAccumulator.absPressure;
4638 }
4639
4640 if (fields & Accumulator::FIELD_ABS_TOOL_WIDTH) {
Jeff Brown8d608662010-08-30 03:02:23 -07004641 mToolWidth = mAccumulator.absToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004642 }
4643
Jeff Brownace13b12011-03-09 17:39:48 -08004644 if (fields & Accumulator::FIELD_BUTTONS) {
4645 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
4646 }
4647
Jeff Brown6d0fec22010-07-23 21:28:06 -07004648 mCurrentTouch.clear();
4649
4650 if (mDown) {
4651 mCurrentTouch.pointerCount = 1;
4652 mCurrentTouch.pointers[0].id = 0;
4653 mCurrentTouch.pointers[0].x = mX;
4654 mCurrentTouch.pointers[0].y = mY;
4655 mCurrentTouch.pointers[0].pressure = mPressure;
Jeff Brown8d608662010-08-30 03:02:23 -07004656 mCurrentTouch.pointers[0].touchMajor = 0;
4657 mCurrentTouch.pointers[0].touchMinor = 0;
4658 mCurrentTouch.pointers[0].toolMajor = mToolWidth;
4659 mCurrentTouch.pointers[0].toolMinor = mToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004660 mCurrentTouch.pointers[0].orientation = 0;
4661 mCurrentTouch.idToIndex[0] = 0;
4662 mCurrentTouch.idBits.markBit(0);
Jeff Brownace13b12011-03-09 17:39:48 -08004663 mCurrentTouch.buttonState = mButtonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004664 }
4665
4666 syncTouch(when, true);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004667
4668 mAccumulator.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07004669}
4670
Jeff Brown8d608662010-08-30 03:02:23 -07004671void SingleTouchInputMapper::configureRawAxes() {
4672 TouchInputMapper::configureRawAxes();
Jeff Brown6d0fec22010-07-23 21:28:06 -07004673
Jeff Brown8d608662010-08-30 03:02:23 -07004674 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_X, & mRawAxes.x);
4675 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_Y, & mRawAxes.y);
4676 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_PRESSURE, & mRawAxes.pressure);
4677 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_TOOL_WIDTH, & mRawAxes.toolMajor);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004678}
4679
4680
4681// --- MultiTouchInputMapper ---
4682
Jeff Brown47e6b1b2010-11-29 17:37:49 -08004683MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
4684 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004685 initialize();
4686}
4687
4688MultiTouchInputMapper::~MultiTouchInputMapper() {
4689}
4690
4691void MultiTouchInputMapper::initialize() {
4692 mAccumulator.clear();
Jeff Brownace13b12011-03-09 17:39:48 -08004693 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004694}
4695
4696void MultiTouchInputMapper::reset() {
4697 TouchInputMapper::reset();
4698
Jeff Brown6d0fec22010-07-23 21:28:06 -07004699 initialize();
4700}
4701
4702void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
4703 switch (rawEvent->type) {
Jeff Brownace13b12011-03-09 17:39:48 -08004704 case EV_KEY: {
4705 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
4706 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
4707 if (buttonState) {
4708 if (rawEvent->value) {
4709 mAccumulator.buttonDown |= buttonState;
4710 } else {
4711 mAccumulator.buttonUp |= buttonState;
4712 }
4713 }
4714 }
4715 break;
4716 }
4717
Jeff Brown6d0fec22010-07-23 21:28:06 -07004718 case EV_ABS: {
4719 uint32_t pointerIndex = mAccumulator.pointerCount;
4720 Accumulator::Pointer* pointer = & mAccumulator.pointers[pointerIndex];
4721
4722 switch (rawEvent->scanCode) {
4723 case ABS_MT_POSITION_X:
4724 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_X;
4725 pointer->absMTPositionX = rawEvent->value;
4726 break;
4727 case ABS_MT_POSITION_Y:
4728 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_Y;
4729 pointer->absMTPositionY = rawEvent->value;
4730 break;
4731 case ABS_MT_TOUCH_MAJOR:
4732 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MAJOR;
4733 pointer->absMTTouchMajor = rawEvent->value;
4734 break;
4735 case ABS_MT_TOUCH_MINOR:
4736 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MINOR;
4737 pointer->absMTTouchMinor = rawEvent->value;
4738 break;
4739 case ABS_MT_WIDTH_MAJOR:
4740 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MAJOR;
4741 pointer->absMTWidthMajor = rawEvent->value;
4742 break;
4743 case ABS_MT_WIDTH_MINOR:
4744 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MINOR;
4745 pointer->absMTWidthMinor = rawEvent->value;
4746 break;
4747 case ABS_MT_ORIENTATION:
4748 pointer->fields |= Accumulator::FIELD_ABS_MT_ORIENTATION;
4749 pointer->absMTOrientation = rawEvent->value;
4750 break;
4751 case ABS_MT_TRACKING_ID:
4752 pointer->fields |= Accumulator::FIELD_ABS_MT_TRACKING_ID;
4753 pointer->absMTTrackingId = rawEvent->value;
4754 break;
Jeff Brown8d608662010-08-30 03:02:23 -07004755 case ABS_MT_PRESSURE:
4756 pointer->fields |= Accumulator::FIELD_ABS_MT_PRESSURE;
4757 pointer->absMTPressure = rawEvent->value;
4758 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004759 }
4760 break;
4761 }
4762
4763 case EV_SYN:
4764 switch (rawEvent->scanCode) {
4765 case SYN_MT_REPORT: {
4766 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
4767 uint32_t pointerIndex = mAccumulator.pointerCount;
4768
4769 if (mAccumulator.pointers[pointerIndex].fields) {
4770 if (pointerIndex == MAX_POINTERS) {
4771 LOGW("MultiTouch device driver returned more than maximum of %d pointers.",
4772 MAX_POINTERS);
4773 } else {
4774 pointerIndex += 1;
4775 mAccumulator.pointerCount = pointerIndex;
4776 }
4777 }
4778
4779 mAccumulator.pointers[pointerIndex].clear();
4780 break;
4781 }
4782
4783 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004784 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004785 break;
4786 }
4787 break;
4788 }
4789}
4790
4791void MultiTouchInputMapper::sync(nsecs_t when) {
4792 static const uint32_t REQUIRED_FIELDS =
Jeff Brown8d608662010-08-30 03:02:23 -07004793 Accumulator::FIELD_ABS_MT_POSITION_X | Accumulator::FIELD_ABS_MT_POSITION_Y;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004794
Jeff Brown6d0fec22010-07-23 21:28:06 -07004795 uint32_t inCount = mAccumulator.pointerCount;
4796 uint32_t outCount = 0;
4797 bool havePointerIds = true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004798
Jeff Brown6d0fec22010-07-23 21:28:06 -07004799 mCurrentTouch.clear();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004800
Jeff Brown6d0fec22010-07-23 21:28:06 -07004801 for (uint32_t inIndex = 0; inIndex < inCount; inIndex++) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004802 const Accumulator::Pointer& inPointer = mAccumulator.pointers[inIndex];
4803 uint32_t fields = inPointer.fields;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004804
Jeff Brown6d0fec22010-07-23 21:28:06 -07004805 if ((fields & REQUIRED_FIELDS) != REQUIRED_FIELDS) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004806 // Some drivers send empty MT sync packets without X / Y to indicate a pointer up.
4807 // Drop this finger.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004808 continue;
4809 }
4810
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004811 PointerData& outPointer = mCurrentTouch.pointers[outCount];
4812 outPointer.x = inPointer.absMTPositionX;
4813 outPointer.y = inPointer.absMTPositionY;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004814
Jeff Brown8d608662010-08-30 03:02:23 -07004815 if (fields & Accumulator::FIELD_ABS_MT_PRESSURE) {
4816 if (inPointer.absMTPressure <= 0) {
Jeff Brownc3db8582010-10-20 15:33:38 -07004817 // Some devices send sync packets with X / Y but with a 0 pressure to indicate
4818 // a pointer going up. Drop this finger.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004819 continue;
4820 }
Jeff Brown8d608662010-08-30 03:02:23 -07004821 outPointer.pressure = inPointer.absMTPressure;
4822 } else {
4823 // Default pressure to 0 if absent.
4824 outPointer.pressure = 0;
4825 }
4826
4827 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MAJOR) {
4828 if (inPointer.absMTTouchMajor <= 0) {
4829 // Some devices send sync packets with X / Y but with a 0 touch major to indicate
4830 // a pointer going up. Drop this finger.
4831 continue;
4832 }
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004833 outPointer.touchMajor = inPointer.absMTTouchMajor;
4834 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004835 // Default touch area to 0 if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004836 outPointer.touchMajor = 0;
4837 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004838
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004839 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MINOR) {
4840 outPointer.touchMinor = inPointer.absMTTouchMinor;
4841 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004842 // Assume touch area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004843 outPointer.touchMinor = outPointer.touchMajor;
4844 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004845
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004846 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MAJOR) {
4847 outPointer.toolMajor = inPointer.absMTWidthMajor;
4848 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004849 // Default tool area to 0 if absent.
4850 outPointer.toolMajor = 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004851 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004852
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004853 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MINOR) {
4854 outPointer.toolMinor = inPointer.absMTWidthMinor;
4855 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004856 // Assume tool area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004857 outPointer.toolMinor = outPointer.toolMajor;
4858 }
4859
4860 if (fields & Accumulator::FIELD_ABS_MT_ORIENTATION) {
4861 outPointer.orientation = inPointer.absMTOrientation;
4862 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004863 // Default orientation to vertical if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004864 outPointer.orientation = 0;
4865 }
4866
Jeff Brown8d608662010-08-30 03:02:23 -07004867 // Assign pointer id using tracking id if available.
Jeff Brown6d0fec22010-07-23 21:28:06 -07004868 if (havePointerIds) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004869 if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) {
4870 uint32_t id = uint32_t(inPointer.absMTTrackingId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004871
Jeff Brown6d0fec22010-07-23 21:28:06 -07004872 if (id > MAX_POINTER_ID) {
4873#if DEBUG_POINTERS
4874 LOGD("Pointers: Ignoring driver provided pointer id %d because "
Jeff Brown01ce2e92010-09-26 22:20:12 -07004875 "it is larger than max supported id %d",
Jeff Brown6d0fec22010-07-23 21:28:06 -07004876 id, MAX_POINTER_ID);
4877#endif
4878 havePointerIds = false;
4879 }
4880 else {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004881 outPointer.id = id;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004882 mCurrentTouch.idToIndex[id] = outCount;
4883 mCurrentTouch.idBits.markBit(id);
4884 }
4885 } else {
4886 havePointerIds = false;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004887 }
4888 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004889
Jeff Brown6d0fec22010-07-23 21:28:06 -07004890 outCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004891 }
4892
Jeff Brown6d0fec22010-07-23 21:28:06 -07004893 mCurrentTouch.pointerCount = outCount;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004894
Jeff Brownace13b12011-03-09 17:39:48 -08004895 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
4896 mCurrentTouch.buttonState = mButtonState;
4897
Jeff Brown6d0fec22010-07-23 21:28:06 -07004898 syncTouch(when, havePointerIds);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004899
4900 mAccumulator.clear();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004901}
4902
Jeff Brown8d608662010-08-30 03:02:23 -07004903void MultiTouchInputMapper::configureRawAxes() {
4904 TouchInputMapper::configureRawAxes();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004905
Jeff Brown8d608662010-08-30 03:02:23 -07004906 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_X, & mRawAxes.x);
4907 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_Y, & mRawAxes.y);
4908 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MAJOR, & mRawAxes.touchMajor);
4909 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MINOR, & mRawAxes.touchMinor);
4910 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MAJOR, & mRawAxes.toolMajor);
4911 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MINOR, & mRawAxes.toolMinor);
4912 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_ORIENTATION, & mRawAxes.orientation);
4913 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_PRESSURE, & mRawAxes.pressure);
Jeff Brown9c3cda02010-06-15 01:31:58 -07004914}
4915
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004916
Jeff Browncb1404e2011-01-15 18:14:15 -08004917// --- JoystickInputMapper ---
4918
4919JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
4920 InputMapper(device) {
Jeff Browncb1404e2011-01-15 18:14:15 -08004921}
4922
4923JoystickInputMapper::~JoystickInputMapper() {
4924}
4925
4926uint32_t JoystickInputMapper::getSources() {
4927 return AINPUT_SOURCE_JOYSTICK;
4928}
4929
4930void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
4931 InputMapper::populateDeviceInfo(info);
4932
Jeff Brown6f2fba42011-02-19 01:08:02 -08004933 for (size_t i = 0; i < mAxes.size(); i++) {
4934 const Axis& axis = mAxes.valueAt(i);
Jeff Brownefd32662011-03-08 15:13:06 -08004935 info->addMotionRange(axis.axisInfo.axis, AINPUT_SOURCE_JOYSTICK,
4936 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08004937 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
Jeff Brownefd32662011-03-08 15:13:06 -08004938 info->addMotionRange(axis.axisInfo.highAxis, AINPUT_SOURCE_JOYSTICK,
4939 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08004940 }
Jeff Browncb1404e2011-01-15 18:14:15 -08004941 }
4942}
4943
4944void JoystickInputMapper::dump(String8& dump) {
4945 dump.append(INDENT2 "Joystick Input Mapper:\n");
4946
Jeff Brown6f2fba42011-02-19 01:08:02 -08004947 dump.append(INDENT3 "Axes:\n");
4948 size_t numAxes = mAxes.size();
4949 for (size_t i = 0; i < numAxes; i++) {
4950 const Axis& axis = mAxes.valueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08004951 const char* label = getAxisLabel(axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004952 if (label) {
Jeff Brown85297452011-03-04 13:07:49 -08004953 dump.appendFormat(INDENT4 "%s", label);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004954 } else {
Jeff Brown85297452011-03-04 13:07:49 -08004955 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004956 }
Jeff Brown85297452011-03-04 13:07:49 -08004957 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
4958 label = getAxisLabel(axis.axisInfo.highAxis);
4959 if (label) {
4960 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
4961 } else {
4962 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
4963 axis.axisInfo.splitValue);
4964 }
4965 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
4966 dump.append(" (invert)");
4967 }
4968
4969 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f\n",
4970 axis.min, axis.max, axis.flat, axis.fuzz);
4971 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
4972 "highScale=%0.5f, highOffset=%0.5f\n",
4973 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004974 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, rawFlat=%d, rawFuzz=%d\n",
4975 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
4976 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz);
Jeff Browncb1404e2011-01-15 18:14:15 -08004977 }
4978}
4979
4980void JoystickInputMapper::configure() {
4981 InputMapper::configure();
4982
Jeff Brown6f2fba42011-02-19 01:08:02 -08004983 // Collect all axes.
4984 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
4985 RawAbsoluteAxisInfo rawAxisInfo;
4986 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), abs, &rawAxisInfo);
4987 if (rawAxisInfo.valid) {
Jeff Brown85297452011-03-04 13:07:49 -08004988 // Map axis.
4989 AxisInfo axisInfo;
4990 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004991 if (!explicitlyMapped) {
4992 // Axis is not explicitly mapped, will choose a generic axis later.
Jeff Brown85297452011-03-04 13:07:49 -08004993 axisInfo.mode = AxisInfo::MODE_NORMAL;
4994 axisInfo.axis = -1;
Jeff Brown6f2fba42011-02-19 01:08:02 -08004995 }
Jeff Browncb1404e2011-01-15 18:14:15 -08004996
Jeff Brown85297452011-03-04 13:07:49 -08004997 // Apply flat override.
4998 int32_t rawFlat = axisInfo.flatOverride < 0
4999 ? rawAxisInfo.flat : axisInfo.flatOverride;
5000
5001 // Calculate scaling factors and limits.
Jeff Brown6f2fba42011-02-19 01:08:02 -08005002 Axis axis;
Jeff Brown85297452011-03-04 13:07:49 -08005003 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
5004 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
5005 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
5006 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5007 scale, 0.0f, highScale, 0.0f,
5008 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
5009 } else if (isCenteredAxis(axisInfo.axis)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005010 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
5011 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
Jeff Brown85297452011-03-04 13:07:49 -08005012 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5013 scale, offset, scale, offset,
5014 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005015 } else {
5016 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
Jeff Brown85297452011-03-04 13:07:49 -08005017 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5018 scale, 0.0f, scale, 0.0f,
5019 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005020 }
5021
5022 // To eliminate noise while the joystick is at rest, filter out small variations
5023 // in axis values up front.
5024 axis.filter = axis.flat * 0.25f;
5025
5026 mAxes.add(abs, axis);
5027 }
5028 }
5029
5030 // If there are too many axes, start dropping them.
5031 // Prefer to keep explicitly mapped axes.
5032 if (mAxes.size() > PointerCoords::MAX_AXES) {
5033 LOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.",
5034 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
5035 pruneAxes(true);
5036 pruneAxes(false);
5037 }
5038
5039 // Assign generic axis ids to remaining axes.
5040 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
5041 size_t numAxes = mAxes.size();
5042 for (size_t i = 0; i < numAxes; i++) {
5043 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005044 if (axis.axisInfo.axis < 0) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005045 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
5046 && haveAxis(nextGenericAxisId)) {
5047 nextGenericAxisId += 1;
5048 }
5049
5050 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
Jeff Brown85297452011-03-04 13:07:49 -08005051 axis.axisInfo.axis = nextGenericAxisId;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005052 nextGenericAxisId += 1;
5053 } else {
5054 LOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
5055 "have already been assigned to other axes.",
5056 getDeviceName().string(), mAxes.keyAt(i));
5057 mAxes.removeItemsAt(i--);
5058 numAxes -= 1;
5059 }
5060 }
5061 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005062}
5063
Jeff Brown85297452011-03-04 13:07:49 -08005064bool JoystickInputMapper::haveAxis(int32_t axisId) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005065 size_t numAxes = mAxes.size();
5066 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005067 const Axis& axis = mAxes.valueAt(i);
5068 if (axis.axisInfo.axis == axisId
5069 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
5070 && axis.axisInfo.highAxis == axisId)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005071 return true;
5072 }
5073 }
5074 return false;
5075}
Jeff Browncb1404e2011-01-15 18:14:15 -08005076
Jeff Brown6f2fba42011-02-19 01:08:02 -08005077void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
5078 size_t i = mAxes.size();
5079 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
5080 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
5081 continue;
5082 }
5083 LOGI("Discarding joystick '%s' axis %d because there are too many axes.",
5084 getDeviceName().string(), mAxes.keyAt(i));
5085 mAxes.removeItemsAt(i);
5086 }
5087}
5088
5089bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
5090 switch (axis) {
5091 case AMOTION_EVENT_AXIS_X:
5092 case AMOTION_EVENT_AXIS_Y:
5093 case AMOTION_EVENT_AXIS_Z:
5094 case AMOTION_EVENT_AXIS_RX:
5095 case AMOTION_EVENT_AXIS_RY:
5096 case AMOTION_EVENT_AXIS_RZ:
5097 case AMOTION_EVENT_AXIS_HAT_X:
5098 case AMOTION_EVENT_AXIS_HAT_Y:
5099 case AMOTION_EVENT_AXIS_ORIENTATION:
Jeff Brown85297452011-03-04 13:07:49 -08005100 case AMOTION_EVENT_AXIS_RUDDER:
5101 case AMOTION_EVENT_AXIS_WHEEL:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005102 return true;
5103 default:
5104 return false;
5105 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005106}
5107
5108void JoystickInputMapper::reset() {
5109 // Recenter all axes.
5110 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Browncb1404e2011-01-15 18:14:15 -08005111
Jeff Brown6f2fba42011-02-19 01:08:02 -08005112 size_t numAxes = mAxes.size();
5113 for (size_t i = 0; i < numAxes; i++) {
5114 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005115 axis.resetValue();
Jeff Brown6f2fba42011-02-19 01:08:02 -08005116 }
5117
5118 sync(when, true /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005119
5120 InputMapper::reset();
5121}
5122
5123void JoystickInputMapper::process(const RawEvent* rawEvent) {
5124 switch (rawEvent->type) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005125 case EV_ABS: {
5126 ssize_t index = mAxes.indexOfKey(rawEvent->scanCode);
5127 if (index >= 0) {
5128 Axis& axis = mAxes.editValueAt(index);
Jeff Brown85297452011-03-04 13:07:49 -08005129 float newValue, highNewValue;
5130 switch (axis.axisInfo.mode) {
5131 case AxisInfo::MODE_INVERT:
5132 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
5133 * axis.scale + axis.offset;
5134 highNewValue = 0.0f;
5135 break;
5136 case AxisInfo::MODE_SPLIT:
5137 if (rawEvent->value < axis.axisInfo.splitValue) {
5138 newValue = (axis.axisInfo.splitValue - rawEvent->value)
5139 * axis.scale + axis.offset;
5140 highNewValue = 0.0f;
5141 } else if (rawEvent->value > axis.axisInfo.splitValue) {
5142 newValue = 0.0f;
5143 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
5144 * axis.highScale + axis.highOffset;
5145 } else {
5146 newValue = 0.0f;
5147 highNewValue = 0.0f;
5148 }
5149 break;
5150 default:
5151 newValue = rawEvent->value * axis.scale + axis.offset;
5152 highNewValue = 0.0f;
5153 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005154 }
Jeff Brown85297452011-03-04 13:07:49 -08005155 axis.newValue = newValue;
5156 axis.highNewValue = highNewValue;
Jeff Browncb1404e2011-01-15 18:14:15 -08005157 }
5158 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005159 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005160
5161 case EV_SYN:
5162 switch (rawEvent->scanCode) {
5163 case SYN_REPORT:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005164 sync(rawEvent->when, false /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005165 break;
5166 }
5167 break;
5168 }
5169}
5170
Jeff Brown6f2fba42011-02-19 01:08:02 -08005171void JoystickInputMapper::sync(nsecs_t when, bool force) {
Jeff Brown85297452011-03-04 13:07:49 -08005172 if (!filterAxes(force)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005173 return;
Jeff Browncb1404e2011-01-15 18:14:15 -08005174 }
5175
5176 int32_t metaState = mContext->getGlobalMetaState();
5177
Jeff Brown6f2fba42011-02-19 01:08:02 -08005178 PointerCoords pointerCoords;
5179 pointerCoords.clear();
5180
5181 size_t numAxes = mAxes.size();
5182 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005183 const Axis& axis = mAxes.valueAt(i);
5184 pointerCoords.setAxisValue(axis.axisInfo.axis, axis.currentValue);
5185 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5186 pointerCoords.setAxisValue(axis.axisInfo.highAxis, axis.highCurrentValue);
5187 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005188 }
5189
Jeff Brown56194eb2011-03-02 19:23:13 -08005190 // Moving a joystick axis should not wake the devide because joysticks can
5191 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
5192 // button will likely wake the device.
5193 // TODO: Use the input device configuration to control this behavior more finely.
5194 uint32_t policyFlags = 0;
5195
Jeff Brown6f2fba42011-02-19 01:08:02 -08005196 int32_t pointerId = 0;
Jeff Brown56194eb2011-03-02 19:23:13 -08005197 getDispatcher()->notifyMotion(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Jeff Brown6f2fba42011-02-19 01:08:02 -08005198 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
5199 1, &pointerId, &pointerCoords, 0, 0, 0);
Jeff Browncb1404e2011-01-15 18:14:15 -08005200}
5201
Jeff Brown85297452011-03-04 13:07:49 -08005202bool JoystickInputMapper::filterAxes(bool force) {
5203 bool atLeastOneSignificantChange = force;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005204 size_t numAxes = mAxes.size();
5205 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005206 Axis& axis = mAxes.editValueAt(i);
5207 if (force || hasValueChangedSignificantly(axis.filter,
5208 axis.newValue, axis.currentValue, axis.min, axis.max)) {
5209 axis.currentValue = axis.newValue;
5210 atLeastOneSignificantChange = true;
5211 }
5212 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5213 if (force || hasValueChangedSignificantly(axis.filter,
5214 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
5215 axis.highCurrentValue = axis.highNewValue;
5216 atLeastOneSignificantChange = true;
5217 }
5218 }
5219 }
5220 return atLeastOneSignificantChange;
5221}
5222
5223bool JoystickInputMapper::hasValueChangedSignificantly(
5224 float filter, float newValue, float currentValue, float min, float max) {
5225 if (newValue != currentValue) {
5226 // Filter out small changes in value unless the value is converging on the axis
5227 // bounds or center point. This is intended to reduce the amount of information
5228 // sent to applications by particularly noisy joysticks (such as PS3).
5229 if (fabs(newValue - currentValue) > filter
5230 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
5231 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
5232 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
5233 return true;
5234 }
5235 }
5236 return false;
5237}
5238
5239bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
5240 float filter, float newValue, float currentValue, float thresholdValue) {
5241 float newDistance = fabs(newValue - thresholdValue);
5242 if (newDistance < filter) {
5243 float oldDistance = fabs(currentValue - thresholdValue);
5244 if (newDistance < oldDistance) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005245 return true;
5246 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005247 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08005248 return false;
Jeff Browncb1404e2011-01-15 18:14:15 -08005249}
5250
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005251} // namespace android