blob: 94753bfaf41999d9cc1c378313068fb2a741963a [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 Brown96ad3972011-03-09 17:39:48 -080036// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
Jeff Brownefd32662011-03-08 15:13:06 -080039
Jeff Brownb4ff35d2011-01-02 16:37:43 -080040#include "InputReader.h"
41
Jeff 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 Brown96ad3972011-03-09 17:39:48 -080060// --- Constants ---
61
62// Quiet time between certain gesture transitions.
63// Time to allow for all fingers or buttons to settle into a stable state before
64// starting a new gesture.
65static const nsecs_t QUIET_INTERVAL = 100 * 1000000; // 100 ms
66
67// The minimum speed that a pointer must travel for us to consider switching the active
68// touch pointer to it during a drag. This threshold is set to avoid switching due
69// to noise from a finger resting on the touch pad (perhaps just pressing it down).
70static const float DRAG_MIN_SWITCH_SPEED = 50.0f; // pixels per second
71
72// Tap gesture delay time.
73// The time between down and up must be less than this to be considered a tap.
74static const nsecs_t TAP_INTERVAL = 100 * 1000000; // 100 ms
75
76// The distance in pixels that the pointer is allowed to move from initial down
77// to up and still be called a tap.
78static const float TAP_SLOP = 5.0f; // 5 pixels
79
80// The transition from INDETERMINATE_MULTITOUCH to SWIPE or FREEFORM gesture mode is made when
81// all of the pointers have traveled this number of pixels from the start point.
82static const float MULTITOUCH_MIN_TRAVEL = 5.0f;
83
84// The transition from INDETERMINATE_MULTITOUCH to SWIPE gesture mode can only occur when the
85// cosine of the angle between the two vectors is greater than or equal to than this value
86// which indicates that the vectors are oriented in the same direction.
87// When the vectors are oriented in the exactly same direction, the cosine is 1.0.
88// (In exactly opposite directions, the cosine is -1.0.)
89static const float SWIPE_TRANSITION_ANGLE_COSINE = 0.5f; // cosine of 45 degrees
90
91
Jeff 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 Brown96ad3972011-03-09 17:39:48 -0800119inline static int32_t distanceSquared(int32_t x1, int32_t y1, int32_t x2, int32_t y2) {
120 int32_t dx = x1 - x2;
121 int32_t dy = y1 - y2;
122 return dx * dx + dy * dy;
123}
124
Jeff Brown517bb4c2011-01-14 19:09:23 -0800125inline static int32_t signExtendNybble(int32_t value) {
126 return value >= 8 ? value - 16 : value;
127}
128
Jeff Brownef3d7e82010-09-30 14:33:04 -0700129static inline const char* toString(bool value) {
130 return value ? "true" : "false";
131}
132
Jeff Brown9626b142011-03-03 02:09:54 -0800133static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
134 const int32_t map[][4], size_t mapSize) {
135 if (orientation != DISPLAY_ORIENTATION_0) {
136 for (size_t i = 0; i < mapSize; i++) {
137 if (value == map[i][0]) {
138 return map[i][orientation];
139 }
140 }
141 }
142 return value;
143}
144
Jeff 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 Brown68d60752011-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 Brown68d60752011-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 Browndbf8d272011-03-18 18:14:26 -0700253 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
254 if (count) {
255 processEvents(mEventBuffer, count);
256 }
257 if (!count || timeoutMillis == 0) {
Jeff Brown68d60752011-03-17 01:34:19 -0700258 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
259#if DEBUG_RAW_EVENTS
260 LOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
261#endif
262 mNextTimeout = LLONG_MAX;
263 timeoutExpired(now);
264 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700265}
266
Jeff Browndbf8d272011-03-18 18:14:26 -0700267void InputReader::processEvents(const RawEvent* rawEvents, size_t count) {
268 for (const RawEvent* rawEvent = rawEvents; count;) {
269 int32_t type = rawEvent->type;
270 size_t batchSize = 1;
271 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
272 int32_t deviceId = rawEvent->deviceId;
273 while (batchSize < count) {
274 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
275 || rawEvent[batchSize].deviceId != deviceId) {
276 break;
277 }
278 batchSize += 1;
279 }
280#if DEBUG_RAW_EVENTS
281 LOGD("BatchSize: %d Count: %d", batchSize, count);
282#endif
283 processEventsForDevice(deviceId, rawEvent, batchSize);
284 } else {
285 switch (rawEvent->type) {
286 case EventHubInterface::DEVICE_ADDED:
287 addDevice(rawEvent->deviceId);
288 break;
289 case EventHubInterface::DEVICE_REMOVED:
290 removeDevice(rawEvent->deviceId);
291 break;
292 case EventHubInterface::FINISHED_DEVICE_SCAN:
293 handleConfigurationChanged(rawEvent->when);
294 break;
295 default:
296 assert(false); // can't happen
297 break;
298 }
299 }
300 count -= batchSize;
301 rawEvent += batchSize;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700302 }
303}
304
Jeff Brown7342bb92010-10-01 18:55:43 -0700305void InputReader::addDevice(int32_t deviceId) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700306 String8 name = mEventHub->getDeviceName(deviceId);
307 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
308
309 InputDevice* device = createDevice(deviceId, name, classes);
310 device->configure();
311
Jeff Brown8d608662010-08-30 03:02:23 -0700312 if (device->isIgnored()) {
Jeff Brown90655042010-12-02 13:50:46 -0800313 LOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, name.string());
Jeff Brown8d608662010-08-30 03:02:23 -0700314 } else {
Jeff Brown90655042010-12-02 13:50:46 -0800315 LOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, name.string(),
Jeff Brownef3d7e82010-09-30 14:33:04 -0700316 device->getSources());
Jeff Brown8d608662010-08-30 03:02:23 -0700317 }
318
Jeff Brown6d0fec22010-07-23 21:28:06 -0700319 bool added = false;
320 { // acquire device registry writer lock
321 RWLock::AutoWLock _wl(mDeviceRegistryLock);
322
323 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
324 if (deviceIndex < 0) {
325 mDevices.add(deviceId, device);
326 added = true;
327 }
328 } // release device registry writer lock
329
330 if (! added) {
331 LOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
332 delete device;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700333 return;
334 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700335}
336
Jeff Brown7342bb92010-10-01 18:55:43 -0700337void InputReader::removeDevice(int32_t deviceId) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700338 bool removed = false;
339 InputDevice* device = NULL;
340 { // acquire device registry writer lock
341 RWLock::AutoWLock _wl(mDeviceRegistryLock);
342
343 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
344 if (deviceIndex >= 0) {
345 device = mDevices.valueAt(deviceIndex);
346 mDevices.removeItemsAt(deviceIndex, 1);
347 removed = true;
348 }
349 } // release device registry writer lock
350
351 if (! removed) {
352 LOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700353 return;
354 }
355
Jeff Brown6d0fec22010-07-23 21:28:06 -0700356 if (device->isIgnored()) {
Jeff Brown90655042010-12-02 13:50:46 -0800357 LOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Jeff Brown6d0fec22010-07-23 21:28:06 -0700358 device->getId(), device->getName().string());
359 } else {
Jeff Brown90655042010-12-02 13:50:46 -0800360 LOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Jeff Brown6d0fec22010-07-23 21:28:06 -0700361 device->getId(), device->getName().string(), device->getSources());
362 }
363
Jeff Brown8d608662010-08-30 03:02:23 -0700364 device->reset();
365
Jeff Brown6d0fec22010-07-23 21:28:06 -0700366 delete device;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700367}
368
Jeff Brown6d0fec22010-07-23 21:28:06 -0700369InputDevice* InputReader::createDevice(int32_t deviceId, const String8& name, uint32_t classes) {
370 InputDevice* device = new InputDevice(this, deviceId, name);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700371
Jeff Brown56194eb2011-03-02 19:23:13 -0800372 // External devices.
373 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
374 device->setExternal(true);
375 }
376
Jeff Brown6d0fec22010-07-23 21:28:06 -0700377 // Switch-like devices.
378 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
379 device->addMapper(new SwitchInputMapper(device));
380 }
381
382 // Keyboard-like devices.
Jeff Brownefd32662011-03-08 15:13:06 -0800383 uint32_t keyboardSource = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700384 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
385 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800386 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700387 }
388 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
389 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
390 }
391 if (classes & INPUT_DEVICE_CLASS_DPAD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800392 keyboardSource |= AINPUT_SOURCE_DPAD;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700393 }
Jeff Browncb1404e2011-01-15 18:14:15 -0800394 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800395 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
Jeff Browncb1404e2011-01-15 18:14:15 -0800396 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700397
Jeff Brownefd32662011-03-08 15:13:06 -0800398 if (keyboardSource != 0) {
399 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700400 }
401
Jeff Brown83c09682010-12-23 17:50:18 -0800402 // Cursor-like devices.
403 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
404 device->addMapper(new CursorInputMapper(device));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700405 }
406
Jeff Brown58a2da82011-01-25 16:02:22 -0800407 // Touchscreens and touchpad devices.
408 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800409 device->addMapper(new MultiTouchInputMapper(device));
Jeff Brown58a2da82011-01-25 16:02:22 -0800410 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800411 device->addMapper(new SingleTouchInputMapper(device));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700412 }
413
Jeff Browncb1404e2011-01-15 18:14:15 -0800414 // Joystick-like devices.
415 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
416 device->addMapper(new JoystickInputMapper(device));
417 }
418
Jeff Brown6d0fec22010-07-23 21:28:06 -0700419 return device;
420}
421
Jeff Browndbf8d272011-03-18 18:14:26 -0700422void InputReader::processEventsForDevice(int32_t deviceId,
423 const RawEvent* rawEvents, size_t count) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700424 { // acquire device registry reader lock
425 RWLock::AutoRLock _rl(mDeviceRegistryLock);
426
427 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
428 if (deviceIndex < 0) {
429 LOGW("Discarding event for unknown deviceId %d.", deviceId);
430 return;
431 }
432
433 InputDevice* device = mDevices.valueAt(deviceIndex);
434 if (device->isIgnored()) {
435 //LOGD("Discarding event for ignored deviceId %d.", deviceId);
436 return;
437 }
438
Jeff Browndbf8d272011-03-18 18:14:26 -0700439 device->process(rawEvents, count);
Jeff Brown6d0fec22010-07-23 21:28:06 -0700440 } // release device registry reader lock
441}
442
Jeff Brown68d60752011-03-17 01:34:19 -0700443void InputReader::timeoutExpired(nsecs_t when) {
444 { // acquire device registry reader lock
445 RWLock::AutoRLock _rl(mDeviceRegistryLock);
446
447 for (size_t i = 0; i < mDevices.size(); i++) {
448 InputDevice* device = mDevices.valueAt(i);
449 if (!device->isIgnored()) {
450 device->timeoutExpired(when);
451 }
452 }
453 } // release device registry reader lock
454}
455
Jeff Brownc3db8582010-10-20 15:33:38 -0700456void InputReader::handleConfigurationChanged(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700457 // Reset global meta state because it depends on the list of all configured devices.
458 updateGlobalMetaState();
459
460 // Update input configuration.
461 updateInputConfiguration();
462
463 // Enqueue configuration changed.
464 mDispatcher->notifyConfigurationChanged(when);
465}
466
467void InputReader::configureExcludedDevices() {
468 Vector<String8> excludedDeviceNames;
469 mPolicy->getExcludedDeviceNames(excludedDeviceNames);
470
471 for (size_t i = 0; i < excludedDeviceNames.size(); i++) {
472 mEventHub->addExcludedDevice(excludedDeviceNames[i]);
473 }
474}
475
476void InputReader::updateGlobalMetaState() {
477 { // acquire state lock
478 AutoMutex _l(mStateLock);
479
480 mGlobalMetaState = 0;
481
482 { // acquire device registry reader lock
483 RWLock::AutoRLock _rl(mDeviceRegistryLock);
484
485 for (size_t i = 0; i < mDevices.size(); i++) {
486 InputDevice* device = mDevices.valueAt(i);
487 mGlobalMetaState |= device->getMetaState();
488 }
489 } // release device registry reader lock
490 } // release state lock
491}
492
493int32_t InputReader::getGlobalMetaState() {
494 { // acquire state lock
495 AutoMutex _l(mStateLock);
496
497 return mGlobalMetaState;
498 } // release state lock
499}
500
501void InputReader::updateInputConfiguration() {
502 { // acquire state lock
503 AutoMutex _l(mStateLock);
504
505 int32_t touchScreenConfig = InputConfiguration::TOUCHSCREEN_NOTOUCH;
506 int32_t keyboardConfig = InputConfiguration::KEYBOARD_NOKEYS;
507 int32_t navigationConfig = InputConfiguration::NAVIGATION_NONAV;
508 { // acquire device registry reader lock
509 RWLock::AutoRLock _rl(mDeviceRegistryLock);
510
511 InputDeviceInfo deviceInfo;
512 for (size_t i = 0; i < mDevices.size(); i++) {
513 InputDevice* device = mDevices.valueAt(i);
514 device->getDeviceInfo(& deviceInfo);
515 uint32_t sources = deviceInfo.getSources();
516
517 if ((sources & AINPUT_SOURCE_TOUCHSCREEN) == AINPUT_SOURCE_TOUCHSCREEN) {
518 touchScreenConfig = InputConfiguration::TOUCHSCREEN_FINGER;
519 }
520 if ((sources & AINPUT_SOURCE_TRACKBALL) == AINPUT_SOURCE_TRACKBALL) {
521 navigationConfig = InputConfiguration::NAVIGATION_TRACKBALL;
522 } else if ((sources & AINPUT_SOURCE_DPAD) == AINPUT_SOURCE_DPAD) {
523 navigationConfig = InputConfiguration::NAVIGATION_DPAD;
524 }
525 if (deviceInfo.getKeyboardType() == AINPUT_KEYBOARD_TYPE_ALPHABETIC) {
526 keyboardConfig = InputConfiguration::KEYBOARD_QWERTY;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700527 }
528 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700529 } // release device registry reader lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700530
Jeff Brown6d0fec22010-07-23 21:28:06 -0700531 mInputConfiguration.touchScreen = touchScreenConfig;
532 mInputConfiguration.keyboard = keyboardConfig;
533 mInputConfiguration.navigation = navigationConfig;
534 } // release state lock
535}
536
Jeff Brownfe508922011-01-18 15:10:10 -0800537void InputReader::disableVirtualKeysUntil(nsecs_t time) {
538 mDisableVirtualKeysTimeout = time;
539}
540
541bool InputReader::shouldDropVirtualKey(nsecs_t now,
542 InputDevice* device, int32_t keyCode, int32_t scanCode) {
543 if (now < mDisableVirtualKeysTimeout) {
544 LOGI("Dropping virtual key from device %s because virtual keys are "
545 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
546 device->getName().string(),
547 (mDisableVirtualKeysTimeout - now) * 0.000001,
548 keyCode, scanCode);
549 return true;
550 } else {
551 return false;
552 }
553}
554
Jeff Brown05dc66a2011-03-02 14:41:58 -0800555void InputReader::fadePointer() {
556 { // acquire device registry reader lock
557 RWLock::AutoRLock _rl(mDeviceRegistryLock);
558
559 for (size_t i = 0; i < mDevices.size(); i++) {
560 InputDevice* device = mDevices.valueAt(i);
561 device->fadePointer();
562 }
563 } // release device registry reader lock
564}
565
Jeff Brown68d60752011-03-17 01:34:19 -0700566void InputReader::requestTimeoutAtTime(nsecs_t when) {
567 if (when < mNextTimeout) {
568 mNextTimeout = when;
569 }
570}
571
Jeff Brown6d0fec22010-07-23 21:28:06 -0700572void InputReader::getInputConfiguration(InputConfiguration* outConfiguration) {
573 { // acquire state lock
574 AutoMutex _l(mStateLock);
575
576 *outConfiguration = mInputConfiguration;
577 } // release state lock
578}
579
580status_t InputReader::getInputDeviceInfo(int32_t deviceId, InputDeviceInfo* outDeviceInfo) {
581 { // acquire device registry reader lock
582 RWLock::AutoRLock _rl(mDeviceRegistryLock);
583
584 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
585 if (deviceIndex < 0) {
586 return NAME_NOT_FOUND;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700587 }
588
Jeff Brown6d0fec22010-07-23 21:28:06 -0700589 InputDevice* device = mDevices.valueAt(deviceIndex);
590 if (device->isIgnored()) {
591 return NAME_NOT_FOUND;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700592 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700593
594 device->getDeviceInfo(outDeviceInfo);
595 return OK;
596 } // release device registy reader lock
597}
598
599void InputReader::getInputDeviceIds(Vector<int32_t>& outDeviceIds) {
600 outDeviceIds.clear();
601
602 { // acquire device registry reader lock
603 RWLock::AutoRLock _rl(mDeviceRegistryLock);
604
605 size_t numDevices = mDevices.size();
606 for (size_t i = 0; i < numDevices; i++) {
607 InputDevice* device = mDevices.valueAt(i);
608 if (! device->isIgnored()) {
609 outDeviceIds.add(device->getId());
610 }
611 }
612 } // release device registy reader lock
613}
614
615int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
616 int32_t keyCode) {
617 return getState(deviceId, sourceMask, keyCode, & InputDevice::getKeyCodeState);
618}
619
620int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
621 int32_t scanCode) {
622 return getState(deviceId, sourceMask, scanCode, & InputDevice::getScanCodeState);
623}
624
625int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
626 return getState(deviceId, sourceMask, switchCode, & InputDevice::getSwitchState);
627}
628
629int32_t InputReader::getState(int32_t deviceId, uint32_t sourceMask, int32_t code,
630 GetStateFunc getStateFunc) {
631 { // acquire device registry reader lock
632 RWLock::AutoRLock _rl(mDeviceRegistryLock);
633
634 int32_t result = AKEY_STATE_UNKNOWN;
635 if (deviceId >= 0) {
636 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
637 if (deviceIndex >= 0) {
638 InputDevice* device = mDevices.valueAt(deviceIndex);
639 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
640 result = (device->*getStateFunc)(sourceMask, code);
641 }
642 }
643 } else {
644 size_t numDevices = mDevices.size();
645 for (size_t i = 0; i < numDevices; i++) {
646 InputDevice* device = mDevices.valueAt(i);
647 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
648 result = (device->*getStateFunc)(sourceMask, code);
649 if (result >= AKEY_STATE_DOWN) {
650 return result;
651 }
652 }
653 }
654 }
655 return result;
656 } // release device registy reader lock
657}
658
659bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
660 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
661 memset(outFlags, 0, numCodes);
662 return markSupportedKeyCodes(deviceId, sourceMask, numCodes, keyCodes, outFlags);
663}
664
665bool InputReader::markSupportedKeyCodes(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
666 const int32_t* keyCodes, uint8_t* outFlags) {
667 { // acquire device registry reader lock
668 RWLock::AutoRLock _rl(mDeviceRegistryLock);
669 bool result = false;
670 if (deviceId >= 0) {
671 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
672 if (deviceIndex >= 0) {
673 InputDevice* device = mDevices.valueAt(deviceIndex);
674 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
675 result = device->markSupportedKeyCodes(sourceMask,
676 numCodes, keyCodes, outFlags);
677 }
678 }
679 } else {
680 size_t numDevices = mDevices.size();
681 for (size_t i = 0; i < numDevices; i++) {
682 InputDevice* device = mDevices.valueAt(i);
683 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
684 result |= device->markSupportedKeyCodes(sourceMask,
685 numCodes, keyCodes, outFlags);
686 }
687 }
688 }
689 return result;
690 } // release device registy reader lock
691}
692
Jeff Brownb88102f2010-09-08 11:49:43 -0700693void InputReader::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -0700694 mEventHub->dump(dump);
695 dump.append("\n");
696
697 dump.append("Input Reader State:\n");
698
Jeff Brownef3d7e82010-09-30 14:33:04 -0700699 { // acquire device registry reader lock
700 RWLock::AutoRLock _rl(mDeviceRegistryLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700701
Jeff Brownef3d7e82010-09-30 14:33:04 -0700702 for (size_t i = 0; i < mDevices.size(); i++) {
703 mDevices.valueAt(i)->dump(dump);
Jeff Brownb88102f2010-09-08 11:49:43 -0700704 }
Jeff Brownef3d7e82010-09-30 14:33:04 -0700705 } // release device registy reader lock
Jeff Brownb88102f2010-09-08 11:49:43 -0700706}
707
Jeff Brown6d0fec22010-07-23 21:28:06 -0700708
709// --- InputReaderThread ---
710
711InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
712 Thread(/*canCallJava*/ true), mReader(reader) {
713}
714
715InputReaderThread::~InputReaderThread() {
716}
717
718bool InputReaderThread::threadLoop() {
719 mReader->loopOnce();
720 return true;
721}
722
723
724// --- InputDevice ---
725
726InputDevice::InputDevice(InputReaderContext* context, int32_t id, const String8& name) :
Jeff Brown56194eb2011-03-02 19:23:13 -0800727 mContext(context), mId(id), mName(name), mSources(0), mIsExternal(false) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700728}
729
730InputDevice::~InputDevice() {
731 size_t numMappers = mMappers.size();
732 for (size_t i = 0; i < numMappers; i++) {
733 delete mMappers[i];
734 }
735 mMappers.clear();
736}
737
Jeff Brownef3d7e82010-09-30 14:33:04 -0700738void InputDevice::dump(String8& dump) {
739 InputDeviceInfo deviceInfo;
740 getDeviceInfo(& deviceInfo);
741
Jeff Brown90655042010-12-02 13:50:46 -0800742 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
Jeff Brownef3d7e82010-09-30 14:33:04 -0700743 deviceInfo.getName().string());
Jeff Brown56194eb2011-03-02 19:23:13 -0800744 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Jeff Brownef3d7e82010-09-30 14:33:04 -0700745 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
746 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Jeff Browncc0c1592011-02-19 05:07:28 -0800747
Jeff Brownefd32662011-03-08 15:13:06 -0800748 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
Jeff Browncc0c1592011-02-19 05:07:28 -0800749 if (!ranges.isEmpty()) {
Jeff Brownef3d7e82010-09-30 14:33:04 -0700750 dump.append(INDENT2 "Motion Ranges:\n");
Jeff Browncc0c1592011-02-19 05:07:28 -0800751 for (size_t i = 0; i < ranges.size(); i++) {
Jeff Brownefd32662011-03-08 15:13:06 -0800752 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
753 const char* label = getAxisLabel(range.axis);
Jeff Browncc0c1592011-02-19 05:07:28 -0800754 char name[32];
755 if (label) {
756 strncpy(name, label, sizeof(name));
757 name[sizeof(name) - 1] = '\0';
758 } else {
Jeff Brownefd32662011-03-08 15:13:06 -0800759 snprintf(name, sizeof(name), "%d", range.axis);
Jeff Browncc0c1592011-02-19 05:07:28 -0800760 }
Jeff Brownefd32662011-03-08 15:13:06 -0800761 dump.appendFormat(INDENT3 "%s: source=0x%08x, "
762 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f\n",
763 name, range.source, range.min, range.max, range.flat, range.fuzz);
Jeff Browncc0c1592011-02-19 05:07:28 -0800764 }
Jeff Brownef3d7e82010-09-30 14:33:04 -0700765 }
766
767 size_t numMappers = mMappers.size();
768 for (size_t i = 0; i < numMappers; i++) {
769 InputMapper* mapper = mMappers[i];
770 mapper->dump(dump);
771 }
772}
773
Jeff Brown6d0fec22010-07-23 21:28:06 -0700774void InputDevice::addMapper(InputMapper* mapper) {
775 mMappers.add(mapper);
776}
777
778void InputDevice::configure() {
Jeff Brown8d608662010-08-30 03:02:23 -0700779 if (! isIgnored()) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800780 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
Jeff Brown8d608662010-08-30 03:02:23 -0700781 }
782
Jeff Brown6d0fec22010-07-23 21:28:06 -0700783 mSources = 0;
784
785 size_t numMappers = mMappers.size();
786 for (size_t i = 0; i < numMappers; i++) {
787 InputMapper* mapper = mMappers[i];
788 mapper->configure();
789 mSources |= mapper->getSources();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700790 }
791}
792
Jeff Brown6d0fec22010-07-23 21:28:06 -0700793void InputDevice::reset() {
794 size_t numMappers = mMappers.size();
795 for (size_t i = 0; i < numMappers; i++) {
796 InputMapper* mapper = mMappers[i];
797 mapper->reset();
798 }
799}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700800
Jeff Browndbf8d272011-03-18 18:14:26 -0700801void InputDevice::process(const RawEvent* rawEvents, size_t count) {
802 // Process all of the events in order for each mapper.
803 // We cannot simply ask each mapper to process them in bulk because mappers may
804 // have side-effects that must be interleaved. For example, joystick movement events and
805 // gamepad button presses are handled by different mappers but they should be dispatched
806 // in the order received.
Jeff Brown6d0fec22010-07-23 21:28:06 -0700807 size_t numMappers = mMappers.size();
Jeff Browndbf8d272011-03-18 18:14:26 -0700808 for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
809#if DEBUG_RAW_EVENTS
810 LOGD("Input event: device=%d type=0x%04x scancode=0x%04x "
811 "keycode=0x%04x value=0x%04x flags=0x%08x",
812 rawEvent->deviceId, rawEvent->type, rawEvent->scanCode, rawEvent->keyCode,
813 rawEvent->value, rawEvent->flags);
814#endif
815
816 for (size_t i = 0; i < numMappers; i++) {
817 InputMapper* mapper = mMappers[i];
818 mapper->process(rawEvent);
819 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700820 }
821}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700822
Jeff Brown68d60752011-03-17 01:34:19 -0700823void InputDevice::timeoutExpired(nsecs_t when) {
824 size_t numMappers = mMappers.size();
825 for (size_t i = 0; i < numMappers; i++) {
826 InputMapper* mapper = mMappers[i];
827 mapper->timeoutExpired(when);
828 }
829}
830
Jeff Brown6d0fec22010-07-23 21:28:06 -0700831void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
832 outDeviceInfo->initialize(mId, mName);
833
834 size_t numMappers = mMappers.size();
835 for (size_t i = 0; i < numMappers; i++) {
836 InputMapper* mapper = mMappers[i];
837 mapper->populateDeviceInfo(outDeviceInfo);
838 }
839}
840
841int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
842 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
843}
844
845int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
846 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
847}
848
849int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
850 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
851}
852
853int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
854 int32_t result = AKEY_STATE_UNKNOWN;
855 size_t numMappers = mMappers.size();
856 for (size_t i = 0; i < numMappers; i++) {
857 InputMapper* mapper = mMappers[i];
858 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
859 result = (mapper->*getStateFunc)(sourceMask, code);
860 if (result >= AKEY_STATE_DOWN) {
861 return result;
862 }
863 }
864 }
865 return result;
866}
867
868bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
869 const int32_t* keyCodes, uint8_t* outFlags) {
870 bool result = false;
871 size_t numMappers = mMappers.size();
872 for (size_t i = 0; i < numMappers; i++) {
873 InputMapper* mapper = mMappers[i];
874 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
875 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
876 }
877 }
878 return result;
879}
880
881int32_t InputDevice::getMetaState() {
882 int32_t result = 0;
883 size_t numMappers = mMappers.size();
884 for (size_t i = 0; i < numMappers; i++) {
885 InputMapper* mapper = mMappers[i];
886 result |= mapper->getMetaState();
887 }
888 return result;
889}
890
Jeff Brown05dc66a2011-03-02 14:41:58 -0800891void InputDevice::fadePointer() {
892 size_t numMappers = mMappers.size();
893 for (size_t i = 0; i < numMappers; i++) {
894 InputMapper* mapper = mMappers[i];
895 mapper->fadePointer();
896 }
897}
898
Jeff Brown6d0fec22010-07-23 21:28:06 -0700899
900// --- InputMapper ---
901
902InputMapper::InputMapper(InputDevice* device) :
903 mDevice(device), mContext(device->getContext()) {
904}
905
906InputMapper::~InputMapper() {
907}
908
909void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
910 info->addSource(getSources());
911}
912
Jeff Brownef3d7e82010-09-30 14:33:04 -0700913void InputMapper::dump(String8& dump) {
914}
915
Jeff Brown6d0fec22010-07-23 21:28:06 -0700916void InputMapper::configure() {
917}
918
919void InputMapper::reset() {
920}
921
Jeff Brown68d60752011-03-17 01:34:19 -0700922void InputMapper::timeoutExpired(nsecs_t when) {
923}
924
Jeff Brown6d0fec22010-07-23 21:28:06 -0700925int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
926 return AKEY_STATE_UNKNOWN;
927}
928
929int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
930 return AKEY_STATE_UNKNOWN;
931}
932
933int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
934 return AKEY_STATE_UNKNOWN;
935}
936
937bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
938 const int32_t* keyCodes, uint8_t* outFlags) {
939 return false;
940}
941
942int32_t InputMapper::getMetaState() {
943 return 0;
944}
945
Jeff Brown05dc66a2011-03-02 14:41:58 -0800946void InputMapper::fadePointer() {
947}
948
Jeff Browncb1404e2011-01-15 18:14:15 -0800949void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
950 const RawAbsoluteAxisInfo& axis, const char* name) {
951 if (axis.valid) {
952 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d\n",
953 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz);
954 } else {
955 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
956 }
957}
958
Jeff Brown6d0fec22010-07-23 21:28:06 -0700959
960// --- SwitchInputMapper ---
961
962SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
963 InputMapper(device) {
964}
965
966SwitchInputMapper::~SwitchInputMapper() {
967}
968
969uint32_t SwitchInputMapper::getSources() {
Jeff Brown89de57a2011-01-19 18:41:38 -0800970 return AINPUT_SOURCE_SWITCH;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700971}
972
973void SwitchInputMapper::process(const RawEvent* rawEvent) {
974 switch (rawEvent->type) {
975 case EV_SW:
976 processSwitch(rawEvent->when, rawEvent->scanCode, rawEvent->value);
977 break;
978 }
979}
980
981void SwitchInputMapper::processSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue) {
Jeff Brownb6997262010-10-08 22:31:17 -0700982 getDispatcher()->notifySwitch(when, switchCode, switchValue, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -0700983}
984
985int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
986 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
987}
988
989
990// --- KeyboardInputMapper ---
991
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800992KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
Jeff Brownefd32662011-03-08 15:13:06 -0800993 uint32_t source, int32_t keyboardType) :
994 InputMapper(device), mSource(source),
Jeff Brown6d0fec22010-07-23 21:28:06 -0700995 mKeyboardType(keyboardType) {
Jeff Brown6328cdc2010-07-29 18:18:33 -0700996 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -0700997}
998
999KeyboardInputMapper::~KeyboardInputMapper() {
1000}
1001
Jeff Brown6328cdc2010-07-29 18:18:33 -07001002void KeyboardInputMapper::initializeLocked() {
1003 mLocked.metaState = AMETA_NONE;
1004 mLocked.downTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001005}
1006
1007uint32_t KeyboardInputMapper::getSources() {
Jeff Brownefd32662011-03-08 15:13:06 -08001008 return mSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001009}
1010
1011void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1012 InputMapper::populateDeviceInfo(info);
1013
1014 info->setKeyboardType(mKeyboardType);
1015}
1016
Jeff Brownef3d7e82010-09-30 14:33:04 -07001017void KeyboardInputMapper::dump(String8& dump) {
1018 { // acquire lock
1019 AutoMutex _l(mLock);
1020 dump.append(INDENT2 "Keyboard Input Mapper:\n");
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001021 dumpParameters(dump);
Jeff Brownef3d7e82010-09-30 14:33:04 -07001022 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
1023 dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mLocked.keyDowns.size());
1024 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mLocked.metaState);
1025 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
1026 } // release lock
1027}
1028
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001029
1030void KeyboardInputMapper::configure() {
1031 InputMapper::configure();
1032
1033 // Configure basic parameters.
1034 configureParameters();
Jeff Brown49ed71d2010-12-06 17:13:33 -08001035
1036 // Reset LEDs.
1037 {
1038 AutoMutex _l(mLock);
1039 resetLedStateLocked();
1040 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001041}
1042
1043void KeyboardInputMapper::configureParameters() {
1044 mParameters.orientationAware = false;
1045 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
1046 mParameters.orientationAware);
1047
1048 mParameters.associatedDisplayId = mParameters.orientationAware ? 0 : -1;
1049}
1050
1051void KeyboardInputMapper::dumpParameters(String8& dump) {
1052 dump.append(INDENT3 "Parameters:\n");
1053 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1054 mParameters.associatedDisplayId);
1055 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1056 toString(mParameters.orientationAware));
1057}
1058
Jeff Brown6d0fec22010-07-23 21:28:06 -07001059void KeyboardInputMapper::reset() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001060 for (;;) {
1061 int32_t keyCode, scanCode;
1062 { // acquire lock
1063 AutoMutex _l(mLock);
1064
1065 // Synthesize key up event on reset if keys are currently down.
1066 if (mLocked.keyDowns.isEmpty()) {
1067 initializeLocked();
Jeff Brown49ed71d2010-12-06 17:13:33 -08001068 resetLedStateLocked();
Jeff Brown6328cdc2010-07-29 18:18:33 -07001069 break; // done
1070 }
1071
1072 const KeyDown& keyDown = mLocked.keyDowns.top();
1073 keyCode = keyDown.keyCode;
1074 scanCode = keyDown.scanCode;
1075 } // release lock
1076
Jeff Brown6d0fec22010-07-23 21:28:06 -07001077 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown6328cdc2010-07-29 18:18:33 -07001078 processKey(when, false, keyCode, scanCode, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001079 }
1080
1081 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001082 getContext()->updateGlobalMetaState();
1083}
1084
1085void KeyboardInputMapper::process(const RawEvent* rawEvent) {
1086 switch (rawEvent->type) {
1087 case EV_KEY: {
1088 int32_t scanCode = rawEvent->scanCode;
1089 if (isKeyboardOrGamepadKey(scanCode)) {
1090 processKey(rawEvent->when, rawEvent->value != 0, rawEvent->keyCode, scanCode,
1091 rawEvent->flags);
1092 }
1093 break;
1094 }
1095 }
1096}
1097
1098bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
1099 return scanCode < BTN_MOUSE
1100 || scanCode >= KEY_OK
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001101 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
Jeff Browncb1404e2011-01-15 18:14:15 -08001102 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001103}
1104
Jeff Brown6328cdc2010-07-29 18:18:33 -07001105void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode,
1106 int32_t scanCode, uint32_t policyFlags) {
1107 int32_t newMetaState;
1108 nsecs_t downTime;
1109 bool metaStateChanged = false;
1110
1111 { // acquire lock
1112 AutoMutex _l(mLock);
1113
1114 if (down) {
1115 // Rotate key codes according to orientation if needed.
1116 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001117 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001118 int32_t orientation;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001119 if (!getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1120 NULL, NULL, & orientation)) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001121 orientation = DISPLAY_ORIENTATION_0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001122 }
1123
1124 keyCode = rotateKeyCode(keyCode, orientation);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001125 }
1126
Jeff Brown6328cdc2010-07-29 18:18:33 -07001127 // Add key down.
1128 ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1129 if (keyDownIndex >= 0) {
1130 // key repeat, be sure to use same keycode as before in case of rotation
Jeff Brown6b53e8d2010-11-10 16:03:06 -08001131 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001132 } else {
1133 // key down
Jeff Brownfe508922011-01-18 15:10:10 -08001134 if ((policyFlags & POLICY_FLAG_VIRTUAL)
1135 && mContext->shouldDropVirtualKey(when,
1136 getDevice(), keyCode, scanCode)) {
1137 return;
1138 }
1139
Jeff Brown6328cdc2010-07-29 18:18:33 -07001140 mLocked.keyDowns.push();
1141 KeyDown& keyDown = mLocked.keyDowns.editTop();
1142 keyDown.keyCode = keyCode;
1143 keyDown.scanCode = scanCode;
1144 }
1145
1146 mLocked.downTime = when;
1147 } else {
1148 // Remove key down.
1149 ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1150 if (keyDownIndex >= 0) {
1151 // key up, be sure to use same keycode as before in case of rotation
Jeff Brown6b53e8d2010-11-10 16:03:06 -08001152 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001153 mLocked.keyDowns.removeAt(size_t(keyDownIndex));
1154 } else {
1155 // key was not actually down
1156 LOGI("Dropping key up from device %s because the key was not down. "
1157 "keyCode=%d, scanCode=%d",
1158 getDeviceName().string(), keyCode, scanCode);
1159 return;
1160 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001161 }
1162
Jeff Brown6328cdc2010-07-29 18:18:33 -07001163 int32_t oldMetaState = mLocked.metaState;
1164 newMetaState = updateMetaState(keyCode, down, oldMetaState);
1165 if (oldMetaState != newMetaState) {
1166 mLocked.metaState = newMetaState;
1167 metaStateChanged = true;
Jeff Brown497a92c2010-09-12 17:55:08 -07001168 updateLedStateLocked(false);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001169 }
Jeff Brownfd0358292010-06-30 16:10:35 -07001170
Jeff Brown6328cdc2010-07-29 18:18:33 -07001171 downTime = mLocked.downTime;
1172 } // release lock
1173
Jeff Brown56194eb2011-03-02 19:23:13 -08001174 // Key down on external an keyboard should wake the device.
1175 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
1176 // For internal keyboards, the key layout file should specify the policy flags for
1177 // each wake key individually.
1178 // TODO: Use the input device configuration to control this behavior more finely.
1179 if (down && getDevice()->isExternal()
1180 && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) {
1181 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1182 }
1183
Jeff Brown6328cdc2010-07-29 18:18:33 -07001184 if (metaStateChanged) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001185 getContext()->updateGlobalMetaState();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001186 }
1187
Jeff Brown05dc66a2011-03-02 14:41:58 -08001188 if (down && !isMetaKey(keyCode)) {
1189 getContext()->fadePointer();
1190 }
1191
Jeff Brownefd32662011-03-08 15:13:06 -08001192 getDispatcher()->notifyKey(when, getDeviceId(), mSource, policyFlags,
Jeff Brownb6997262010-10-08 22:31:17 -07001193 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
1194 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001195}
1196
Jeff Brown6328cdc2010-07-29 18:18:33 -07001197ssize_t KeyboardInputMapper::findKeyDownLocked(int32_t scanCode) {
1198 size_t n = mLocked.keyDowns.size();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001199 for (size_t i = 0; i < n; i++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001200 if (mLocked.keyDowns[i].scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001201 return i;
1202 }
1203 }
1204 return -1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001205}
1206
Jeff Brown6d0fec22010-07-23 21:28:06 -07001207int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1208 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
1209}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001210
Jeff Brown6d0fec22010-07-23 21:28:06 -07001211int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1212 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1213}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001214
Jeff Brown6d0fec22010-07-23 21:28:06 -07001215bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1216 const int32_t* keyCodes, uint8_t* outFlags) {
1217 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
1218}
1219
1220int32_t KeyboardInputMapper::getMetaState() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001221 { // acquire lock
1222 AutoMutex _l(mLock);
1223 return mLocked.metaState;
1224 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001225}
1226
Jeff Brown49ed71d2010-12-06 17:13:33 -08001227void KeyboardInputMapper::resetLedStateLocked() {
1228 initializeLedStateLocked(mLocked.capsLockLedState, LED_CAPSL);
1229 initializeLedStateLocked(mLocked.numLockLedState, LED_NUML);
1230 initializeLedStateLocked(mLocked.scrollLockLedState, LED_SCROLLL);
1231
1232 updateLedStateLocked(true);
1233}
1234
1235void KeyboardInputMapper::initializeLedStateLocked(LockedState::LedState& ledState, int32_t led) {
1236 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
1237 ledState.on = false;
1238}
1239
Jeff Brown497a92c2010-09-12 17:55:08 -07001240void KeyboardInputMapper::updateLedStateLocked(bool reset) {
1241 updateLedStateForModifierLocked(mLocked.capsLockLedState, LED_CAPSL,
Jeff Brown51e7fe752010-10-29 22:19:53 -07001242 AMETA_CAPS_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001243 updateLedStateForModifierLocked(mLocked.numLockLedState, LED_NUML,
Jeff Brown51e7fe752010-10-29 22:19:53 -07001244 AMETA_NUM_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001245 updateLedStateForModifierLocked(mLocked.scrollLockLedState, LED_SCROLLL,
Jeff Brown51e7fe752010-10-29 22:19:53 -07001246 AMETA_SCROLL_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001247}
1248
1249void KeyboardInputMapper::updateLedStateForModifierLocked(LockedState::LedState& ledState,
1250 int32_t led, int32_t modifier, bool reset) {
1251 if (ledState.avail) {
1252 bool desiredState = (mLocked.metaState & modifier) != 0;
Jeff Brown49ed71d2010-12-06 17:13:33 -08001253 if (reset || ledState.on != desiredState) {
Jeff Brown497a92c2010-09-12 17:55:08 -07001254 getEventHub()->setLedState(getDeviceId(), led, desiredState);
1255 ledState.on = desiredState;
1256 }
1257 }
1258}
1259
Jeff Brown6d0fec22010-07-23 21:28:06 -07001260
Jeff Brown83c09682010-12-23 17:50:18 -08001261// --- CursorInputMapper ---
Jeff Brown6d0fec22010-07-23 21:28:06 -07001262
Jeff Brown83c09682010-12-23 17:50:18 -08001263CursorInputMapper::CursorInputMapper(InputDevice* device) :
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001264 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001265 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001266}
1267
Jeff Brown83c09682010-12-23 17:50:18 -08001268CursorInputMapper::~CursorInputMapper() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001269}
1270
Jeff Brown83c09682010-12-23 17:50:18 -08001271uint32_t CursorInputMapper::getSources() {
Jeff Brownefd32662011-03-08 15:13:06 -08001272 return mSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001273}
1274
Jeff Brown83c09682010-12-23 17:50:18 -08001275void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001276 InputMapper::populateDeviceInfo(info);
1277
Jeff Brown83c09682010-12-23 17:50:18 -08001278 if (mParameters.mode == Parameters::MODE_POINTER) {
1279 float minX, minY, maxX, maxY;
1280 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
Jeff Brownefd32662011-03-08 15:13:06 -08001281 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f);
1282 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f);
Jeff Brown83c09682010-12-23 17:50:18 -08001283 }
1284 } else {
Jeff Brownefd32662011-03-08 15:13:06 -08001285 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale);
1286 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale);
Jeff Brown83c09682010-12-23 17:50:18 -08001287 }
Jeff Brownefd32662011-03-08 15:13:06 -08001288 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001289
1290 if (mHaveVWheel) {
Jeff Brownefd32662011-03-08 15:13:06 -08001291 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001292 }
1293 if (mHaveHWheel) {
Jeff Brownefd32662011-03-08 15:13:06 -08001294 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001295 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001296}
1297
Jeff Brown83c09682010-12-23 17:50:18 -08001298void CursorInputMapper::dump(String8& dump) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07001299 { // acquire lock
1300 AutoMutex _l(mLock);
Jeff Brown83c09682010-12-23 17:50:18 -08001301 dump.append(INDENT2 "Cursor Input Mapper:\n");
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001302 dumpParameters(dump);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001303 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
1304 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
Jeff Brownef3d7e82010-09-30 14:33:04 -07001305 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
1306 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001307 dump.appendFormat(INDENT3 "HaveVWheel: %s\n", toString(mHaveVWheel));
1308 dump.appendFormat(INDENT3 "HaveHWheel: %s\n", toString(mHaveHWheel));
1309 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
1310 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001311 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mLocked.buttonState);
1312 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mLocked.buttonState)));
Jeff Brownef3d7e82010-09-30 14:33:04 -07001313 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
1314 } // release lock
1315}
1316
Jeff Brown83c09682010-12-23 17:50:18 -08001317void CursorInputMapper::configure() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001318 InputMapper::configure();
1319
1320 // Configure basic parameters.
1321 configureParameters();
Jeff Brown83c09682010-12-23 17:50:18 -08001322
1323 // Configure device mode.
1324 switch (mParameters.mode) {
1325 case Parameters::MODE_POINTER:
Jeff Brownefd32662011-03-08 15:13:06 -08001326 mSource = AINPUT_SOURCE_MOUSE;
Jeff Brown83c09682010-12-23 17:50:18 -08001327 mXPrecision = 1.0f;
1328 mYPrecision = 1.0f;
1329 mXScale = 1.0f;
1330 mYScale = 1.0f;
1331 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
1332 break;
1333 case Parameters::MODE_NAVIGATION:
Jeff Brownefd32662011-03-08 15:13:06 -08001334 mSource = AINPUT_SOURCE_TRACKBALL;
Jeff Brown83c09682010-12-23 17:50:18 -08001335 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1336 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1337 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1338 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1339 break;
1340 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08001341
1342 mVWheelScale = 1.0f;
1343 mHWheelScale = 1.0f;
Jeff Browncc0c1592011-02-19 05:07:28 -08001344
1345 mHaveVWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_WHEEL);
1346 mHaveHWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_HWHEEL);
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001347}
1348
Jeff Brown83c09682010-12-23 17:50:18 -08001349void CursorInputMapper::configureParameters() {
1350 mParameters.mode = Parameters::MODE_POINTER;
1351 String8 cursorModeString;
1352 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
1353 if (cursorModeString == "navigation") {
1354 mParameters.mode = Parameters::MODE_NAVIGATION;
1355 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
1356 LOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
1357 }
1358 }
1359
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001360 mParameters.orientationAware = false;
Jeff Brown83c09682010-12-23 17:50:18 -08001361 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001362 mParameters.orientationAware);
1363
Jeff Brown83c09682010-12-23 17:50:18 -08001364 mParameters.associatedDisplayId = mParameters.mode == Parameters::MODE_POINTER
1365 || mParameters.orientationAware ? 0 : -1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001366}
1367
Jeff Brown83c09682010-12-23 17:50:18 -08001368void CursorInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001369 dump.append(INDENT3 "Parameters:\n");
1370 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1371 mParameters.associatedDisplayId);
Jeff Brown83c09682010-12-23 17:50:18 -08001372
1373 switch (mParameters.mode) {
1374 case Parameters::MODE_POINTER:
1375 dump.append(INDENT4 "Mode: pointer\n");
1376 break;
1377 case Parameters::MODE_NAVIGATION:
1378 dump.append(INDENT4 "Mode: navigation\n");
1379 break;
1380 default:
1381 assert(false);
1382 }
1383
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001384 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1385 toString(mParameters.orientationAware));
1386}
1387
Jeff Brown83c09682010-12-23 17:50:18 -08001388void CursorInputMapper::initializeLocked() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001389 mAccumulator.clear();
1390
Jeff Brownefd32662011-03-08 15:13:06 -08001391 mLocked.buttonState = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001392 mLocked.downTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001393}
1394
Jeff Brown83c09682010-12-23 17:50:18 -08001395void CursorInputMapper::reset() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001396 for (;;) {
Jeff Brownefd32662011-03-08 15:13:06 -08001397 uint32_t buttonState;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001398 { // acquire lock
1399 AutoMutex _l(mLock);
1400
Jeff Brownefd32662011-03-08 15:13:06 -08001401 buttonState = mLocked.buttonState;
1402 if (!buttonState) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001403 initializeLocked();
1404 break; // done
1405 }
1406 } // release lock
1407
Jeff Brown83c09682010-12-23 17:50:18 -08001408 // Synthesize button up event on reset.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001409 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brownefd32662011-03-08 15:13:06 -08001410 mAccumulator.clear();
1411 mAccumulator.buttonDown = 0;
1412 mAccumulator.buttonUp = buttonState;
1413 mAccumulator.fields = Accumulator::FIELD_BUTTONS;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001414 sync(when);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001415 }
1416
Jeff Brown6d0fec22010-07-23 21:28:06 -07001417 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001418}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001419
Jeff Brown83c09682010-12-23 17:50:18 -08001420void CursorInputMapper::process(const RawEvent* rawEvent) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001421 switch (rawEvent->type) {
Jeff Brownefd32662011-03-08 15:13:06 -08001422 case EV_KEY: {
1423 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
1424 if (buttonState) {
1425 if (rawEvent->value) {
1426 mAccumulator.buttonDown = buttonState;
1427 mAccumulator.buttonUp = 0;
1428 } else {
1429 mAccumulator.buttonDown = 0;
1430 mAccumulator.buttonUp = buttonState;
1431 }
1432 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
1433
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001434 // Sync now since BTN_MOUSE is not necessarily followed by SYN_REPORT and
1435 // we need to ensure that we report the up/down promptly.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001436 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001437 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001438 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001439 break;
Jeff Brownefd32662011-03-08 15:13:06 -08001440 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001441
Jeff Brown6d0fec22010-07-23 21:28:06 -07001442 case EV_REL:
1443 switch (rawEvent->scanCode) {
1444 case REL_X:
1445 mAccumulator.fields |= Accumulator::FIELD_REL_X;
1446 mAccumulator.relX = rawEvent->value;
1447 break;
1448 case REL_Y:
1449 mAccumulator.fields |= Accumulator::FIELD_REL_Y;
1450 mAccumulator.relY = rawEvent->value;
1451 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001452 case REL_WHEEL:
1453 mAccumulator.fields |= Accumulator::FIELD_REL_WHEEL;
1454 mAccumulator.relWheel = rawEvent->value;
1455 break;
1456 case REL_HWHEEL:
1457 mAccumulator.fields |= Accumulator::FIELD_REL_HWHEEL;
1458 mAccumulator.relHWheel = rawEvent->value;
1459 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001460 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001461 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001462
Jeff Brown6d0fec22010-07-23 21:28:06 -07001463 case EV_SYN:
1464 switch (rawEvent->scanCode) {
1465 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001466 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001467 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001468 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001469 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001470 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001471}
1472
Jeff Brown83c09682010-12-23 17:50:18 -08001473void CursorInputMapper::sync(nsecs_t when) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001474 uint32_t fields = mAccumulator.fields;
1475 if (fields == 0) {
1476 return; // no new state changes, so nothing to do
1477 }
1478
Jeff Brown9626b142011-03-03 02:09:54 -08001479 int32_t motionEventAction;
1480 int32_t motionEventEdgeFlags;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001481 PointerCoords pointerCoords;
1482 nsecs_t downTime;
Jeff Brown33bbfd22011-02-24 20:55:35 -08001483 float vscroll, hscroll;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001484 { // acquire lock
1485 AutoMutex _l(mLock);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001486
Jeff Brownefd32662011-03-08 15:13:06 -08001487 bool down, downChanged;
1488 bool wasDown = isPointerDown(mLocked.buttonState);
1489 bool buttonsChanged = fields & Accumulator::FIELD_BUTTONS;
1490 if (buttonsChanged) {
1491 mLocked.buttonState = (mLocked.buttonState | mAccumulator.buttonDown)
1492 & ~mAccumulator.buttonUp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001493
Jeff Brownefd32662011-03-08 15:13:06 -08001494 down = isPointerDown(mLocked.buttonState);
1495
1496 if (!wasDown && down) {
1497 mLocked.downTime = when;
1498 downChanged = true;
1499 } else if (wasDown && !down) {
1500 downChanged = true;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001501 } else {
Jeff Brownefd32662011-03-08 15:13:06 -08001502 downChanged = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001503 }
Jeff Brownefd32662011-03-08 15:13:06 -08001504 } else {
1505 down = wasDown;
1506 downChanged = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001507 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001508
Jeff Brown6328cdc2010-07-29 18:18:33 -07001509 downTime = mLocked.downTime;
Jeff Brown83c09682010-12-23 17:50:18 -08001510 float deltaX = fields & Accumulator::FIELD_REL_X ? mAccumulator.relX * mXScale : 0.0f;
1511 float deltaY = fields & Accumulator::FIELD_REL_Y ? mAccumulator.relY * mYScale : 0.0f;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001512
Jeff Brown6328cdc2010-07-29 18:18:33 -07001513 if (downChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08001514 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
1515 } else if (down || mPointerController == NULL) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001516 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
Jeff Browncc0c1592011-02-19 05:07:28 -08001517 } else {
1518 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001519 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001520
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001521 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0
Jeff Brown83c09682010-12-23 17:50:18 -08001522 && (deltaX != 0.0f || deltaY != 0.0f)) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001523 // Rotate motion based on display orientation if needed.
1524 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
1525 int32_t orientation;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001526 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1527 NULL, NULL, & orientation)) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001528 orientation = DISPLAY_ORIENTATION_0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001529 }
1530
1531 float temp;
1532 switch (orientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001533 case DISPLAY_ORIENTATION_90:
Jeff Brown83c09682010-12-23 17:50:18 -08001534 temp = deltaX;
1535 deltaX = deltaY;
1536 deltaY = -temp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001537 break;
1538
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001539 case DISPLAY_ORIENTATION_180:
Jeff Brown83c09682010-12-23 17:50:18 -08001540 deltaX = -deltaX;
1541 deltaY = -deltaY;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001542 break;
1543
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001544 case DISPLAY_ORIENTATION_270:
Jeff Brown83c09682010-12-23 17:50:18 -08001545 temp = deltaX;
1546 deltaX = -deltaY;
1547 deltaY = temp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001548 break;
1549 }
1550 }
Jeff Brown83c09682010-12-23 17:50:18 -08001551
Jeff Brown91c69ab2011-02-14 17:03:18 -08001552 pointerCoords.clear();
1553
Jeff Brown9626b142011-03-03 02:09:54 -08001554 motionEventEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
1555
Jeff Brown83c09682010-12-23 17:50:18 -08001556 if (mPointerController != NULL) {
1557 mPointerController->move(deltaX, deltaY);
Jeff Brownefd32662011-03-08 15:13:06 -08001558 if (buttonsChanged) {
1559 mPointerController->setButtonState(mLocked.buttonState);
Jeff Brown83c09682010-12-23 17:50:18 -08001560 }
Jeff Brownefd32662011-03-08 15:13:06 -08001561
Jeff Brown91c69ab2011-02-14 17:03:18 -08001562 float x, y;
1563 mPointerController->getPosition(&x, &y);
Jeff Brownebbd5d12011-02-17 13:01:34 -08001564 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
1565 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jeff Brown9626b142011-03-03 02:09:54 -08001566
1567 if (motionEventAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownefd32662011-03-08 15:13:06 -08001568 motionEventEdgeFlags = calculateEdgeFlagsUsingPointerBounds(
1569 mPointerController, x, y);
Jeff Brown9626b142011-03-03 02:09:54 -08001570 }
Jeff Brown83c09682010-12-23 17:50:18 -08001571 } else {
Jeff Brownebbd5d12011-02-17 13:01:34 -08001572 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
1573 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
Jeff Brown83c09682010-12-23 17:50:18 -08001574 }
1575
Jeff Brownefd32662011-03-08 15:13:06 -08001576 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001577
1578 if (mHaveVWheel && (fields & Accumulator::FIELD_REL_WHEEL)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001579 vscroll = mAccumulator.relWheel;
1580 } else {
1581 vscroll = 0;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001582 }
1583 if (mHaveHWheel && (fields & Accumulator::FIELD_REL_HWHEEL)) {
Jeff Brown33bbfd22011-02-24 20:55:35 -08001584 hscroll = mAccumulator.relHWheel;
1585 } else {
1586 hscroll = 0;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001587 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001588 if (hscroll != 0 || vscroll != 0) {
1589 mPointerController->unfade();
1590 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001591 } // release lock
1592
Jeff Brown56194eb2011-03-02 19:23:13 -08001593 // Moving an external trackball or mouse should wake the device.
1594 // We don't do this for internal cursor devices to prevent them from waking up
1595 // the device in your pocket.
1596 // TODO: Use the input device configuration to control this behavior more finely.
1597 uint32_t policyFlags = 0;
1598 if (getDevice()->isExternal()) {
1599 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1600 }
1601
Jeff Brown6d0fec22010-07-23 21:28:06 -07001602 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown6328cdc2010-07-29 18:18:33 -07001603 int32_t pointerId = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08001604 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brown9626b142011-03-03 02:09:54 -08001605 motionEventAction, 0, metaState, motionEventEdgeFlags,
Jeff Brownb6997262010-10-08 22:31:17 -07001606 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1607
1608 mAccumulator.clear();
Jeff Brown33bbfd22011-02-24 20:55:35 -08001609
1610 if (vscroll != 0 || hscroll != 0) {
1611 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
1612 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
1613
Jeff Brownefd32662011-03-08 15:13:06 -08001614 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brown33bbfd22011-02-24 20:55:35 -08001615 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
1616 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1617 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001618}
1619
Jeff Brown83c09682010-12-23 17:50:18 -08001620int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brownc3fc2d02010-08-10 15:47:53 -07001621 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
1622 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1623 } else {
1624 return AKEY_STATE_UNKNOWN;
1625 }
1626}
1627
Jeff Brown05dc66a2011-03-02 14:41:58 -08001628void CursorInputMapper::fadePointer() {
1629 { // acquire lock
1630 AutoMutex _l(mLock);
Jeff Brownefd32662011-03-08 15:13:06 -08001631 if (mPointerController != NULL) {
1632 mPointerController->fade();
1633 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001634 } // release lock
1635}
1636
Jeff Brown6d0fec22010-07-23 21:28:06 -07001637
1638// --- TouchInputMapper ---
1639
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001640TouchInputMapper::TouchInputMapper(InputDevice* device) :
1641 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001642 mLocked.surfaceOrientation = -1;
1643 mLocked.surfaceWidth = -1;
1644 mLocked.surfaceHeight = -1;
1645
1646 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001647}
1648
1649TouchInputMapper::~TouchInputMapper() {
1650}
1651
1652uint32_t TouchInputMapper::getSources() {
Jeff Brown96ad3972011-03-09 17:39:48 -08001653 return mTouchSource | mPointerSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001654}
1655
1656void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1657 InputMapper::populateDeviceInfo(info);
1658
Jeff Brown6328cdc2010-07-29 18:18:33 -07001659 { // acquire lock
1660 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001661
Jeff Brown6328cdc2010-07-29 18:18:33 -07001662 // Ensure surface information is up to date so that orientation changes are
1663 // noticed immediately.
Jeff Brownefd32662011-03-08 15:13:06 -08001664 if (!configureSurfaceLocked()) {
1665 return;
1666 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001667
Jeff Brownefd32662011-03-08 15:13:06 -08001668 info->addMotionRange(mLocked.orientedRanges.x);
1669 info->addMotionRange(mLocked.orientedRanges.y);
Jeff Brown8d608662010-08-30 03:02:23 -07001670
1671 if (mLocked.orientedRanges.havePressure) {
Jeff Brownefd32662011-03-08 15:13:06 -08001672 info->addMotionRange(mLocked.orientedRanges.pressure);
Jeff Brown8d608662010-08-30 03:02:23 -07001673 }
1674
1675 if (mLocked.orientedRanges.haveSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001676 info->addMotionRange(mLocked.orientedRanges.size);
Jeff Brown8d608662010-08-30 03:02:23 -07001677 }
1678
Jeff Brownc6d282b2010-10-14 21:42:15 -07001679 if (mLocked.orientedRanges.haveTouchSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001680 info->addMotionRange(mLocked.orientedRanges.touchMajor);
1681 info->addMotionRange(mLocked.orientedRanges.touchMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001682 }
1683
Jeff Brownc6d282b2010-10-14 21:42:15 -07001684 if (mLocked.orientedRanges.haveToolSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001685 info->addMotionRange(mLocked.orientedRanges.toolMajor);
1686 info->addMotionRange(mLocked.orientedRanges.toolMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001687 }
1688
1689 if (mLocked.orientedRanges.haveOrientation) {
Jeff Brownefd32662011-03-08 15:13:06 -08001690 info->addMotionRange(mLocked.orientedRanges.orientation);
Jeff Brown8d608662010-08-30 03:02:23 -07001691 }
Jeff Brown96ad3972011-03-09 17:39:48 -08001692
1693 if (mPointerController != NULL) {
1694 float minX, minY, maxX, maxY;
1695 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
1696 info->addMotionRange(AMOTION_EVENT_AXIS_X, mPointerSource,
1697 minX, maxX, 0.0f, 0.0f);
1698 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mPointerSource,
1699 minY, maxY, 0.0f, 0.0f);
1700 }
1701 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mPointerSource,
1702 0.0f, 1.0f, 0.0f, 0.0f);
1703 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001704 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001705}
1706
Jeff Brownef3d7e82010-09-30 14:33:04 -07001707void TouchInputMapper::dump(String8& dump) {
1708 { // acquire lock
1709 AutoMutex _l(mLock);
1710 dump.append(INDENT2 "Touch Input Mapper:\n");
Jeff Brownef3d7e82010-09-30 14:33:04 -07001711 dumpParameters(dump);
1712 dumpVirtualKeysLocked(dump);
1713 dumpRawAxes(dump);
1714 dumpCalibration(dump);
1715 dumpSurfaceLocked(dump);
Jeff Brownefd32662011-03-08 15:13:06 -08001716
Jeff Brown511ee5f2010-10-18 13:32:20 -07001717 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
Jeff Brownc6d282b2010-10-14 21:42:15 -07001718 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mLocked.xScale);
1719 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mLocked.yScale);
1720 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mLocked.xPrecision);
1721 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mLocked.yPrecision);
1722 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mLocked.geometricScale);
1723 dump.appendFormat(INDENT4 "ToolSizeLinearScale: %0.3f\n", mLocked.toolSizeLinearScale);
1724 dump.appendFormat(INDENT4 "ToolSizeLinearBias: %0.3f\n", mLocked.toolSizeLinearBias);
1725 dump.appendFormat(INDENT4 "ToolSizeAreaScale: %0.3f\n", mLocked.toolSizeAreaScale);
1726 dump.appendFormat(INDENT4 "ToolSizeAreaBias: %0.3f\n", mLocked.toolSizeAreaBias);
1727 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mLocked.pressureScale);
1728 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mLocked.sizeScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001729 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mLocked.orientationScale);
1730
1731 dump.appendFormat(INDENT3 "Last Touch:\n");
1732 dump.appendFormat(INDENT4 "Pointer Count: %d\n", mLastTouch.pointerCount);
Jeff Brown96ad3972011-03-09 17:39:48 -08001733 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", mLastTouch.buttonState);
1734
1735 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
1736 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
1737 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
1738 mLocked.pointerGestureXMovementScale);
1739 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
1740 mLocked.pointerGestureYMovementScale);
1741 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
1742 mLocked.pointerGestureXZoomScale);
1743 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
1744 mLocked.pointerGestureYZoomScale);
1745 dump.appendFormat(INDENT4 "MaxSwipeWidthSquared: %d\n",
1746 mLocked.pointerGestureMaxSwipeWidthSquared);
1747 }
Jeff Brownef3d7e82010-09-30 14:33:04 -07001748 } // release lock
1749}
1750
Jeff Brown6328cdc2010-07-29 18:18:33 -07001751void TouchInputMapper::initializeLocked() {
1752 mCurrentTouch.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001753 mLastTouch.clear();
1754 mDownTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001755
1756 for (uint32_t i = 0; i < MAX_POINTERS; i++) {
1757 mAveragingTouchFilter.historyStart[i] = 0;
1758 mAveragingTouchFilter.historyEnd[i] = 0;
1759 }
1760
1761 mJumpyTouchFilter.jumpyPointsDropped = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001762
1763 mLocked.currentVirtualKey.down = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001764
1765 mLocked.orientedRanges.havePressure = false;
1766 mLocked.orientedRanges.haveSize = false;
Jeff Brownc6d282b2010-10-14 21:42:15 -07001767 mLocked.orientedRanges.haveTouchSize = false;
1768 mLocked.orientedRanges.haveToolSize = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001769 mLocked.orientedRanges.haveOrientation = false;
Jeff Brown96ad3972011-03-09 17:39:48 -08001770
1771 mPointerGesture.reset();
Jeff Brown8d608662010-08-30 03:02:23 -07001772}
1773
Jeff Brown6d0fec22010-07-23 21:28:06 -07001774void TouchInputMapper::configure() {
1775 InputMapper::configure();
1776
1777 // Configure basic parameters.
Jeff Brown8d608662010-08-30 03:02:23 -07001778 configureParameters();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001779
Jeff Brown83c09682010-12-23 17:50:18 -08001780 // Configure sources.
1781 switch (mParameters.deviceType) {
1782 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Jeff Brownefd32662011-03-08 15:13:06 -08001783 mTouchSource = AINPUT_SOURCE_TOUCHSCREEN;
Jeff Brown96ad3972011-03-09 17:39:48 -08001784 mPointerSource = 0;
Jeff Brown83c09682010-12-23 17:50:18 -08001785 break;
1786 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Jeff Brownefd32662011-03-08 15:13:06 -08001787 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
Jeff Brown96ad3972011-03-09 17:39:48 -08001788 mPointerSource = 0;
1789 break;
1790 case Parameters::DEVICE_TYPE_POINTER:
1791 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
1792 mPointerSource = AINPUT_SOURCE_MOUSE;
Jeff Brown83c09682010-12-23 17:50:18 -08001793 break;
1794 default:
1795 assert(false);
1796 }
1797
Jeff Brown6d0fec22010-07-23 21:28:06 -07001798 // Configure absolute axis information.
Jeff Brown8d608662010-08-30 03:02:23 -07001799 configureRawAxes();
Jeff Brown8d608662010-08-30 03:02:23 -07001800
1801 // Prepare input device calibration.
1802 parseCalibration();
1803 resolveCalibration();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001804
Jeff Brown6328cdc2010-07-29 18:18:33 -07001805 { // acquire lock
1806 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001807
Jeff Brown8d608662010-08-30 03:02:23 -07001808 // Configure surface dimensions and orientation.
Jeff Brown6328cdc2010-07-29 18:18:33 -07001809 configureSurfaceLocked();
1810 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001811}
1812
Jeff Brown8d608662010-08-30 03:02:23 -07001813void TouchInputMapper::configureParameters() {
1814 mParameters.useBadTouchFilter = getPolicy()->filterTouchEvents();
1815 mParameters.useAveragingTouchFilter = getPolicy()->filterTouchEvents();
1816 mParameters.useJumpyTouchFilter = getPolicy()->filterJumpyTouchEvents();
Jeff Brownfe508922011-01-18 15:10:10 -08001817 mParameters.virtualKeyQuietTime = getPolicy()->getVirtualKeyQuietTime();
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001818
Jeff Brown96ad3972011-03-09 17:39:48 -08001819 if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
1820 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
1821 // The device is a cursor device with a touch pad attached.
1822 // By default don't use the touch pad to move the pointer.
1823 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
1824 } else {
1825 // The device is just a touch pad.
1826 // By default use the touch pad to move the pointer and to perform related gestures.
1827 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
1828 }
1829
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001830 String8 deviceTypeString;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001831 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
1832 deviceTypeString)) {
Jeff Brown58a2da82011-01-25 16:02:22 -08001833 if (deviceTypeString == "touchScreen") {
1834 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brownefd32662011-03-08 15:13:06 -08001835 } else if (deviceTypeString == "touchPad") {
1836 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
Jeff Brown96ad3972011-03-09 17:39:48 -08001837 } else if (deviceTypeString == "pointer") {
1838 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
Jeff Brownefd32662011-03-08 15:13:06 -08001839 } else {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001840 LOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
1841 }
1842 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001843
Jeff Brownefd32662011-03-08 15:13:06 -08001844 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001845 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
1846 mParameters.orientationAware);
1847
Jeff Brownefd32662011-03-08 15:13:06 -08001848 mParameters.associatedDisplayId = mParameters.orientationAware
1849 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
Jeff Brown96ad3972011-03-09 17:39:48 -08001850 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
Jeff Brownefd32662011-03-08 15:13:06 -08001851 ? 0 : -1;
Jeff Brown8d608662010-08-30 03:02:23 -07001852}
1853
Jeff Brownef3d7e82010-09-30 14:33:04 -07001854void TouchInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001855 dump.append(INDENT3 "Parameters:\n");
1856
1857 switch (mParameters.deviceType) {
1858 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
1859 dump.append(INDENT4 "DeviceType: touchScreen\n");
1860 break;
1861 case Parameters::DEVICE_TYPE_TOUCH_PAD:
1862 dump.append(INDENT4 "DeviceType: touchPad\n");
1863 break;
Jeff Brown96ad3972011-03-09 17:39:48 -08001864 case Parameters::DEVICE_TYPE_POINTER:
1865 dump.append(INDENT4 "DeviceType: pointer\n");
1866 break;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001867 default:
1868 assert(false);
1869 }
1870
1871 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1872 mParameters.associatedDisplayId);
1873 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1874 toString(mParameters.orientationAware));
1875
1876 dump.appendFormat(INDENT4 "UseBadTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001877 toString(mParameters.useBadTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001878 dump.appendFormat(INDENT4 "UseAveragingTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001879 toString(mParameters.useAveragingTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001880 dump.appendFormat(INDENT4 "UseJumpyTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001881 toString(mParameters.useJumpyTouchFilter));
Jeff Brownb88102f2010-09-08 11:49:43 -07001882}
1883
Jeff Brown8d608662010-08-30 03:02:23 -07001884void TouchInputMapper::configureRawAxes() {
1885 mRawAxes.x.clear();
1886 mRawAxes.y.clear();
1887 mRawAxes.pressure.clear();
1888 mRawAxes.touchMajor.clear();
1889 mRawAxes.touchMinor.clear();
1890 mRawAxes.toolMajor.clear();
1891 mRawAxes.toolMinor.clear();
1892 mRawAxes.orientation.clear();
1893}
1894
Jeff Brownef3d7e82010-09-30 14:33:04 -07001895void TouchInputMapper::dumpRawAxes(String8& dump) {
1896 dump.append(INDENT3 "Raw Axes:\n");
Jeff Browncb1404e2011-01-15 18:14:15 -08001897 dumpRawAbsoluteAxisInfo(dump, mRawAxes.x, "X");
1898 dumpRawAbsoluteAxisInfo(dump, mRawAxes.y, "Y");
1899 dumpRawAbsoluteAxisInfo(dump, mRawAxes.pressure, "Pressure");
1900 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMajor, "TouchMajor");
1901 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMinor, "TouchMinor");
1902 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMajor, "ToolMajor");
1903 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMinor, "ToolMinor");
1904 dumpRawAbsoluteAxisInfo(dump, mRawAxes.orientation, "Orientation");
Jeff Brown6d0fec22010-07-23 21:28:06 -07001905}
1906
Jeff Brown6328cdc2010-07-29 18:18:33 -07001907bool TouchInputMapper::configureSurfaceLocked() {
Jeff Brown9626b142011-03-03 02:09:54 -08001908 // Ensure we have valid X and Y axes.
1909 if (!mRawAxes.x.valid || !mRawAxes.y.valid) {
1910 LOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
1911 "The device will be inoperable.", getDeviceName().string());
1912 return false;
1913 }
1914
Jeff Brown6d0fec22010-07-23 21:28:06 -07001915 // Update orientation and dimensions if needed.
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001916 int32_t orientation = DISPLAY_ORIENTATION_0;
Jeff Brown9626b142011-03-03 02:09:54 -08001917 int32_t width = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
1918 int32_t height = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001919
1920 if (mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001921 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001922 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
Jeff Brownefd32662011-03-08 15:13:06 -08001923 &mLocked.associatedDisplayWidth, &mLocked.associatedDisplayHeight,
1924 &mLocked.associatedDisplayOrientation)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001925 return false;
1926 }
Jeff Brownefd32662011-03-08 15:13:06 -08001927
1928 // A touch screen inherits the dimensions of the display.
1929 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
1930 width = mLocked.associatedDisplayWidth;
1931 height = mLocked.associatedDisplayHeight;
1932 }
1933
1934 // The device inherits the orientation of the display if it is orientation aware.
1935 if (mParameters.orientationAware) {
1936 orientation = mLocked.associatedDisplayOrientation;
1937 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001938 }
1939
Jeff Brown96ad3972011-03-09 17:39:48 -08001940 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
1941 && mPointerController == NULL) {
1942 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
1943 }
1944
Jeff Brown6328cdc2010-07-29 18:18:33 -07001945 bool orientationChanged = mLocked.surfaceOrientation != orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001946 if (orientationChanged) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001947 mLocked.surfaceOrientation = orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001948 }
1949
Jeff Brown6328cdc2010-07-29 18:18:33 -07001950 bool sizeChanged = mLocked.surfaceWidth != width || mLocked.surfaceHeight != height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001951 if (sizeChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08001952 LOGI("Device reconfigured: id=%d, name='%s', surface size is now %dx%d",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001953 getDeviceId(), getDeviceName().string(), width, height);
Jeff Brown8d608662010-08-30 03:02:23 -07001954
Jeff Brown6328cdc2010-07-29 18:18:33 -07001955 mLocked.surfaceWidth = width;
1956 mLocked.surfaceHeight = height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001957
Jeff Brown8d608662010-08-30 03:02:23 -07001958 // Configure X and Y factors.
Jeff Brown9626b142011-03-03 02:09:54 -08001959 mLocked.xScale = float(width) / (mRawAxes.x.maxValue - mRawAxes.x.minValue + 1);
1960 mLocked.yScale = float(height) / (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1);
1961 mLocked.xPrecision = 1.0f / mLocked.xScale;
1962 mLocked.yPrecision = 1.0f / mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001963
Jeff Brownefd32662011-03-08 15:13:06 -08001964 mLocked.orientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
1965 mLocked.orientedRanges.x.source = mTouchSource;
1966 mLocked.orientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
1967 mLocked.orientedRanges.y.source = mTouchSource;
1968
Jeff Brown9626b142011-03-03 02:09:54 -08001969 configureVirtualKeysLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001970
Jeff Brown8d608662010-08-30 03:02:23 -07001971 // Scale factor for terms that are not oriented in a particular axis.
1972 // If the pixels are square then xScale == yScale otherwise we fake it
1973 // by choosing an average.
1974 mLocked.geometricScale = avg(mLocked.xScale, mLocked.yScale);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001975
Jeff Brown8d608662010-08-30 03:02:23 -07001976 // Size of diagonal axis.
1977 float diagonalSize = pythag(width, height);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001978
Jeff Brown8d608662010-08-30 03:02:23 -07001979 // TouchMajor and TouchMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07001980 if (mCalibration.touchSizeCalibration != Calibration::TOUCH_SIZE_CALIBRATION_NONE) {
1981 mLocked.orientedRanges.haveTouchSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08001982
1983 mLocked.orientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
1984 mLocked.orientedRanges.touchMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07001985 mLocked.orientedRanges.touchMajor.min = 0;
1986 mLocked.orientedRanges.touchMajor.max = diagonalSize;
1987 mLocked.orientedRanges.touchMajor.flat = 0;
1988 mLocked.orientedRanges.touchMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08001989
Jeff Brown8d608662010-08-30 03:02:23 -07001990 mLocked.orientedRanges.touchMinor = mLocked.orientedRanges.touchMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08001991 mLocked.orientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07001992 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001993
Jeff Brown8d608662010-08-30 03:02:23 -07001994 // ToolMajor and ToolMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07001995 mLocked.toolSizeLinearScale = 0;
1996 mLocked.toolSizeLinearBias = 0;
1997 mLocked.toolSizeAreaScale = 0;
1998 mLocked.toolSizeAreaBias = 0;
1999 if (mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2000 if (mCalibration.toolSizeCalibration == Calibration::TOOL_SIZE_CALIBRATION_LINEAR) {
2001 if (mCalibration.haveToolSizeLinearScale) {
2002 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
Jeff Brown8d608662010-08-30 03:02:23 -07002003 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002004 mLocked.toolSizeLinearScale = float(min(width, height))
Jeff Brown8d608662010-08-30 03:02:23 -07002005 / mRawAxes.toolMajor.maxValue;
2006 }
2007
Jeff Brownc6d282b2010-10-14 21:42:15 -07002008 if (mCalibration.haveToolSizeLinearBias) {
2009 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2010 }
2011 } else if (mCalibration.toolSizeCalibration ==
2012 Calibration::TOOL_SIZE_CALIBRATION_AREA) {
2013 if (mCalibration.haveToolSizeLinearScale) {
2014 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
2015 } else {
2016 mLocked.toolSizeLinearScale = min(width, height);
2017 }
2018
2019 if (mCalibration.haveToolSizeLinearBias) {
2020 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2021 }
2022
2023 if (mCalibration.haveToolSizeAreaScale) {
2024 mLocked.toolSizeAreaScale = mCalibration.toolSizeAreaScale;
2025 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2026 mLocked.toolSizeAreaScale = 1.0f / mRawAxes.toolMajor.maxValue;
2027 }
2028
2029 if (mCalibration.haveToolSizeAreaBias) {
2030 mLocked.toolSizeAreaBias = mCalibration.toolSizeAreaBias;
Jeff Brown8d608662010-08-30 03:02:23 -07002031 }
2032 }
2033
Jeff Brownc6d282b2010-10-14 21:42:15 -07002034 mLocked.orientedRanges.haveToolSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002035
2036 mLocked.orientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
2037 mLocked.orientedRanges.toolMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002038 mLocked.orientedRanges.toolMajor.min = 0;
2039 mLocked.orientedRanges.toolMajor.max = diagonalSize;
2040 mLocked.orientedRanges.toolMajor.flat = 0;
2041 mLocked.orientedRanges.toolMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08002042
Jeff Brown8d608662010-08-30 03:02:23 -07002043 mLocked.orientedRanges.toolMinor = mLocked.orientedRanges.toolMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08002044 mLocked.orientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002045 }
2046
2047 // Pressure factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002048 mLocked.pressureScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002049 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE) {
2050 RawAbsoluteAxisInfo rawPressureAxis;
2051 switch (mCalibration.pressureSource) {
2052 case Calibration::PRESSURE_SOURCE_PRESSURE:
2053 rawPressureAxis = mRawAxes.pressure;
2054 break;
2055 case Calibration::PRESSURE_SOURCE_TOUCH:
2056 rawPressureAxis = mRawAxes.touchMajor;
2057 break;
2058 default:
2059 rawPressureAxis.clear();
2060 }
2061
Jeff Brown8d608662010-08-30 03:02:23 -07002062 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
2063 || mCalibration.pressureCalibration
2064 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
2065 if (mCalibration.havePressureScale) {
2066 mLocked.pressureScale = mCalibration.pressureScale;
2067 } else if (rawPressureAxis.valid && rawPressureAxis.maxValue != 0) {
2068 mLocked.pressureScale = 1.0f / rawPressureAxis.maxValue;
2069 }
2070 }
2071
2072 mLocked.orientedRanges.havePressure = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002073
2074 mLocked.orientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
2075 mLocked.orientedRanges.pressure.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002076 mLocked.orientedRanges.pressure.min = 0;
2077 mLocked.orientedRanges.pressure.max = 1.0;
2078 mLocked.orientedRanges.pressure.flat = 0;
2079 mLocked.orientedRanges.pressure.fuzz = 0;
2080 }
2081
2082 // Size factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002083 mLocked.sizeScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002084 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002085 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_NORMALIZED) {
2086 if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2087 mLocked.sizeScale = 1.0f / mRawAxes.toolMajor.maxValue;
2088 }
2089 }
2090
2091 mLocked.orientedRanges.haveSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002092
2093 mLocked.orientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
2094 mLocked.orientedRanges.size.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002095 mLocked.orientedRanges.size.min = 0;
2096 mLocked.orientedRanges.size.max = 1.0;
2097 mLocked.orientedRanges.size.flat = 0;
2098 mLocked.orientedRanges.size.fuzz = 0;
2099 }
2100
2101 // Orientation
Jeff Brownc6d282b2010-10-14 21:42:15 -07002102 mLocked.orientationScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002103 if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002104 if (mCalibration.orientationCalibration
2105 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
2106 if (mRawAxes.orientation.valid && mRawAxes.orientation.maxValue != 0) {
2107 mLocked.orientationScale = float(M_PI_2) / mRawAxes.orientation.maxValue;
2108 }
2109 }
2110
Jeff Brownefd32662011-03-08 15:13:06 -08002111 mLocked.orientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
2112 mLocked.orientedRanges.orientation.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002113 mLocked.orientedRanges.orientation.min = - M_PI_2;
2114 mLocked.orientedRanges.orientation.max = M_PI_2;
2115 mLocked.orientedRanges.orientation.flat = 0;
2116 mLocked.orientedRanges.orientation.fuzz = 0;
2117 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002118 }
2119
2120 if (orientationChanged || sizeChanged) {
Jeff Brown9626b142011-03-03 02:09:54 -08002121 // Compute oriented surface dimensions, precision, scales and ranges.
2122 // Note that the maximum value reported is an inclusive maximum value so it is one
2123 // unit less than the total width or height of surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002124 switch (mLocked.surfaceOrientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08002125 case DISPLAY_ORIENTATION_90:
2126 case DISPLAY_ORIENTATION_270:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002127 mLocked.orientedSurfaceWidth = mLocked.surfaceHeight;
2128 mLocked.orientedSurfaceHeight = mLocked.surfaceWidth;
Jeff Brown9626b142011-03-03 02:09:54 -08002129
Jeff Brown6328cdc2010-07-29 18:18:33 -07002130 mLocked.orientedXPrecision = mLocked.yPrecision;
2131 mLocked.orientedYPrecision = mLocked.xPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002132
2133 mLocked.orientedRanges.x.min = 0;
2134 mLocked.orientedRanges.x.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2135 * mLocked.yScale;
2136 mLocked.orientedRanges.x.flat = 0;
2137 mLocked.orientedRanges.x.fuzz = mLocked.yScale;
2138
2139 mLocked.orientedRanges.y.min = 0;
2140 mLocked.orientedRanges.y.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2141 * mLocked.xScale;
2142 mLocked.orientedRanges.y.flat = 0;
2143 mLocked.orientedRanges.y.fuzz = mLocked.xScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002144 break;
Jeff Brown9626b142011-03-03 02:09:54 -08002145
Jeff Brown6d0fec22010-07-23 21:28:06 -07002146 default:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002147 mLocked.orientedSurfaceWidth = mLocked.surfaceWidth;
2148 mLocked.orientedSurfaceHeight = mLocked.surfaceHeight;
Jeff Brown9626b142011-03-03 02:09:54 -08002149
Jeff Brown6328cdc2010-07-29 18:18:33 -07002150 mLocked.orientedXPrecision = mLocked.xPrecision;
2151 mLocked.orientedYPrecision = mLocked.yPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002152
2153 mLocked.orientedRanges.x.min = 0;
2154 mLocked.orientedRanges.x.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2155 * mLocked.xScale;
2156 mLocked.orientedRanges.x.flat = 0;
2157 mLocked.orientedRanges.x.fuzz = mLocked.xScale;
2158
2159 mLocked.orientedRanges.y.min = 0;
2160 mLocked.orientedRanges.y.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2161 * mLocked.yScale;
2162 mLocked.orientedRanges.y.flat = 0;
2163 mLocked.orientedRanges.y.fuzz = mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002164 break;
2165 }
Jeff Brown96ad3972011-03-09 17:39:48 -08002166
2167 // Compute pointer gesture detection parameters.
2168 // TODO: These factors should not be hardcoded.
2169 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
2170 int32_t rawWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2171 int32_t rawHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
2172
2173 // Scale movements such that one whole swipe of the touch pad covers a portion
2174 // of the display along whichever axis of the touch pad is longer.
2175 // Assume that the touch pad has a square aspect ratio such that movements in
2176 // X and Y of the same number of raw units cover the same physical distance.
2177 const float scaleFactor = 0.8f;
2178
2179 mLocked.pointerGestureXMovementScale = rawWidth > rawHeight
2180 ? scaleFactor * float(mLocked.associatedDisplayWidth) / rawWidth
2181 : scaleFactor * float(mLocked.associatedDisplayHeight) / rawHeight;
2182 mLocked.pointerGestureYMovementScale = mLocked.pointerGestureXMovementScale;
2183
2184 // Scale zooms to cover a smaller range of the display than movements do.
2185 // This value determines the area around the pointer that is affected by freeform
2186 // pointer gestures.
2187 mLocked.pointerGestureXZoomScale = mLocked.pointerGestureXMovementScale * 0.4f;
2188 mLocked.pointerGestureYZoomScale = mLocked.pointerGestureYMovementScale * 0.4f;
2189
2190 // Max width between pointers to detect a swipe gesture is 3/4 of the short
2191 // axis of the touch pad. Touches that are wider than this are translated
2192 // into freeform gestures.
2193 mLocked.pointerGestureMaxSwipeWidthSquared = min(rawWidth, rawHeight) * 3 / 4;
2194 mLocked.pointerGestureMaxSwipeWidthSquared *=
2195 mLocked.pointerGestureMaxSwipeWidthSquared;
2196 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002197 }
2198
2199 return true;
2200}
2201
Jeff Brownef3d7e82010-09-30 14:33:04 -07002202void TouchInputMapper::dumpSurfaceLocked(String8& dump) {
2203 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mLocked.surfaceWidth);
2204 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mLocked.surfaceHeight);
2205 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mLocked.surfaceOrientation);
Jeff Brownb88102f2010-09-08 11:49:43 -07002206}
2207
Jeff Brown6328cdc2010-07-29 18:18:33 -07002208void TouchInputMapper::configureVirtualKeysLocked() {
Jeff Brown8d608662010-08-30 03:02:23 -07002209 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
Jeff Brown90655042010-12-02 13:50:46 -08002210 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002211
Jeff Brown6328cdc2010-07-29 18:18:33 -07002212 mLocked.virtualKeys.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002213
Jeff Brown6328cdc2010-07-29 18:18:33 -07002214 if (virtualKeyDefinitions.size() == 0) {
2215 return;
2216 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002217
Jeff Brown6328cdc2010-07-29 18:18:33 -07002218 mLocked.virtualKeys.setCapacity(virtualKeyDefinitions.size());
2219
Jeff Brown8d608662010-08-30 03:02:23 -07002220 int32_t touchScreenLeft = mRawAxes.x.minValue;
2221 int32_t touchScreenTop = mRawAxes.y.minValue;
Jeff Brown9626b142011-03-03 02:09:54 -08002222 int32_t touchScreenWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2223 int32_t touchScreenHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002224
2225 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002226 const VirtualKeyDefinition& virtualKeyDefinition =
Jeff Brown6328cdc2010-07-29 18:18:33 -07002227 virtualKeyDefinitions[i];
2228
2229 mLocked.virtualKeys.add();
2230 VirtualKey& virtualKey = mLocked.virtualKeys.editTop();
2231
2232 virtualKey.scanCode = virtualKeyDefinition.scanCode;
2233 int32_t keyCode;
2234 uint32_t flags;
Jeff Brown6f2fba42011-02-19 01:08:02 -08002235 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode,
Jeff Brown6328cdc2010-07-29 18:18:33 -07002236 & keyCode, & flags)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002237 LOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
2238 virtualKey.scanCode);
Jeff Brown6328cdc2010-07-29 18:18:33 -07002239 mLocked.virtualKeys.pop(); // drop the key
2240 continue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002241 }
2242
Jeff Brown6328cdc2010-07-29 18:18:33 -07002243 virtualKey.keyCode = keyCode;
2244 virtualKey.flags = flags;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002245
Jeff Brown6328cdc2010-07-29 18:18:33 -07002246 // convert the key definition's display coordinates into touch coordinates for a hit box
2247 int32_t halfWidth = virtualKeyDefinition.width / 2;
2248 int32_t halfHeight = virtualKeyDefinition.height / 2;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002249
Jeff Brown6328cdc2010-07-29 18:18:33 -07002250 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
2251 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2252 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
2253 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2254 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
2255 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
2256 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
2257 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
Jeff Brownef3d7e82010-09-30 14:33:04 -07002258 }
2259}
2260
2261void TouchInputMapper::dumpVirtualKeysLocked(String8& dump) {
2262 if (!mLocked.virtualKeys.isEmpty()) {
2263 dump.append(INDENT3 "Virtual Keys:\n");
2264
2265 for (size_t i = 0; i < mLocked.virtualKeys.size(); i++) {
2266 const VirtualKey& virtualKey = mLocked.virtualKeys.itemAt(i);
2267 dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, "
2268 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
2269 i, virtualKey.scanCode, virtualKey.keyCode,
2270 virtualKey.hitLeft, virtualKey.hitRight,
2271 virtualKey.hitTop, virtualKey.hitBottom);
2272 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002273 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002274}
2275
Jeff Brown8d608662010-08-30 03:02:23 -07002276void TouchInputMapper::parseCalibration() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002277 const PropertyMap& in = getDevice()->getConfiguration();
Jeff Brown8d608662010-08-30 03:02:23 -07002278 Calibration& out = mCalibration;
2279
Jeff Brownc6d282b2010-10-14 21:42:15 -07002280 // Touch Size
2281 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT;
2282 String8 touchSizeCalibrationString;
2283 if (in.tryGetProperty(String8("touch.touchSize.calibration"), touchSizeCalibrationString)) {
2284 if (touchSizeCalibrationString == "none") {
2285 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
2286 } else if (touchSizeCalibrationString == "geometric") {
2287 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC;
2288 } else if (touchSizeCalibrationString == "pressure") {
2289 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
2290 } else if (touchSizeCalibrationString != "default") {
2291 LOGW("Invalid value for touch.touchSize.calibration: '%s'",
2292 touchSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002293 }
2294 }
2295
Jeff Brownc6d282b2010-10-14 21:42:15 -07002296 // Tool Size
2297 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_DEFAULT;
2298 String8 toolSizeCalibrationString;
2299 if (in.tryGetProperty(String8("touch.toolSize.calibration"), toolSizeCalibrationString)) {
2300 if (toolSizeCalibrationString == "none") {
2301 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
2302 } else if (toolSizeCalibrationString == "geometric") {
2303 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC;
2304 } else if (toolSizeCalibrationString == "linear") {
2305 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
2306 } else if (toolSizeCalibrationString == "area") {
2307 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_AREA;
2308 } else if (toolSizeCalibrationString != "default") {
2309 LOGW("Invalid value for touch.toolSize.calibration: '%s'",
2310 toolSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002311 }
2312 }
2313
Jeff Brownc6d282b2010-10-14 21:42:15 -07002314 out.haveToolSizeLinearScale = in.tryGetProperty(String8("touch.toolSize.linearScale"),
2315 out.toolSizeLinearScale);
2316 out.haveToolSizeLinearBias = in.tryGetProperty(String8("touch.toolSize.linearBias"),
2317 out.toolSizeLinearBias);
2318 out.haveToolSizeAreaScale = in.tryGetProperty(String8("touch.toolSize.areaScale"),
2319 out.toolSizeAreaScale);
2320 out.haveToolSizeAreaBias = in.tryGetProperty(String8("touch.toolSize.areaBias"),
2321 out.toolSizeAreaBias);
2322 out.haveToolSizeIsSummed = in.tryGetProperty(String8("touch.toolSize.isSummed"),
2323 out.toolSizeIsSummed);
Jeff Brown8d608662010-08-30 03:02:23 -07002324
2325 // Pressure
2326 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
2327 String8 pressureCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002328 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002329 if (pressureCalibrationString == "none") {
2330 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2331 } else if (pressureCalibrationString == "physical") {
2332 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
2333 } else if (pressureCalibrationString == "amplitude") {
2334 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2335 } else if (pressureCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002336 LOGW("Invalid value for touch.pressure.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002337 pressureCalibrationString.string());
2338 }
2339 }
2340
2341 out.pressureSource = Calibration::PRESSURE_SOURCE_DEFAULT;
2342 String8 pressureSourceString;
2343 if (in.tryGetProperty(String8("touch.pressure.source"), pressureSourceString)) {
2344 if (pressureSourceString == "pressure") {
2345 out.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2346 } else if (pressureSourceString == "touch") {
2347 out.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2348 } else if (pressureSourceString != "default") {
2349 LOGW("Invalid value for touch.pressure.source: '%s'",
2350 pressureSourceString.string());
2351 }
2352 }
2353
2354 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
2355 out.pressureScale);
2356
2357 // Size
2358 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
2359 String8 sizeCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002360 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002361 if (sizeCalibrationString == "none") {
2362 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2363 } else if (sizeCalibrationString == "normalized") {
2364 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2365 } else if (sizeCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002366 LOGW("Invalid value for touch.size.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002367 sizeCalibrationString.string());
2368 }
2369 }
2370
2371 // Orientation
2372 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
2373 String8 orientationCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002374 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002375 if (orientationCalibrationString == "none") {
2376 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2377 } else if (orientationCalibrationString == "interpolated") {
2378 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002379 } else if (orientationCalibrationString == "vector") {
2380 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002381 } else if (orientationCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002382 LOGW("Invalid value for touch.orientation.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002383 orientationCalibrationString.string());
2384 }
2385 }
2386}
2387
2388void TouchInputMapper::resolveCalibration() {
2389 // Pressure
2390 switch (mCalibration.pressureSource) {
2391 case Calibration::PRESSURE_SOURCE_DEFAULT:
2392 if (mRawAxes.pressure.valid) {
2393 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2394 } else if (mRawAxes.touchMajor.valid) {
2395 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2396 }
2397 break;
2398
2399 case Calibration::PRESSURE_SOURCE_PRESSURE:
2400 if (! mRawAxes.pressure.valid) {
2401 LOGW("Calibration property touch.pressure.source is 'pressure' but "
2402 "the pressure axis is not available.");
2403 }
2404 break;
2405
2406 case Calibration::PRESSURE_SOURCE_TOUCH:
2407 if (! mRawAxes.touchMajor.valid) {
2408 LOGW("Calibration property touch.pressure.source is 'touch' but "
2409 "the touchMajor axis is not available.");
2410 }
2411 break;
2412
2413 default:
2414 break;
2415 }
2416
2417 switch (mCalibration.pressureCalibration) {
2418 case Calibration::PRESSURE_CALIBRATION_DEFAULT:
2419 if (mCalibration.pressureSource != Calibration::PRESSURE_SOURCE_DEFAULT) {
2420 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2421 } else {
2422 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2423 }
2424 break;
2425
2426 default:
2427 break;
2428 }
2429
Jeff Brownc6d282b2010-10-14 21:42:15 -07002430 // Tool Size
2431 switch (mCalibration.toolSizeCalibration) {
2432 case Calibration::TOOL_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002433 if (mRawAxes.toolMajor.valid) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002434 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
Jeff Brown8d608662010-08-30 03:02:23 -07002435 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002436 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002437 }
2438 break;
2439
2440 default:
2441 break;
2442 }
2443
Jeff Brownc6d282b2010-10-14 21:42:15 -07002444 // Touch Size
2445 switch (mCalibration.touchSizeCalibration) {
2446 case Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002447 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE
Jeff Brownc6d282b2010-10-14 21:42:15 -07002448 && mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2449 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
Jeff Brown8d608662010-08-30 03:02:23 -07002450 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002451 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002452 }
2453 break;
2454
2455 default:
2456 break;
2457 }
2458
2459 // Size
2460 switch (mCalibration.sizeCalibration) {
2461 case Calibration::SIZE_CALIBRATION_DEFAULT:
2462 if (mRawAxes.toolMajor.valid) {
2463 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2464 } else {
2465 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2466 }
2467 break;
2468
2469 default:
2470 break;
2471 }
2472
2473 // Orientation
2474 switch (mCalibration.orientationCalibration) {
2475 case Calibration::ORIENTATION_CALIBRATION_DEFAULT:
2476 if (mRawAxes.orientation.valid) {
2477 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
2478 } else {
2479 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2480 }
2481 break;
2482
2483 default:
2484 break;
2485 }
2486}
2487
Jeff Brownef3d7e82010-09-30 14:33:04 -07002488void TouchInputMapper::dumpCalibration(String8& dump) {
2489 dump.append(INDENT3 "Calibration:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002490
Jeff Brownc6d282b2010-10-14 21:42:15 -07002491 // Touch Size
2492 switch (mCalibration.touchSizeCalibration) {
2493 case Calibration::TOUCH_SIZE_CALIBRATION_NONE:
2494 dump.append(INDENT4 "touch.touchSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002495 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002496 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
2497 dump.append(INDENT4 "touch.touchSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002498 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002499 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
2500 dump.append(INDENT4 "touch.touchSize.calibration: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002501 break;
2502 default:
2503 assert(false);
2504 }
2505
Jeff Brownc6d282b2010-10-14 21:42:15 -07002506 // Tool Size
2507 switch (mCalibration.toolSizeCalibration) {
2508 case Calibration::TOOL_SIZE_CALIBRATION_NONE:
2509 dump.append(INDENT4 "touch.toolSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002510 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002511 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
2512 dump.append(INDENT4 "touch.toolSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002513 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002514 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
2515 dump.append(INDENT4 "touch.toolSize.calibration: linear\n");
2516 break;
2517 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
2518 dump.append(INDENT4 "touch.toolSize.calibration: area\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002519 break;
2520 default:
2521 assert(false);
2522 }
2523
Jeff Brownc6d282b2010-10-14 21:42:15 -07002524 if (mCalibration.haveToolSizeLinearScale) {
2525 dump.appendFormat(INDENT4 "touch.toolSize.linearScale: %0.3f\n",
2526 mCalibration.toolSizeLinearScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002527 }
2528
Jeff Brownc6d282b2010-10-14 21:42:15 -07002529 if (mCalibration.haveToolSizeLinearBias) {
2530 dump.appendFormat(INDENT4 "touch.toolSize.linearBias: %0.3f\n",
2531 mCalibration.toolSizeLinearBias);
Jeff Brown8d608662010-08-30 03:02:23 -07002532 }
2533
Jeff Brownc6d282b2010-10-14 21:42:15 -07002534 if (mCalibration.haveToolSizeAreaScale) {
2535 dump.appendFormat(INDENT4 "touch.toolSize.areaScale: %0.3f\n",
2536 mCalibration.toolSizeAreaScale);
2537 }
2538
2539 if (mCalibration.haveToolSizeAreaBias) {
2540 dump.appendFormat(INDENT4 "touch.toolSize.areaBias: %0.3f\n",
2541 mCalibration.toolSizeAreaBias);
2542 }
2543
2544 if (mCalibration.haveToolSizeIsSummed) {
Jeff Brown1f245102010-11-18 20:53:46 -08002545 dump.appendFormat(INDENT4 "touch.toolSize.isSummed: %s\n",
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002546 toString(mCalibration.toolSizeIsSummed));
Jeff Brown8d608662010-08-30 03:02:23 -07002547 }
2548
2549 // Pressure
2550 switch (mCalibration.pressureCalibration) {
2551 case Calibration::PRESSURE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002552 dump.append(INDENT4 "touch.pressure.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002553 break;
2554 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002555 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002556 break;
2557 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002558 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002559 break;
2560 default:
2561 assert(false);
2562 }
2563
2564 switch (mCalibration.pressureSource) {
2565 case Calibration::PRESSURE_SOURCE_PRESSURE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002566 dump.append(INDENT4 "touch.pressure.source: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002567 break;
2568 case Calibration::PRESSURE_SOURCE_TOUCH:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002569 dump.append(INDENT4 "touch.pressure.source: touch\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002570 break;
2571 case Calibration::PRESSURE_SOURCE_DEFAULT:
2572 break;
2573 default:
2574 assert(false);
2575 }
2576
2577 if (mCalibration.havePressureScale) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07002578 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
2579 mCalibration.pressureScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002580 }
2581
2582 // Size
2583 switch (mCalibration.sizeCalibration) {
2584 case Calibration::SIZE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002585 dump.append(INDENT4 "touch.size.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002586 break;
2587 case Calibration::SIZE_CALIBRATION_NORMALIZED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002588 dump.append(INDENT4 "touch.size.calibration: normalized\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002589 break;
2590 default:
2591 assert(false);
2592 }
2593
2594 // Orientation
2595 switch (mCalibration.orientationCalibration) {
2596 case Calibration::ORIENTATION_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002597 dump.append(INDENT4 "touch.orientation.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002598 break;
2599 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002600 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002601 break;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002602 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
2603 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
2604 break;
Jeff Brown8d608662010-08-30 03:02:23 -07002605 default:
2606 assert(false);
2607 }
2608}
2609
Jeff Brown6d0fec22010-07-23 21:28:06 -07002610void TouchInputMapper::reset() {
2611 // Synthesize touch up event if touch is currently down.
2612 // This will also take care of finishing virtual key processing if needed.
2613 if (mLastTouch.pointerCount != 0) {
2614 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
2615 mCurrentTouch.clear();
2616 syncTouch(when, true);
2617 }
2618
Jeff Brown6328cdc2010-07-29 18:18:33 -07002619 { // acquire lock
2620 AutoMutex _l(mLock);
2621 initializeLocked();
2622 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002623
Jeff Brown6328cdc2010-07-29 18:18:33 -07002624 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002625}
2626
2627void TouchInputMapper::syncTouch(nsecs_t when, bool havePointerIds) {
Jeff Brown68d60752011-03-17 01:34:19 -07002628#if DEBUG_RAW_EVENTS
2629 if (!havePointerIds) {
2630 LOGD("syncTouch: pointerCount=%d, no pointer ids", mCurrentTouch.pointerCount);
2631 } else {
2632 LOGD("syncTouch: pointerCount=%d, up=0x%08x, down=0x%08x, move=0x%08x, "
2633 "last=0x%08x, current=0x%08x", mCurrentTouch.pointerCount,
2634 mLastTouch.idBits.value & ~mCurrentTouch.idBits.value,
2635 mCurrentTouch.idBits.value & ~mLastTouch.idBits.value,
2636 mLastTouch.idBits.value & mCurrentTouch.idBits.value,
2637 mLastTouch.idBits.value, mCurrentTouch.idBits.value);
2638 }
2639#endif
2640
Jeff Brown6328cdc2010-07-29 18:18:33 -07002641 // Preprocess pointer data.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002642 if (mParameters.useBadTouchFilter) {
2643 if (applyBadTouchFilter()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002644 havePointerIds = false;
2645 }
2646 }
2647
Jeff Brown6d0fec22010-07-23 21:28:06 -07002648 if (mParameters.useJumpyTouchFilter) {
2649 if (applyJumpyTouchFilter()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002650 havePointerIds = false;
2651 }
2652 }
2653
Jeff Brown68d60752011-03-17 01:34:19 -07002654 if (!havePointerIds) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002655 calculatePointerIds();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002656 }
2657
Jeff Brown6d0fec22010-07-23 21:28:06 -07002658 TouchData temp;
2659 TouchData* savedTouch;
2660 if (mParameters.useAveragingTouchFilter) {
2661 temp.copyFrom(mCurrentTouch);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002662 savedTouch = & temp;
2663
Jeff Brown6d0fec22010-07-23 21:28:06 -07002664 applyAveragingTouchFilter();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002665 } else {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002666 savedTouch = & mCurrentTouch;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002667 }
2668
Jeff Brown56194eb2011-03-02 19:23:13 -08002669 uint32_t policyFlags = 0;
Jeff Brown05dc66a2011-03-02 14:41:58 -08002670 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
Jeff Brownefd32662011-03-08 15:13:06 -08002671 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
2672 // If this is a touch screen, hide the pointer on an initial down.
2673 getContext()->fadePointer();
2674 }
Jeff Brown56194eb2011-03-02 19:23:13 -08002675
2676 // Initial downs on external touch devices should wake the device.
2677 // We don't do this for internal touch screens to prevent them from waking
2678 // up in your pocket.
2679 // TODO: Use the input device configuration to control this behavior more finely.
2680 if (getDevice()->isExternal()) {
2681 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
2682 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08002683 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002684
Jeff Brown05dc66a2011-03-02 14:41:58 -08002685 // Process touches and virtual keys.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002686 TouchResult touchResult = consumeOffScreenTouches(when, policyFlags);
2687 if (touchResult == DISPATCH_TOUCH) {
Jeff Brownefd32662011-03-08 15:13:06 -08002688 suppressSwipeOntoVirtualKeys(when);
Jeff Brown96ad3972011-03-09 17:39:48 -08002689 if (mPointerController != NULL) {
2690 dispatchPointerGestures(when, policyFlags);
2691 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002692 dispatchTouches(when, policyFlags);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002693 }
2694
Jeff Brown6328cdc2010-07-29 18:18:33 -07002695 // Copy current touch to last touch in preparation for the next cycle.
Jeff Brown96ad3972011-03-09 17:39:48 -08002696 // Keep the button state so we can track edge-triggered button state changes.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002697 if (touchResult == DROP_STROKE) {
2698 mLastTouch.clear();
Jeff Brown96ad3972011-03-09 17:39:48 -08002699 mLastTouch.buttonState = savedTouch->buttonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002700 } else {
2701 mLastTouch.copyFrom(*savedTouch);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002702 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002703}
2704
Jeff Brown6d0fec22010-07-23 21:28:06 -07002705TouchInputMapper::TouchResult TouchInputMapper::consumeOffScreenTouches(
2706 nsecs_t when, uint32_t policyFlags) {
2707 int32_t keyEventAction, keyEventFlags;
2708 int32_t keyCode, scanCode, downTime;
2709 TouchResult touchResult;
Jeff Brown349703e2010-06-22 01:27:15 -07002710
Jeff Brown6328cdc2010-07-29 18:18:33 -07002711 { // acquire lock
2712 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002713
Jeff Brown6328cdc2010-07-29 18:18:33 -07002714 // Update surface size and orientation, including virtual key positions.
2715 if (! configureSurfaceLocked()) {
2716 return DROP_STROKE;
2717 }
2718
2719 // Check for virtual key press.
2720 if (mLocked.currentVirtualKey.down) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002721 if (mCurrentTouch.pointerCount == 0) {
2722 // Pointer went up while virtual key was down.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002723 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002724#if DEBUG_VIRTUAL_KEYS
2725 LOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002726 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002727#endif
2728 keyEventAction = AKEY_EVENT_ACTION_UP;
2729 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2730 touchResult = SKIP_TOUCH;
2731 goto DispatchVirtualKey;
2732 }
2733
2734 if (mCurrentTouch.pointerCount == 1) {
2735 int32_t x = mCurrentTouch.pointers[0].x;
2736 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002737 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
2738 if (virtualKey && virtualKey->keyCode == mLocked.currentVirtualKey.keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002739 // Pointer is still within the space of the virtual key.
2740 return SKIP_TOUCH;
2741 }
2742 }
2743
2744 // Pointer left virtual key area or another pointer also went down.
2745 // Send key cancellation and drop the stroke so subsequent motions will be
2746 // considered fresh downs. This is useful when the user swipes away from the
2747 // virtual key area into the main display surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002748 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002749#if DEBUG_VIRTUAL_KEYS
2750 LOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002751 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002752#endif
2753 keyEventAction = AKEY_EVENT_ACTION_UP;
2754 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
2755 | AKEY_EVENT_FLAG_CANCELED;
Jeff Brownc3db8582010-10-20 15:33:38 -07002756
2757 // Check whether the pointer moved inside the display area where we should
2758 // start a new stroke.
2759 int32_t x = mCurrentTouch.pointers[0].x;
2760 int32_t y = mCurrentTouch.pointers[0].y;
2761 if (isPointInsideSurfaceLocked(x, y)) {
2762 mLastTouch.clear();
2763 touchResult = DISPATCH_TOUCH;
2764 } else {
2765 touchResult = DROP_STROKE;
2766 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002767 } else {
2768 if (mCurrentTouch.pointerCount >= 1 && mLastTouch.pointerCount == 0) {
2769 // Pointer just went down. Handle off-screen touches, if needed.
2770 int32_t x = mCurrentTouch.pointers[0].x;
2771 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002772 if (! isPointInsideSurfaceLocked(x, y)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002773 // If exactly one pointer went down, check for virtual key hit.
2774 // Otherwise we will drop the entire stroke.
2775 if (mCurrentTouch.pointerCount == 1) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002776 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002777 if (virtualKey) {
Jeff Brownfe508922011-01-18 15:10:10 -08002778 if (mContext->shouldDropVirtualKey(when, getDevice(),
2779 virtualKey->keyCode, virtualKey->scanCode)) {
2780 return DROP_STROKE;
2781 }
2782
Jeff Brown6328cdc2010-07-29 18:18:33 -07002783 mLocked.currentVirtualKey.down = true;
2784 mLocked.currentVirtualKey.downTime = when;
2785 mLocked.currentVirtualKey.keyCode = virtualKey->keyCode;
2786 mLocked.currentVirtualKey.scanCode = virtualKey->scanCode;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002787#if DEBUG_VIRTUAL_KEYS
2788 LOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002789 mLocked.currentVirtualKey.keyCode,
2790 mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002791#endif
2792 keyEventAction = AKEY_EVENT_ACTION_DOWN;
2793 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM
2794 | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2795 touchResult = SKIP_TOUCH;
2796 goto DispatchVirtualKey;
2797 }
2798 }
2799 return DROP_STROKE;
2800 }
2801 }
2802 return DISPATCH_TOUCH;
2803 }
2804
2805 DispatchVirtualKey:
2806 // Collect remaining state needed to dispatch virtual key.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002807 keyCode = mLocked.currentVirtualKey.keyCode;
2808 scanCode = mLocked.currentVirtualKey.scanCode;
2809 downTime = mLocked.currentVirtualKey.downTime;
2810 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002811
2812 // Dispatch virtual key.
2813 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown0eaf3932010-10-01 14:55:30 -07002814 policyFlags |= POLICY_FLAG_VIRTUAL;
Jeff Brownb6997262010-10-08 22:31:17 -07002815 getDispatcher()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
2816 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
2817 return touchResult;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002818}
2819
Jeff Brownefd32662011-03-08 15:13:06 -08002820void TouchInputMapper::suppressSwipeOntoVirtualKeys(nsecs_t when) {
Jeff Brownfe508922011-01-18 15:10:10 -08002821 // Disable all virtual key touches that happen within a short time interval of the
2822 // most recent touch. The idea is to filter out stray virtual key presses when
2823 // interacting with the touch screen.
2824 //
2825 // Problems we're trying to solve:
2826 //
2827 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
2828 // virtual key area that is implemented by a separate touch panel and accidentally
2829 // triggers a virtual key.
2830 //
2831 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
2832 // area and accidentally triggers a virtual key. This often happens when virtual keys
2833 // are layed out below the screen near to where the on screen keyboard's space bar
2834 // is displayed.
2835 if (mParameters.virtualKeyQuietTime > 0 && mCurrentTouch.pointerCount != 0) {
2836 mContext->disableVirtualKeysUntil(when + mParameters.virtualKeyQuietTime);
2837 }
2838}
2839
Jeff Brown6d0fec22010-07-23 21:28:06 -07002840void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
2841 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
2842 uint32_t lastPointerCount = mLastTouch.pointerCount;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002843 if (currentPointerCount == 0 && lastPointerCount == 0) {
2844 return; // nothing to do!
2845 }
2846
Jeff Brown96ad3972011-03-09 17:39:48 -08002847 // Update current touch coordinates.
2848 int32_t edgeFlags;
2849 float xPrecision, yPrecision;
2850 prepareTouches(&edgeFlags, &xPrecision, &yPrecision);
2851
2852 // Dispatch motions.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002853 BitSet32 currentIdBits = mCurrentTouch.idBits;
2854 BitSet32 lastIdBits = mLastTouch.idBits;
Jeff Brown96ad3972011-03-09 17:39:48 -08002855 uint32_t metaState = getContext()->getGlobalMetaState();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002856
2857 if (currentIdBits == lastIdBits) {
2858 // No pointer id changes so this is a move event.
2859 // The dispatcher takes care of batching moves so we don't have to deal with that here.
Jeff Brown96ad3972011-03-09 17:39:48 -08002860 dispatchMotion(when, policyFlags, mTouchSource,
2861 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
2862 mCurrentTouchCoords, mCurrentTouch.idToIndex, currentIdBits, -1,
2863 xPrecision, yPrecision, mDownTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002864 } else {
Jeff Brownc3db8582010-10-20 15:33:38 -07002865 // There may be pointers going up and pointers going down and pointers moving
2866 // all at the same time.
Jeff Brown96ad3972011-03-09 17:39:48 -08002867 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2868 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002869 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
Jeff Brown96ad3972011-03-09 17:39:48 -08002870 BitSet32 dispatchedIdBits(lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002871
Jeff Brown96ad3972011-03-09 17:39:48 -08002872 // Update last coordinates of pointers that have moved so that we observe the new
2873 // pointer positions at the same time as other pointers that have just gone up.
2874 bool moveNeeded = updateMovedPointerCoords(
2875 mCurrentTouchCoords, mCurrentTouch.idToIndex,
2876 mLastTouchCoords, mLastTouch.idToIndex,
2877 moveIdBits);
Jeff Brownc3db8582010-10-20 15:33:38 -07002878
Jeff Brown96ad3972011-03-09 17:39:48 -08002879 // Dispatch pointer up events.
Jeff Brownc3db8582010-10-20 15:33:38 -07002880 while (!upIdBits.isEmpty()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002881 uint32_t upId = upIdBits.firstMarkedBit();
2882 upIdBits.clearBit(upId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002883
Jeff Brown96ad3972011-03-09 17:39:48 -08002884 dispatchMotion(when, policyFlags, mTouchSource,
2885 AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, 0,
2886 mLastTouchCoords, mLastTouch.idToIndex, dispatchedIdBits, upId,
2887 xPrecision, yPrecision, mDownTime);
2888 dispatchedIdBits.clearBit(upId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002889 }
2890
Jeff Brownc3db8582010-10-20 15:33:38 -07002891 // Dispatch move events if any of the remaining pointers moved from their old locations.
2892 // Although applications receive new locations as part of individual pointer up
2893 // events, they do not generally handle them except when presented in a move event.
2894 if (moveNeeded) {
Jeff Brown96ad3972011-03-09 17:39:48 -08002895 assert(moveIdBits.value == dispatchedIdBits.value);
2896 dispatchMotion(when, policyFlags, mTouchSource,
2897 AMOTION_EVENT_ACTION_MOVE, 0, metaState, 0,
2898 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, -1,
2899 xPrecision, yPrecision, mDownTime);
Jeff Brownc3db8582010-10-20 15:33:38 -07002900 }
2901
2902 // Dispatch pointer down events using the new pointer locations.
2903 while (!downIdBits.isEmpty()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002904 uint32_t downId = downIdBits.firstMarkedBit();
2905 downIdBits.clearBit(downId);
Jeff Brown96ad3972011-03-09 17:39:48 -08002906 dispatchedIdBits.markBit(downId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002907
Jeff Brown96ad3972011-03-09 17:39:48 -08002908 if (dispatchedIdBits.count() == 1) {
2909 // First pointer is going down. Set down time.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002910 mDownTime = when;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002911 } else {
Jeff Brown96ad3972011-03-09 17:39:48 -08002912 // Only send edge flags with first pointer down.
2913 edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002914 }
2915
Jeff Brown96ad3972011-03-09 17:39:48 -08002916 dispatchMotion(when, policyFlags, mTouchSource,
2917 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
2918 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, downId,
2919 xPrecision, yPrecision, mDownTime);
2920 }
2921 }
2922
2923 // Update state for next time.
2924 for (uint32_t i = 0; i < currentPointerCount; i++) {
2925 mLastTouchCoords[i].copyFrom(mCurrentTouchCoords[i]);
2926 }
2927}
2928
2929void TouchInputMapper::prepareTouches(int32_t* outEdgeFlags,
2930 float* outXPrecision, float* outYPrecision) {
2931 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
2932 uint32_t lastPointerCount = mLastTouch.pointerCount;
2933
2934 AutoMutex _l(mLock);
2935
2936 // Walk through the the active pointers and map touch screen coordinates (TouchData) into
2937 // display or surface coordinates (PointerCoords) and adjust for display orientation.
2938 for (uint32_t i = 0; i < currentPointerCount; i++) {
2939 const PointerData& in = mCurrentTouch.pointers[i];
2940
2941 // ToolMajor and ToolMinor
2942 float toolMajor, toolMinor;
2943 switch (mCalibration.toolSizeCalibration) {
2944 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
2945 toolMajor = in.toolMajor * mLocked.geometricScale;
2946 if (mRawAxes.toolMinor.valid) {
2947 toolMinor = in.toolMinor * mLocked.geometricScale;
2948 } else {
2949 toolMinor = toolMajor;
2950 }
2951 break;
2952 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
2953 toolMajor = in.toolMajor != 0
2954 ? in.toolMajor * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias
2955 : 0;
2956 if (mRawAxes.toolMinor.valid) {
2957 toolMinor = in.toolMinor != 0
2958 ? in.toolMinor * mLocked.toolSizeLinearScale
2959 + mLocked.toolSizeLinearBias
2960 : 0;
2961 } else {
2962 toolMinor = toolMajor;
2963 }
2964 break;
2965 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
2966 if (in.toolMajor != 0) {
2967 float diameter = sqrtf(in.toolMajor
2968 * mLocked.toolSizeAreaScale + mLocked.toolSizeAreaBias);
2969 toolMajor = diameter * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias;
2970 } else {
2971 toolMajor = 0;
2972 }
2973 toolMinor = toolMajor;
2974 break;
2975 default:
2976 toolMajor = 0;
2977 toolMinor = 0;
2978 break;
2979 }
2980
2981 if (mCalibration.haveToolSizeIsSummed && mCalibration.toolSizeIsSummed) {
2982 toolMajor /= currentPointerCount;
2983 toolMinor /= currentPointerCount;
2984 }
2985
2986 // Pressure
2987 float rawPressure;
2988 switch (mCalibration.pressureSource) {
2989 case Calibration::PRESSURE_SOURCE_PRESSURE:
2990 rawPressure = in.pressure;
2991 break;
2992 case Calibration::PRESSURE_SOURCE_TOUCH:
2993 rawPressure = in.touchMajor;
2994 break;
2995 default:
2996 rawPressure = 0;
2997 }
2998
2999 float pressure;
3000 switch (mCalibration.pressureCalibration) {
3001 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3002 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3003 pressure = rawPressure * mLocked.pressureScale;
3004 break;
3005 default:
3006 pressure = 1;
3007 break;
3008 }
3009
3010 // TouchMajor and TouchMinor
3011 float touchMajor, touchMinor;
3012 switch (mCalibration.touchSizeCalibration) {
3013 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
3014 touchMajor = in.touchMajor * mLocked.geometricScale;
3015 if (mRawAxes.touchMinor.valid) {
3016 touchMinor = in.touchMinor * mLocked.geometricScale;
3017 } else {
3018 touchMinor = touchMajor;
3019 }
3020 break;
3021 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
3022 touchMajor = toolMajor * pressure;
3023 touchMinor = toolMinor * pressure;
3024 break;
3025 default:
3026 touchMajor = 0;
3027 touchMinor = 0;
3028 break;
3029 }
3030
3031 if (touchMajor > toolMajor) {
3032 touchMajor = toolMajor;
3033 }
3034 if (touchMinor > toolMinor) {
3035 touchMinor = toolMinor;
3036 }
3037
3038 // Size
3039 float size;
3040 switch (mCalibration.sizeCalibration) {
3041 case Calibration::SIZE_CALIBRATION_NORMALIZED: {
3042 float rawSize = mRawAxes.toolMinor.valid
3043 ? avg(in.toolMajor, in.toolMinor)
3044 : in.toolMajor;
3045 size = rawSize * mLocked.sizeScale;
3046 break;
3047 }
3048 default:
3049 size = 0;
3050 break;
3051 }
3052
3053 // Orientation
3054 float orientation;
3055 switch (mCalibration.orientationCalibration) {
3056 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3057 orientation = in.orientation * mLocked.orientationScale;
3058 break;
3059 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
3060 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
3061 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
3062 if (c1 != 0 || c2 != 0) {
3063 orientation = atan2f(c1, c2) * 0.5f;
3064 float scale = 1.0f + pythag(c1, c2) / 16.0f;
3065 touchMajor *= scale;
3066 touchMinor /= scale;
3067 toolMajor *= scale;
3068 toolMinor /= scale;
3069 } else {
3070 orientation = 0;
3071 }
3072 break;
3073 }
3074 default:
3075 orientation = 0;
3076 }
3077
3078 // X and Y
3079 // Adjust coords for surface orientation.
3080 float x, y;
3081 switch (mLocked.surfaceOrientation) {
3082 case DISPLAY_ORIENTATION_90:
3083 x = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3084 y = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3085 orientation -= M_PI_2;
3086 if (orientation < - M_PI_2) {
3087 orientation += M_PI;
3088 }
3089 break;
3090 case DISPLAY_ORIENTATION_180:
3091 x = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3092 y = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3093 break;
3094 case DISPLAY_ORIENTATION_270:
3095 x = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3096 y = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3097 orientation += M_PI_2;
3098 if (orientation > M_PI_2) {
3099 orientation -= M_PI;
3100 }
3101 break;
3102 default:
3103 x = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3104 y = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3105 break;
3106 }
3107
3108 // Write output coords.
3109 PointerCoords& out = mCurrentTouchCoords[i];
3110 out.clear();
3111 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3112 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3113 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
3114 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
3115 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
3116 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
3117 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
3118 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
3119 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
3120 }
3121
3122 // Check edge flags by looking only at the first pointer since the flags are
3123 // global to the event.
3124 *outEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3125 if (lastPointerCount == 0 && currentPointerCount > 0) {
3126 const PointerData& in = mCurrentTouch.pointers[0];
3127
3128 if (in.x <= mRawAxes.x.minValue) {
3129 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_LEFT,
3130 mLocked.surfaceOrientation);
3131 } else if (in.x >= mRawAxes.x.maxValue) {
3132 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_RIGHT,
3133 mLocked.surfaceOrientation);
3134 }
3135 if (in.y <= mRawAxes.y.minValue) {
3136 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_TOP,
3137 mLocked.surfaceOrientation);
3138 } else if (in.y >= mRawAxes.y.maxValue) {
3139 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_BOTTOM,
3140 mLocked.surfaceOrientation);
3141 }
3142 }
3143
3144 *outXPrecision = mLocked.orientedXPrecision;
3145 *outYPrecision = mLocked.orientedYPrecision;
3146}
3147
3148void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags) {
3149 // Update current gesture coordinates.
3150 bool cancelPreviousGesture, finishPreviousGesture;
3151 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture);
3152
3153 // Send events!
3154 uint32_t metaState = getContext()->getGlobalMetaState();
3155
3156 // Update last coordinates of pointers that have moved so that we observe the new
3157 // pointer positions at the same time as other pointers that have just gone up.
3158 bool down = mPointerGesture.currentGestureMode == PointerGesture::CLICK_OR_DRAG
3159 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
3160 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
3161 bool moveNeeded = false;
3162 if (down && !cancelPreviousGesture && !finishPreviousGesture
3163 && mPointerGesture.lastGesturePointerCount != 0
3164 && mPointerGesture.currentGesturePointerCount != 0) {
3165 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
3166 & mPointerGesture.lastGestureIdBits.value);
3167 moveNeeded = updateMovedPointerCoords(
3168 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3169 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3170 movedGestureIdBits);
3171 }
3172
3173 // Send motion events for all pointers that went up or were canceled.
3174 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
3175 if (!dispatchedGestureIdBits.isEmpty()) {
3176 if (cancelPreviousGesture) {
3177 dispatchMotion(when, policyFlags, mPointerSource,
3178 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3179 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3180 dispatchedGestureIdBits, -1,
3181 0, 0, mPointerGesture.downTime);
3182
3183 dispatchedGestureIdBits.clear();
3184 } else {
3185 BitSet32 upGestureIdBits;
3186 if (finishPreviousGesture) {
3187 upGestureIdBits = dispatchedGestureIdBits;
3188 } else {
3189 upGestureIdBits.value = dispatchedGestureIdBits.value
3190 & ~mPointerGesture.currentGestureIdBits.value;
3191 }
3192 while (!upGestureIdBits.isEmpty()) {
3193 uint32_t id = upGestureIdBits.firstMarkedBit();
3194 upGestureIdBits.clearBit(id);
3195
3196 dispatchMotion(when, policyFlags, mPointerSource,
3197 AMOTION_EVENT_ACTION_POINTER_UP, 0,
3198 metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3199 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3200 dispatchedGestureIdBits, id,
3201 0, 0, mPointerGesture.downTime);
3202
3203 dispatchedGestureIdBits.clearBit(id);
3204 }
3205 }
3206 }
3207
3208 // Send motion events for all pointers that moved.
3209 if (moveNeeded) {
3210 dispatchMotion(when, policyFlags, mPointerSource,
3211 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3212 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3213 dispatchedGestureIdBits, -1,
3214 0, 0, mPointerGesture.downTime);
3215 }
3216
3217 // Send motion events for all pointers that went down.
3218 if (down) {
3219 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
3220 & ~dispatchedGestureIdBits.value);
3221 while (!downGestureIdBits.isEmpty()) {
3222 uint32_t id = downGestureIdBits.firstMarkedBit();
3223 downGestureIdBits.clearBit(id);
3224 dispatchedGestureIdBits.markBit(id);
3225
3226 int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3227 if (dispatchedGestureIdBits.count() == 1) {
3228 // First pointer is going down. Calculate edge flags and set down time.
3229 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3230 const PointerCoords& downCoords = mPointerGesture.currentGestureCoords[index];
3231 edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3232 downCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
3233 downCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3234 mPointerGesture.downTime = when;
3235 }
3236
3237 dispatchMotion(when, policyFlags, mPointerSource,
3238 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
3239 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3240 dispatchedGestureIdBits, id,
3241 0, 0, mPointerGesture.downTime);
3242 }
3243 }
3244
3245 // Send down and up for a tap.
3246 if (mPointerGesture.currentGestureMode == PointerGesture::TAP) {
3247 const PointerCoords& coords = mPointerGesture.currentGestureCoords[0];
3248 int32_t edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3249 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3250 coords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3251 nsecs_t downTime = mPointerGesture.downTime = mPointerGesture.tapTime;
3252 mPointerGesture.resetTapTime();
3253
3254 dispatchMotion(downTime, policyFlags, mPointerSource,
3255 AMOTION_EVENT_ACTION_DOWN, 0, metaState, edgeFlags,
3256 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3257 mPointerGesture.currentGestureIdBits, -1,
3258 0, 0, downTime);
3259 dispatchMotion(when, policyFlags, mPointerSource,
3260 AMOTION_EVENT_ACTION_UP, 0, metaState, edgeFlags,
3261 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3262 mPointerGesture.currentGestureIdBits, -1,
3263 0, 0, downTime);
3264 }
3265
3266 // Send motion events for hover.
3267 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
3268 dispatchMotion(when, policyFlags, mPointerSource,
3269 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3270 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3271 mPointerGesture.currentGestureIdBits, -1,
3272 0, 0, mPointerGesture.downTime);
3273 }
3274
3275 // Update state.
3276 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
3277 if (!down) {
3278 mPointerGesture.lastGesturePointerCount = 0;
3279 mPointerGesture.lastGestureIdBits.clear();
3280 } else {
3281 uint32_t currentGesturePointerCount = mPointerGesture.currentGesturePointerCount;
3282 mPointerGesture.lastGesturePointerCount = currentGesturePointerCount;
3283 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
3284 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
3285 uint32_t id = idBits.firstMarkedBit();
3286 idBits.clearBit(id);
3287 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3288 mPointerGesture.lastGestureCoords[index].copyFrom(
3289 mPointerGesture.currentGestureCoords[index]);
3290 mPointerGesture.lastGestureIdToIndex[id] = index;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003291 }
3292 }
3293}
3294
Jeff Brown96ad3972011-03-09 17:39:48 -08003295void TouchInputMapper::preparePointerGestures(nsecs_t when,
3296 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture) {
3297 *outCancelPreviousGesture = false;
3298 *outFinishPreviousGesture = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003299
Jeff Brown96ad3972011-03-09 17:39:48 -08003300 AutoMutex _l(mLock);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003301
Jeff Brown96ad3972011-03-09 17:39:48 -08003302 // Update the velocity tracker.
3303 {
3304 VelocityTracker::Position positions[MAX_POINTERS];
3305 uint32_t count = 0;
3306 for (BitSet32 idBits(mCurrentTouch.idBits); !idBits.isEmpty(); count++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07003307 uint32_t id = idBits.firstMarkedBit();
3308 idBits.clearBit(id);
Jeff Brown96ad3972011-03-09 17:39:48 -08003309 uint32_t index = mCurrentTouch.idToIndex[id];
3310 positions[count].x = mCurrentTouch.pointers[index].x
3311 * mLocked.pointerGestureXMovementScale;
3312 positions[count].y = mCurrentTouch.pointers[index].y
3313 * mLocked.pointerGestureYMovementScale;
3314 }
3315 mPointerGesture.velocityTracker.addMovement(when, mCurrentTouch.idBits, positions);
3316 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003317
Jeff Brown96ad3972011-03-09 17:39:48 -08003318 // Pick a new active touch id if needed.
3319 // Choose an arbitrary pointer that just went down, if there is one.
3320 // Otherwise choose an arbitrary remaining pointer.
3321 // This guarantees we always have an active touch id when there is at least one pointer.
3322 // We always switch to the newest pointer down because that's usually where the user's
3323 // attention is focused.
3324 int32_t activeTouchId;
3325 BitSet32 downTouchIdBits(mCurrentTouch.idBits.value & ~mLastTouch.idBits.value);
3326 if (!downTouchIdBits.isEmpty()) {
3327 activeTouchId = mPointerGesture.activeTouchId = downTouchIdBits.firstMarkedBit();
3328 } else {
3329 activeTouchId = mPointerGesture.activeTouchId;
3330 if (activeTouchId < 0 || !mCurrentTouch.idBits.hasBit(activeTouchId)) {
3331 if (!mCurrentTouch.idBits.isEmpty()) {
3332 activeTouchId = mPointerGesture.activeTouchId =
3333 mCurrentTouch.idBits.firstMarkedBit();
3334 } else {
3335 activeTouchId = mPointerGesture.activeTouchId = -1;
3336 }
3337 }
3338 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003339
Jeff Brown96ad3972011-03-09 17:39:48 -08003340 // Update the touch origin data to track where each finger originally went down.
3341 if (mCurrentTouch.pointerCount == 0 || mPointerGesture.touchOrigin.pointerCount == 0) {
3342 // Fast path when all fingers have gone up or down.
3343 mPointerGesture.touchOrigin.copyFrom(mCurrentTouch);
3344 } else {
3345 // Slow path when only some fingers have gone up or down.
3346 for (BitSet32 idBits(mPointerGesture.touchOrigin.idBits.value
3347 & ~mCurrentTouch.idBits.value); !idBits.isEmpty(); ) {
3348 uint32_t id = idBits.firstMarkedBit();
3349 idBits.clearBit(id);
3350 mPointerGesture.touchOrigin.idBits.clearBit(id);
3351 uint32_t index = mPointerGesture.touchOrigin.idToIndex[id];
3352 uint32_t count = --mPointerGesture.touchOrigin.pointerCount;
3353 while (index < count) {
3354 mPointerGesture.touchOrigin.pointers[index] =
3355 mPointerGesture.touchOrigin.pointers[index + 1];
3356 uint32_t movedId = mPointerGesture.touchOrigin.pointers[index].id;
3357 mPointerGesture.touchOrigin.idToIndex[movedId] = index;
3358 index += 1;
3359 }
3360 }
3361 for (BitSet32 idBits(mCurrentTouch.idBits.value
3362 & ~mPointerGesture.touchOrigin.idBits.value); !idBits.isEmpty(); ) {
3363 uint32_t id = idBits.firstMarkedBit();
3364 idBits.clearBit(id);
3365 mPointerGesture.touchOrigin.idBits.markBit(id);
3366 uint32_t index = mPointerGesture.touchOrigin.pointerCount++;
3367 mPointerGesture.touchOrigin.pointers[index] =
3368 mCurrentTouch.pointers[mCurrentTouch.idToIndex[id]];
3369 mPointerGesture.touchOrigin.idToIndex[id] = index;
3370 }
3371 }
3372
3373 // Determine whether we are in quiet time.
3374 bool isQuietTime = when < mPointerGesture.quietTime + QUIET_INTERVAL;
3375 if (!isQuietTime) {
3376 if ((mPointerGesture.lastGestureMode == PointerGesture::SWIPE
3377 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
3378 && mCurrentTouch.pointerCount < 2) {
3379 // Enter quiet time when exiting swipe or freeform state.
3380 // This is to prevent accidentally entering the hover state and flinging the
3381 // pointer when finishing a swipe and there is still one pointer left onscreen.
3382 isQuietTime = true;
3383 } else if (mPointerGesture.lastGestureMode == PointerGesture::CLICK_OR_DRAG
3384 && mCurrentTouch.pointerCount >= 2
3385 && !isPointerDown(mCurrentTouch.buttonState)) {
3386 // Enter quiet time when releasing the button and there are still two or more
3387 // fingers down. This may indicate that one finger was used to press the button
3388 // but it has not gone up yet.
3389 isQuietTime = true;
3390 }
3391 if (isQuietTime) {
3392 mPointerGesture.quietTime = when;
3393 }
3394 }
3395
3396 // Switch states based on button and pointer state.
3397 if (isQuietTime) {
3398 // Case 1: Quiet time. (QUIET)
3399#if DEBUG_GESTURES
3400 LOGD("Gestures: QUIET for next %0.3fms",
3401 (mPointerGesture.quietTime + QUIET_INTERVAL - when) * 0.000001f);
3402#endif
3403 *outFinishPreviousGesture = true;
3404
3405 mPointerGesture.activeGestureId = -1;
3406 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
3407 mPointerGesture.currentGesturePointerCount = 0;
3408 mPointerGesture.currentGestureIdBits.clear();
3409 } else if (isPointerDown(mCurrentTouch.buttonState)) {
3410 // Case 2: Button is pressed. (DRAG)
3411 // The pointer follows the active touch point.
3412 // Emit DOWN, MOVE, UP events at the pointer location.
3413 //
3414 // Only the active touch matters; other fingers are ignored. This policy helps
3415 // to handle the case where the user places a second finger on the touch pad
3416 // to apply the necessary force to depress an integrated button below the surface.
3417 // We don't want the second finger to be delivered to applications.
3418 //
3419 // For this to work well, we need to make sure to track the pointer that is really
3420 // active. If the user first puts one finger down to click then adds another
3421 // finger to drag then the active pointer should switch to the finger that is
3422 // being dragged.
3423#if DEBUG_GESTURES
3424 LOGD("Gestures: CLICK_OR_DRAG activeTouchId=%d, "
3425 "currentTouchPointerCount=%d", activeTouchId, mCurrentTouch.pointerCount);
3426#endif
3427 // Reset state when just starting.
3428 if (mPointerGesture.lastGestureMode != PointerGesture::CLICK_OR_DRAG) {
3429 *outFinishPreviousGesture = true;
3430 mPointerGesture.activeGestureId = 0;
3431 }
3432
3433 // Switch pointers if needed.
3434 // Find the fastest pointer and follow it.
3435 if (activeTouchId >= 0) {
3436 if (mCurrentTouch.pointerCount > 1) {
3437 int32_t bestId = -1;
3438 float bestSpeed = DRAG_MIN_SWITCH_SPEED;
3439 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3440 uint32_t id = mCurrentTouch.pointers[i].id;
3441 float vx, vy;
3442 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
3443 float speed = pythag(vx, vy);
3444 if (speed > bestSpeed) {
3445 bestId = id;
3446 bestSpeed = speed;
3447 }
3448 }
Jeff Brown8d608662010-08-30 03:02:23 -07003449 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003450 if (bestId >= 0 && bestId != activeTouchId) {
3451 mPointerGesture.activeTouchId = activeTouchId = bestId;
3452#if DEBUG_GESTURES
3453 LOGD("Gestures: CLICK_OR_DRAG switched pointers, "
3454 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
3455#endif
Jeff Brown8d608662010-08-30 03:02:23 -07003456 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003457 }
3458
Jeff Brown96ad3972011-03-09 17:39:48 -08003459 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3460 const PointerData& currentPointer =
3461 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3462 const PointerData& lastPointer =
3463 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3464 float deltaX = (currentPointer.x - lastPointer.x)
3465 * mLocked.pointerGestureXMovementScale;
3466 float deltaY = (currentPointer.y - lastPointer.y)
3467 * mLocked.pointerGestureYMovementScale;
3468 mPointerController->move(deltaX, deltaY);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003469 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003470 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003471
Jeff Brown96ad3972011-03-09 17:39:48 -08003472 float x, y;
3473 mPointerController->getPosition(&x, &y);
Jeff Brown91c69ab2011-02-14 17:03:18 -08003474
Jeff Brown96ad3972011-03-09 17:39:48 -08003475 mPointerGesture.currentGestureMode = PointerGesture::CLICK_OR_DRAG;
3476 mPointerGesture.currentGesturePointerCount = 1;
3477 mPointerGesture.currentGestureIdBits.clear();
3478 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3479 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3480 mPointerGesture.currentGestureCoords[0].clear();
3481 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3482 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3483 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3484 } else if (mCurrentTouch.pointerCount == 0) {
3485 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
3486 *outFinishPreviousGesture = true;
3487
3488 // Watch for taps coming out of HOVER or INDETERMINATE_MULTITOUCH mode.
3489 bool tapped = false;
3490 if (mPointerGesture.lastGestureMode == PointerGesture::HOVER
3491 || mPointerGesture.lastGestureMode
3492 == PointerGesture::INDETERMINATE_MULTITOUCH) {
3493 if (when <= mPointerGesture.tapTime + TAP_INTERVAL) {
3494 float x, y;
3495 mPointerController->getPosition(&x, &y);
3496 if (fabs(x - mPointerGesture.initialPointerX) <= TAP_SLOP
3497 && fabs(y - mPointerGesture.initialPointerY) <= TAP_SLOP) {
3498#if DEBUG_GESTURES
3499 LOGD("Gestures: TAP");
3500#endif
3501 mPointerGesture.activeGestureId = 0;
3502 mPointerGesture.currentGestureMode = PointerGesture::TAP;
3503 mPointerGesture.currentGesturePointerCount = 1;
3504 mPointerGesture.currentGestureIdBits.clear();
3505 mPointerGesture.currentGestureIdBits.markBit(
3506 mPointerGesture.activeGestureId);
3507 mPointerGesture.currentGestureIdToIndex[
3508 mPointerGesture.activeGestureId] = 0;
3509 mPointerGesture.currentGestureCoords[0].clear();
3510 mPointerGesture.currentGestureCoords[0].setAxisValue(
3511 AMOTION_EVENT_AXIS_X, mPointerGesture.initialPointerX);
3512 mPointerGesture.currentGestureCoords[0].setAxisValue(
3513 AMOTION_EVENT_AXIS_Y, mPointerGesture.initialPointerY);
3514 mPointerGesture.currentGestureCoords[0].setAxisValue(
3515 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3516 tapped = true;
3517 } else {
3518#if DEBUG_GESTURES
3519 LOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
3520 x - mPointerGesture.initialPointerX,
3521 y - mPointerGesture.initialPointerY);
3522#endif
3523 }
3524 } else {
3525#if DEBUG_GESTURES
3526 LOGD("Gestures: Not a TAP, delay=%lld",
3527 when - mPointerGesture.tapTime);
3528#endif
Jeff Brown6328cdc2010-07-29 18:18:33 -07003529 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003530 }
3531 if (!tapped) {
3532#if DEBUG_GESTURES
3533 LOGD("Gestures: NEUTRAL");
3534#endif
3535 mPointerGesture.activeGestureId = -1;
3536 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
3537 mPointerGesture.currentGesturePointerCount = 0;
3538 mPointerGesture.currentGestureIdBits.clear();
3539 }
3540 } else if (mCurrentTouch.pointerCount == 1) {
3541 // Case 4. Exactly one finger down, button is not pressed. (HOVER)
3542 // The pointer follows the active touch point.
3543 // Emit HOVER_MOVE events at the pointer location.
3544 assert(activeTouchId >= 0);
3545
3546#if DEBUG_GESTURES
3547 LOGD("Gestures: HOVER");
3548#endif
3549
3550 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3551 const PointerData& currentPointer =
3552 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3553 const PointerData& lastPointer =
3554 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3555 float deltaX = (currentPointer.x - lastPointer.x)
3556 * mLocked.pointerGestureXMovementScale;
3557 float deltaY = (currentPointer.y - lastPointer.y)
3558 * mLocked.pointerGestureYMovementScale;
3559 mPointerController->move(deltaX, deltaY);
3560 }
3561
3562 *outFinishPreviousGesture = true;
3563 mPointerGesture.activeGestureId = 0;
3564
3565 float x, y;
3566 mPointerController->getPosition(&x, &y);
3567
3568 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
3569 mPointerGesture.currentGesturePointerCount = 1;
3570 mPointerGesture.currentGestureIdBits.clear();
3571 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3572 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3573 mPointerGesture.currentGestureCoords[0].clear();
3574 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3575 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3576 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 0.0f);
3577
3578 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
3579 mPointerGesture.tapTime = when;
3580 mPointerGesture.initialPointerX = x;
3581 mPointerGesture.initialPointerY = y;
3582 }
3583 } else {
3584 // Case 5. At least two fingers down, button is not pressed. (SWIPE or FREEFORM
3585 // or INDETERMINATE_MULTITOUCH)
3586 // Initially we watch and wait for something interesting to happen so as to
3587 // avoid making a spurious guess as to the nature of the gesture. For example,
3588 // the fingers may be in transition to some other state such as pressing or
3589 // releasing the button or we may be performing a two finger tap.
3590 //
3591 // Fix the centroid of the figure when the gesture actually starts.
3592 // We do not recalculate the centroid at any other time during the gesture because
3593 // it would affect the relationship of the touch points relative to the pointer location.
3594 assert(activeTouchId >= 0);
3595
3596 uint32_t currentTouchPointerCount = mCurrentTouch.pointerCount;
3597 if (currentTouchPointerCount > MAX_POINTERS) {
3598 currentTouchPointerCount = MAX_POINTERS;
3599 }
3600
3601 if (mPointerGesture.lastGestureMode != PointerGesture::INDETERMINATE_MULTITOUCH
3602 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
3603 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
3604 mPointerGesture.currentGestureMode = PointerGesture::INDETERMINATE_MULTITOUCH;
3605
3606 *outFinishPreviousGesture = true;
3607 mPointerGesture.activeGestureId = -1;
3608
3609 // Remember the initial pointer location.
3610 // Everything we do will be relative to this location.
3611 mPointerController->getPosition(&mPointerGesture.initialPointerX,
3612 &mPointerGesture.initialPointerY);
3613
3614 // Track taps.
3615 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
3616 mPointerGesture.tapTime = when;
3617 }
3618
3619 // Reset the touch origin to be relative to exactly where the fingers are now
3620 // in case they have moved some distance away as part of a previous gesture.
3621 // We want to know how far the fingers have traveled since we started considering
3622 // a multitouch gesture.
3623 mPointerGesture.touchOrigin.copyFrom(mCurrentTouch);
3624 } else {
3625 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3626 }
3627
3628 if (mPointerGesture.currentGestureMode == PointerGesture::INDETERMINATE_MULTITOUCH) {
3629 // Wait for the pointers to start moving before doing anything.
3630 bool decideNow = true;
3631 for (uint32_t i = 0; i < currentTouchPointerCount; i++) {
3632 const PointerData& current = mCurrentTouch.pointers[i];
3633 const PointerData& origin = mPointerGesture.touchOrigin.pointers[
3634 mPointerGesture.touchOrigin.idToIndex[current.id]];
3635 float distance = pythag(
3636 (current.x - origin.x) * mLocked.pointerGestureXZoomScale,
3637 (current.y - origin.y) * mLocked.pointerGestureYZoomScale);
3638 if (distance < MULTITOUCH_MIN_TRAVEL) {
3639 decideNow = false;
3640 break;
3641 }
3642 }
3643
3644 if (decideNow) {
3645 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
3646 if (currentTouchPointerCount == 2
3647 && distanceSquared(
3648 mCurrentTouch.pointers[0].x, mCurrentTouch.pointers[0].y,
3649 mCurrentTouch.pointers[1].x, mCurrentTouch.pointers[1].y)
3650 <= mLocked.pointerGestureMaxSwipeWidthSquared) {
3651 const PointerData& current1 = mCurrentTouch.pointers[0];
3652 const PointerData& current2 = mCurrentTouch.pointers[1];
3653 const PointerData& origin1 = mPointerGesture.touchOrigin.pointers[
3654 mPointerGesture.touchOrigin.idToIndex[current1.id]];
3655 const PointerData& origin2 = mPointerGesture.touchOrigin.pointers[
3656 mPointerGesture.touchOrigin.idToIndex[current2.id]];
3657
3658 float x1 = (current1.x - origin1.x) * mLocked.pointerGestureXZoomScale;
3659 float y1 = (current1.y - origin1.y) * mLocked.pointerGestureYZoomScale;
3660 float x2 = (current2.x - origin2.x) * mLocked.pointerGestureXZoomScale;
3661 float y2 = (current2.y - origin2.y) * mLocked.pointerGestureYZoomScale;
3662 float magnitude1 = pythag(x1, y1);
3663 float magnitude2 = pythag(x2, y2);
3664
3665 // Calculate the dot product of the vectors.
3666 // When the vectors are oriented in approximately the same direction,
3667 // the angle betweeen them is near zero and the cosine of the angle
3668 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
3669 // We know that the magnitude is at least MULTITOUCH_MIN_TRAVEL because
3670 // we checked it above.
3671 float dot = x1 * x2 + y1 * y2;
3672 float cosine = dot / (magnitude1 * magnitude2); // denominator always > 0
3673 if (cosine > SWIPE_TRANSITION_ANGLE_COSINE) {
3674 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
3675 }
3676 }
3677
3678 // Remember the initial centroid for the duration of the gesture.
3679 mPointerGesture.initialCentroidX = 0;
3680 mPointerGesture.initialCentroidY = 0;
3681 for (uint32_t i = 0; i < currentTouchPointerCount; i++) {
3682 const PointerData& touch = mCurrentTouch.pointers[i];
3683 mPointerGesture.initialCentroidX += touch.x;
3684 mPointerGesture.initialCentroidY += touch.y;
3685 }
3686 mPointerGesture.initialCentroidX /= int32_t(currentTouchPointerCount);
3687 mPointerGesture.initialCentroidY /= int32_t(currentTouchPointerCount);
3688
3689 mPointerGesture.activeGestureId = 0;
3690 }
3691 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
3692 // Switch to FREEFORM if additional pointers go down.
3693 if (currentTouchPointerCount > 2) {
3694 *outCancelPreviousGesture = true;
3695 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003696 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003697 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003698
Jeff Brown96ad3972011-03-09 17:39:48 -08003699 if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
3700 // SWIPE mode.
3701#if DEBUG_GESTURES
3702 LOGD("Gestures: SWIPE activeTouchId=%d,"
3703 "activeGestureId=%d, currentTouchPointerCount=%d",
3704 activeTouchId, mPointerGesture.activeGestureId, currentTouchPointerCount);
3705#endif
3706 assert(mPointerGesture.activeGestureId >= 0);
3707
3708 float x = (mCurrentTouch.pointers[0].x + mCurrentTouch.pointers[1].x
3709 - mPointerGesture.initialCentroidX * 2) * 0.5f
3710 * mLocked.pointerGestureXMovementScale + mPointerGesture.initialPointerX;
3711 float y = (mCurrentTouch.pointers[0].y + mCurrentTouch.pointers[1].y
3712 - mPointerGesture.initialCentroidY * 2) * 0.5f
3713 * mLocked.pointerGestureYMovementScale + mPointerGesture.initialPointerY;
3714
3715 mPointerGesture.currentGesturePointerCount = 1;
3716 mPointerGesture.currentGestureIdBits.clear();
3717 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3718 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3719 mPointerGesture.currentGestureCoords[0].clear();
3720 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3721 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3722 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3723 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
3724 // FREEFORM mode.
3725#if DEBUG_GESTURES
3726 LOGD("Gestures: FREEFORM activeTouchId=%d,"
3727 "activeGestureId=%d, currentTouchPointerCount=%d",
3728 activeTouchId, mPointerGesture.activeGestureId, currentTouchPointerCount);
3729#endif
3730 assert(mPointerGesture.activeGestureId >= 0);
3731
3732 mPointerGesture.currentGesturePointerCount = currentTouchPointerCount;
3733 mPointerGesture.currentGestureIdBits.clear();
3734
3735 BitSet32 mappedTouchIdBits;
3736 BitSet32 usedGestureIdBits;
3737 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
3738 // Initially, assign the active gesture id to the active touch point
3739 // if there is one. No other touch id bits are mapped yet.
3740 if (!*outCancelPreviousGesture) {
3741 mappedTouchIdBits.markBit(activeTouchId);
3742 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3743 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3744 mPointerGesture.activeGestureId;
3745 } else {
3746 mPointerGesture.activeGestureId = -1;
3747 }
3748 } else {
3749 // Otherwise, assume we mapped all touches from the previous frame.
3750 // Reuse all mappings that are still applicable.
3751 mappedTouchIdBits.value = mLastTouch.idBits.value & mCurrentTouch.idBits.value;
3752 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3753
3754 // Check whether we need to choose a new active gesture id because the
3755 // current went went up.
3756 for (BitSet32 upTouchIdBits(mLastTouch.idBits.value & ~mCurrentTouch.idBits.value);
3757 !upTouchIdBits.isEmpty(); ) {
3758 uint32_t upTouchId = upTouchIdBits.firstMarkedBit();
3759 upTouchIdBits.clearBit(upTouchId);
3760 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3761 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3762 mPointerGesture.activeGestureId = -1;
3763 break;
3764 }
3765 }
3766 }
3767
3768#if DEBUG_GESTURES
3769 LOGD("Gestures: FREEFORM follow up "
3770 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3771 "activeGestureId=%d",
3772 mappedTouchIdBits.value, usedGestureIdBits.value,
3773 mPointerGesture.activeGestureId);
3774#endif
3775
3776 for (uint32_t i = 0; i < currentTouchPointerCount; i++) {
3777 uint32_t touchId = mCurrentTouch.pointers[i].id;
3778 uint32_t gestureId;
3779 if (!mappedTouchIdBits.hasBit(touchId)) {
3780 gestureId = usedGestureIdBits.firstUnmarkedBit();
3781 usedGestureIdBits.markBit(gestureId);
3782 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3783#if DEBUG_GESTURES
3784 LOGD("Gestures: FREEFORM "
3785 "new mapping for touch id %d -> gesture id %d",
3786 touchId, gestureId);
3787#endif
3788 } else {
3789 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3790#if DEBUG_GESTURES
3791 LOGD("Gestures: FREEFORM "
3792 "existing mapping for touch id %d -> gesture id %d",
3793 touchId, gestureId);
3794#endif
3795 }
3796 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3797 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3798
3799 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.initialCentroidX)
3800 * mLocked.pointerGestureXZoomScale + mPointerGesture.initialPointerX;
3801 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.initialCentroidY)
3802 * mLocked.pointerGestureYZoomScale + mPointerGesture.initialPointerY;
3803
3804 mPointerGesture.currentGestureCoords[i].clear();
3805 mPointerGesture.currentGestureCoords[i].setAxisValue(
3806 AMOTION_EVENT_AXIS_X, x);
3807 mPointerGesture.currentGestureCoords[i].setAxisValue(
3808 AMOTION_EVENT_AXIS_Y, y);
3809 mPointerGesture.currentGestureCoords[i].setAxisValue(
3810 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3811 }
3812
3813 if (mPointerGesture.activeGestureId < 0) {
3814 mPointerGesture.activeGestureId =
3815 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3816#if DEBUG_GESTURES
3817 LOGD("Gestures: FREEFORM new "
3818 "activeGestureId=%d", mPointerGesture.activeGestureId);
3819#endif
3820 }
3821 } else {
3822 // INDETERMINATE_MULTITOUCH mode.
3823 // Do nothing.
3824#if DEBUG_GESTURES
3825 LOGD("Gestures: INDETERMINATE_MULTITOUCH");
3826#endif
3827 }
3828 }
3829
3830 // Unfade the pointer if the user is doing anything with the touch pad.
3831 mPointerController->setButtonState(mCurrentTouch.buttonState);
3832 if (mCurrentTouch.buttonState || mCurrentTouch.pointerCount != 0) {
3833 mPointerController->unfade();
3834 }
3835
3836#if DEBUG_GESTURES
3837 LOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3838 "currentGestureMode=%d, currentGesturePointerCount=%d, currentGestureIdBits=0x%08x, "
3839 "lastGestureMode=%d, lastGesturePointerCount=%d, lastGestureIdBits=0x%08x",
3840 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3841 mPointerGesture.currentGestureMode, mPointerGesture.currentGesturePointerCount,
3842 mPointerGesture.currentGestureIdBits.value,
3843 mPointerGesture.lastGestureMode, mPointerGesture.lastGesturePointerCount,
3844 mPointerGesture.lastGestureIdBits.value);
3845 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
3846 uint32_t id = idBits.firstMarkedBit();
3847 idBits.clearBit(id);
3848 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3849 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3850 LOGD(" currentGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
3851 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3852 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3853 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3854 }
3855 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
3856 uint32_t id = idBits.firstMarkedBit();
3857 idBits.clearBit(id);
3858 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3859 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3860 LOGD(" lastGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
3861 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3862 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3863 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3864 }
3865#endif
3866}
3867
3868void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3869 int32_t action, int32_t flags, uint32_t metaState, int32_t edgeFlags,
3870 const PointerCoords* coords, const uint32_t* idToIndex, BitSet32 idBits,
3871 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
3872 PointerCoords pointerCoords[MAX_POINTERS];
3873 int32_t pointerIds[MAX_POINTERS];
3874 uint32_t pointerCount = 0;
3875 while (!idBits.isEmpty()) {
3876 uint32_t id = idBits.firstMarkedBit();
3877 idBits.clearBit(id);
3878 uint32_t index = idToIndex[id];
3879 pointerIds[pointerCount] = id;
3880 pointerCoords[pointerCount].copyFrom(coords[index]);
3881
3882 if (changedId >= 0 && id == uint32_t(changedId)) {
3883 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3884 }
3885
3886 pointerCount += 1;
3887 }
3888
3889 assert(pointerCount != 0);
3890
3891 if (changedId >= 0 && pointerCount == 1) {
3892 // Replace initial down and final up action.
3893 // We can compare the action without masking off the changed pointer index
3894 // because we know the index is 0.
3895 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3896 action = AMOTION_EVENT_ACTION_DOWN;
3897 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
3898 action = AMOTION_EVENT_ACTION_UP;
3899 } else {
3900 // Can't happen.
3901 assert(false);
3902 }
3903 }
3904
3905 getDispatcher()->notifyMotion(when, getDeviceId(), source, policyFlags,
3906 action, flags, metaState, edgeFlags,
3907 pointerCount, pointerIds, pointerCoords, xPrecision, yPrecision, downTime);
3908}
3909
3910bool TouchInputMapper::updateMovedPointerCoords(
3911 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
3912 PointerCoords* outCoords, const uint32_t* outIdToIndex, BitSet32 idBits) const {
3913 bool changed = false;
3914 while (!idBits.isEmpty()) {
3915 uint32_t id = idBits.firstMarkedBit();
3916 idBits.clearBit(id);
3917
3918 uint32_t inIndex = inIdToIndex[id];
3919 uint32_t outIndex = outIdToIndex[id];
3920 const PointerCoords& curInCoords = inCoords[inIndex];
3921 PointerCoords& curOutCoords = outCoords[outIndex];
3922
3923 if (curInCoords != curOutCoords) {
3924 curOutCoords.copyFrom(curInCoords);
3925 changed = true;
3926 }
3927 }
3928 return changed;
3929}
3930
3931void TouchInputMapper::fadePointer() {
3932 { // acquire lock
3933 AutoMutex _l(mLock);
3934 if (mPointerController != NULL) {
3935 mPointerController->fade();
3936 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003937 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003938}
3939
Jeff Brown6328cdc2010-07-29 18:18:33 -07003940bool TouchInputMapper::isPointInsideSurfaceLocked(int32_t x, int32_t y) {
Jeff Brown9626b142011-03-03 02:09:54 -08003941 return x >= mRawAxes.x.minValue && x <= mRawAxes.x.maxValue
3942 && y >= mRawAxes.y.minValue && y <= mRawAxes.y.maxValue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07003943}
3944
Jeff Brown6328cdc2010-07-29 18:18:33 -07003945const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHitLocked(
3946 int32_t x, int32_t y) {
3947 size_t numVirtualKeys = mLocked.virtualKeys.size();
3948 for (size_t i = 0; i < numVirtualKeys; i++) {
3949 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07003950
3951#if DEBUG_VIRTUAL_KEYS
3952 LOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3953 "left=%d, top=%d, right=%d, bottom=%d",
3954 x, y,
3955 virtualKey.keyCode, virtualKey.scanCode,
3956 virtualKey.hitLeft, virtualKey.hitTop,
3957 virtualKey.hitRight, virtualKey.hitBottom);
3958#endif
3959
3960 if (virtualKey.isHit(x, y)) {
3961 return & virtualKey;
3962 }
3963 }
3964
3965 return NULL;
3966}
3967
3968void TouchInputMapper::calculatePointerIds() {
3969 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
3970 uint32_t lastPointerCount = mLastTouch.pointerCount;
3971
3972 if (currentPointerCount == 0) {
3973 // No pointers to assign.
3974 mCurrentTouch.idBits.clear();
3975 } else if (lastPointerCount == 0) {
3976 // All pointers are new.
3977 mCurrentTouch.idBits.clear();
3978 for (uint32_t i = 0; i < currentPointerCount; i++) {
3979 mCurrentTouch.pointers[i].id = i;
3980 mCurrentTouch.idToIndex[i] = i;
3981 mCurrentTouch.idBits.markBit(i);
3982 }
3983 } else if (currentPointerCount == 1 && lastPointerCount == 1) {
3984 // Only one pointer and no change in count so it must have the same id as before.
3985 uint32_t id = mLastTouch.pointers[0].id;
3986 mCurrentTouch.pointers[0].id = id;
3987 mCurrentTouch.idToIndex[id] = 0;
3988 mCurrentTouch.idBits.value = BitSet32::valueForBit(id);
3989 } else {
3990 // General case.
3991 // We build a heap of squared euclidean distances between current and last pointers
3992 // associated with the current and last pointer indices. Then, we find the best
3993 // match (by distance) for each current pointer.
3994 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3995
3996 uint32_t heapSize = 0;
3997 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3998 currentPointerIndex++) {
3999 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
4000 lastPointerIndex++) {
4001 int64_t deltaX = mCurrentTouch.pointers[currentPointerIndex].x
4002 - mLastTouch.pointers[lastPointerIndex].x;
4003 int64_t deltaY = mCurrentTouch.pointers[currentPointerIndex].y
4004 - mLastTouch.pointers[lastPointerIndex].y;
4005
4006 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4007
4008 // Insert new element into the heap (sift up).
4009 heap[heapSize].currentPointerIndex = currentPointerIndex;
4010 heap[heapSize].lastPointerIndex = lastPointerIndex;
4011 heap[heapSize].distance = distance;
4012 heapSize += 1;
4013 }
4014 }
4015
4016 // Heapify
4017 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
4018 startIndex -= 1;
4019 for (uint32_t parentIndex = startIndex; ;) {
4020 uint32_t childIndex = parentIndex * 2 + 1;
4021 if (childIndex >= heapSize) {
4022 break;
4023 }
4024
4025 if (childIndex + 1 < heapSize
4026 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4027 childIndex += 1;
4028 }
4029
4030 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4031 break;
4032 }
4033
4034 swap(heap[parentIndex], heap[childIndex]);
4035 parentIndex = childIndex;
4036 }
4037 }
4038
4039#if DEBUG_POINTER_ASSIGNMENT
4040 LOGD("calculatePointerIds - initial distance min-heap: size=%d", heapSize);
4041 for (size_t i = 0; i < heapSize; i++) {
4042 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4043 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4044 heap[i].distance);
4045 }
4046#endif
4047
4048 // Pull matches out by increasing order of distance.
4049 // To avoid reassigning pointers that have already been matched, the loop keeps track
4050 // of which last and current pointers have been matched using the matchedXXXBits variables.
4051 // It also tracks the used pointer id bits.
4052 BitSet32 matchedLastBits(0);
4053 BitSet32 matchedCurrentBits(0);
4054 BitSet32 usedIdBits(0);
4055 bool first = true;
4056 for (uint32_t i = min(currentPointerCount, lastPointerCount); i > 0; i--) {
4057 for (;;) {
4058 if (first) {
4059 // The first time through the loop, we just consume the root element of
4060 // the heap (the one with smallest distance).
4061 first = false;
4062 } else {
4063 // Previous iterations consumed the root element of the heap.
4064 // Pop root element off of the heap (sift down).
4065 heapSize -= 1;
4066 assert(heapSize > 0);
4067
4068 // Sift down.
4069 heap[0] = heap[heapSize];
4070 for (uint32_t parentIndex = 0; ;) {
4071 uint32_t childIndex = parentIndex * 2 + 1;
4072 if (childIndex >= heapSize) {
4073 break;
4074 }
4075
4076 if (childIndex + 1 < heapSize
4077 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4078 childIndex += 1;
4079 }
4080
4081 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4082 break;
4083 }
4084
4085 swap(heap[parentIndex], heap[childIndex]);
4086 parentIndex = childIndex;
4087 }
4088
4089#if DEBUG_POINTER_ASSIGNMENT
4090 LOGD("calculatePointerIds - reduced distance min-heap: size=%d", heapSize);
4091 for (size_t i = 0; i < heapSize; i++) {
4092 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4093 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4094 heap[i].distance);
4095 }
4096#endif
4097 }
4098
4099 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4100 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4101
4102 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4103 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4104
4105 matchedCurrentBits.markBit(currentPointerIndex);
4106 matchedLastBits.markBit(lastPointerIndex);
4107
4108 uint32_t id = mLastTouch.pointers[lastPointerIndex].id;
4109 mCurrentTouch.pointers[currentPointerIndex].id = id;
4110 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4111 usedIdBits.markBit(id);
4112
4113#if DEBUG_POINTER_ASSIGNMENT
4114 LOGD("calculatePointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
4115 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
4116#endif
4117 break;
4118 }
4119 }
4120
4121 // Assign fresh ids to new pointers.
4122 if (currentPointerCount > lastPointerCount) {
4123 for (uint32_t i = currentPointerCount - lastPointerCount; ;) {
4124 uint32_t currentPointerIndex = matchedCurrentBits.firstUnmarkedBit();
4125 uint32_t id = usedIdBits.firstUnmarkedBit();
4126
4127 mCurrentTouch.pointers[currentPointerIndex].id = id;
4128 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4129 usedIdBits.markBit(id);
4130
4131#if DEBUG_POINTER_ASSIGNMENT
4132 LOGD("calculatePointerIds - assigned: cur=%d, id=%d",
4133 currentPointerIndex, id);
4134#endif
4135
4136 if (--i == 0) break; // done
4137 matchedCurrentBits.markBit(currentPointerIndex);
4138 }
4139 }
4140
4141 // Fix id bits.
4142 mCurrentTouch.idBits = usedIdBits;
4143 }
4144}
4145
4146/* Special hack for devices that have bad screen data: if one of the
4147 * points has moved more than a screen height from the last position,
4148 * then drop it. */
4149bool TouchInputMapper::applyBadTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004150 uint32_t pointerCount = mCurrentTouch.pointerCount;
4151
4152 // Nothing to do if there are no points.
4153 if (pointerCount == 0) {
4154 return false;
4155 }
4156
4157 // Don't do anything if a finger is going down or up. We run
4158 // here before assigning pointer IDs, so there isn't a good
4159 // way to do per-finger matching.
4160 if (pointerCount != mLastTouch.pointerCount) {
4161 return false;
4162 }
4163
4164 // We consider a single movement across more than a 7/16 of
4165 // the long size of the screen to be bad. This was a magic value
4166 // determined by looking at the maximum distance it is feasible
4167 // to actually move in one sample.
Jeff Brown9626b142011-03-03 02:09:54 -08004168 int32_t maxDeltaY = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) * 7 / 16;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004169
4170 // XXX The original code in InputDevice.java included commented out
4171 // code for testing the X axis. Note that when we drop a point
4172 // we don't actually restore the old X either. Strange.
4173 // The old code also tries to track when bad points were previously
4174 // detected but it turns out that due to the placement of a "break"
4175 // at the end of the loop, we never set mDroppedBadPoint to true
4176 // so it is effectively dead code.
4177 // Need to figure out if the old code is busted or just overcomplicated
4178 // but working as intended.
4179
4180 // Look through all new points and see if any are farther than
4181 // acceptable from all previous points.
4182 for (uint32_t i = pointerCount; i-- > 0; ) {
4183 int32_t y = mCurrentTouch.pointers[i].y;
4184 int32_t closestY = INT_MAX;
4185 int32_t closestDeltaY = 0;
4186
4187#if DEBUG_HACKS
4188 LOGD("BadTouchFilter: Looking at next point #%d: y=%d", i, y);
4189#endif
4190
4191 for (uint32_t j = pointerCount; j-- > 0; ) {
4192 int32_t lastY = mLastTouch.pointers[j].y;
4193 int32_t deltaY = abs(y - lastY);
4194
4195#if DEBUG_HACKS
4196 LOGD("BadTouchFilter: Comparing with last point #%d: y=%d deltaY=%d",
4197 j, lastY, deltaY);
4198#endif
4199
4200 if (deltaY < maxDeltaY) {
4201 goto SkipSufficientlyClosePoint;
4202 }
4203 if (deltaY < closestDeltaY) {
4204 closestDeltaY = deltaY;
4205 closestY = lastY;
4206 }
4207 }
4208
4209 // Must not have found a close enough match.
4210#if DEBUG_HACKS
4211 LOGD("BadTouchFilter: Dropping bad point #%d: newY=%d oldY=%d deltaY=%d maxDeltaY=%d",
4212 i, y, closestY, closestDeltaY, maxDeltaY);
4213#endif
4214
4215 mCurrentTouch.pointers[i].y = closestY;
4216 return true; // XXX original code only corrects one point
4217
4218 SkipSufficientlyClosePoint: ;
4219 }
4220
4221 // No change.
4222 return false;
4223}
4224
4225/* Special hack for devices that have bad screen data: drop points where
4226 * the coordinate value for one axis has jumped to the other pointer's location.
4227 */
4228bool TouchInputMapper::applyJumpyTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004229 uint32_t pointerCount = mCurrentTouch.pointerCount;
4230 if (mLastTouch.pointerCount != pointerCount) {
4231#if DEBUG_HACKS
4232 LOGD("JumpyTouchFilter: Different pointer count %d -> %d",
4233 mLastTouch.pointerCount, pointerCount);
4234 for (uint32_t i = 0; i < pointerCount; i++) {
4235 LOGD(" Pointer %d (%d, %d)", i,
4236 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4237 }
4238#endif
4239
4240 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_TRANSITION_DROPS) {
4241 if (mLastTouch.pointerCount == 1 && pointerCount == 2) {
4242 // Just drop the first few events going from 1 to 2 pointers.
4243 // They're bad often enough that they're not worth considering.
4244 mCurrentTouch.pointerCount = 1;
4245 mJumpyTouchFilter.jumpyPointsDropped += 1;
4246
4247#if DEBUG_HACKS
4248 LOGD("JumpyTouchFilter: Pointer 2 dropped");
4249#endif
4250 return true;
4251 } else if (mLastTouch.pointerCount == 2 && pointerCount == 1) {
4252 // The event when we go from 2 -> 1 tends to be messed up too
4253 mCurrentTouch.pointerCount = 2;
4254 mCurrentTouch.pointers[0] = mLastTouch.pointers[0];
4255 mCurrentTouch.pointers[1] = mLastTouch.pointers[1];
4256 mJumpyTouchFilter.jumpyPointsDropped += 1;
4257
4258#if DEBUG_HACKS
4259 for (int32_t i = 0; i < 2; i++) {
4260 LOGD("JumpyTouchFilter: Pointer %d replaced (%d, %d)", i,
4261 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4262 }
4263#endif
4264 return true;
4265 }
4266 }
4267 // Reset jumpy points dropped on other transitions or if limit exceeded.
4268 mJumpyTouchFilter.jumpyPointsDropped = 0;
4269
4270#if DEBUG_HACKS
4271 LOGD("JumpyTouchFilter: Transition - drop limit reset");
4272#endif
4273 return false;
4274 }
4275
4276 // We have the same number of pointers as last time.
4277 // A 'jumpy' point is one where the coordinate value for one axis
4278 // has jumped to the other pointer's location. No need to do anything
4279 // else if we only have one pointer.
4280 if (pointerCount < 2) {
4281 return false;
4282 }
4283
4284 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_DROP_LIMIT) {
Jeff Brown9626b142011-03-03 02:09:54 -08004285 int jumpyEpsilon = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) / JUMPY_EPSILON_DIVISOR;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004286
4287 // We only replace the single worst jumpy point as characterized by pointer distance
4288 // in a single axis.
4289 int32_t badPointerIndex = -1;
4290 int32_t badPointerReplacementIndex = -1;
4291 int32_t badPointerDistance = INT_MIN; // distance to be corrected
4292
4293 for (uint32_t i = pointerCount; i-- > 0; ) {
4294 int32_t x = mCurrentTouch.pointers[i].x;
4295 int32_t y = mCurrentTouch.pointers[i].y;
4296
4297#if DEBUG_HACKS
4298 LOGD("JumpyTouchFilter: Point %d (%d, %d)", i, x, y);
4299#endif
4300
4301 // Check if a touch point is too close to another's coordinates
4302 bool dropX = false, dropY = false;
4303 for (uint32_t j = 0; j < pointerCount; j++) {
4304 if (i == j) {
4305 continue;
4306 }
4307
4308 if (abs(x - mCurrentTouch.pointers[j].x) <= jumpyEpsilon) {
4309 dropX = true;
4310 break;
4311 }
4312
4313 if (abs(y - mCurrentTouch.pointers[j].y) <= jumpyEpsilon) {
4314 dropY = true;
4315 break;
4316 }
4317 }
4318 if (! dropX && ! dropY) {
4319 continue; // not jumpy
4320 }
4321
4322 // Find a replacement candidate by comparing with older points on the
4323 // complementary (non-jumpy) axis.
4324 int32_t distance = INT_MIN; // distance to be corrected
4325 int32_t replacementIndex = -1;
4326
4327 if (dropX) {
4328 // X looks too close. Find an older replacement point with a close Y.
4329 int32_t smallestDeltaY = INT_MAX;
4330 for (uint32_t j = 0; j < pointerCount; j++) {
4331 int32_t deltaY = abs(y - mLastTouch.pointers[j].y);
4332 if (deltaY < smallestDeltaY) {
4333 smallestDeltaY = deltaY;
4334 replacementIndex = j;
4335 }
4336 }
4337 distance = abs(x - mLastTouch.pointers[replacementIndex].x);
4338 } else {
4339 // Y looks too close. Find an older replacement point with a close X.
4340 int32_t smallestDeltaX = INT_MAX;
4341 for (uint32_t j = 0; j < pointerCount; j++) {
4342 int32_t deltaX = abs(x - mLastTouch.pointers[j].x);
4343 if (deltaX < smallestDeltaX) {
4344 smallestDeltaX = deltaX;
4345 replacementIndex = j;
4346 }
4347 }
4348 distance = abs(y - mLastTouch.pointers[replacementIndex].y);
4349 }
4350
4351 // If replacing this pointer would correct a worse error than the previous ones
4352 // considered, then use this replacement instead.
4353 if (distance > badPointerDistance) {
4354 badPointerIndex = i;
4355 badPointerReplacementIndex = replacementIndex;
4356 badPointerDistance = distance;
4357 }
4358 }
4359
4360 // Correct the jumpy pointer if one was found.
4361 if (badPointerIndex >= 0) {
4362#if DEBUG_HACKS
4363 LOGD("JumpyTouchFilter: Replacing bad pointer %d with (%d, %d)",
4364 badPointerIndex,
4365 mLastTouch.pointers[badPointerReplacementIndex].x,
4366 mLastTouch.pointers[badPointerReplacementIndex].y);
4367#endif
4368
4369 mCurrentTouch.pointers[badPointerIndex].x =
4370 mLastTouch.pointers[badPointerReplacementIndex].x;
4371 mCurrentTouch.pointers[badPointerIndex].y =
4372 mLastTouch.pointers[badPointerReplacementIndex].y;
4373 mJumpyTouchFilter.jumpyPointsDropped += 1;
4374 return true;
4375 }
4376 }
4377
4378 mJumpyTouchFilter.jumpyPointsDropped = 0;
4379 return false;
4380}
4381
4382/* Special hack for devices that have bad screen data: aggregate and
4383 * compute averages of the coordinate data, to reduce the amount of
4384 * jitter seen by applications. */
4385void TouchInputMapper::applyAveragingTouchFilter() {
4386 for (uint32_t currentIndex = 0; currentIndex < mCurrentTouch.pointerCount; currentIndex++) {
4387 uint32_t id = mCurrentTouch.pointers[currentIndex].id;
4388 int32_t x = mCurrentTouch.pointers[currentIndex].x;
4389 int32_t y = mCurrentTouch.pointers[currentIndex].y;
Jeff Brown8d608662010-08-30 03:02:23 -07004390 int32_t pressure;
4391 switch (mCalibration.pressureSource) {
4392 case Calibration::PRESSURE_SOURCE_PRESSURE:
4393 pressure = mCurrentTouch.pointers[currentIndex].pressure;
4394 break;
4395 case Calibration::PRESSURE_SOURCE_TOUCH:
4396 pressure = mCurrentTouch.pointers[currentIndex].touchMajor;
4397 break;
4398 default:
4399 pressure = 1;
4400 break;
4401 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004402
4403 if (mLastTouch.idBits.hasBit(id)) {
4404 // Pointer was down before and is still down now.
4405 // Compute average over history trace.
4406 uint32_t start = mAveragingTouchFilter.historyStart[id];
4407 uint32_t end = mAveragingTouchFilter.historyEnd[id];
4408
4409 int64_t deltaX = x - mAveragingTouchFilter.historyData[end].pointers[id].x;
4410 int64_t deltaY = y - mAveragingTouchFilter.historyData[end].pointers[id].y;
4411 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4412
4413#if DEBUG_HACKS
4414 LOGD("AveragingTouchFilter: Pointer id %d - Distance from last sample: %lld",
4415 id, distance);
4416#endif
4417
4418 if (distance < AVERAGING_DISTANCE_LIMIT) {
4419 // Increment end index in preparation for recording new historical data.
4420 end += 1;
4421 if (end > AVERAGING_HISTORY_SIZE) {
4422 end = 0;
4423 }
4424
4425 // If the end index has looped back to the start index then we have filled
4426 // the historical trace up to the desired size so we drop the historical
4427 // data at the start of the trace.
4428 if (end == start) {
4429 start += 1;
4430 if (start > AVERAGING_HISTORY_SIZE) {
4431 start = 0;
4432 }
4433 }
4434
4435 // Add the raw data to the historical trace.
4436 mAveragingTouchFilter.historyStart[id] = start;
4437 mAveragingTouchFilter.historyEnd[id] = end;
4438 mAveragingTouchFilter.historyData[end].pointers[id].x = x;
4439 mAveragingTouchFilter.historyData[end].pointers[id].y = y;
4440 mAveragingTouchFilter.historyData[end].pointers[id].pressure = pressure;
4441
4442 // Average over all historical positions in the trace by total pressure.
4443 int32_t averagedX = 0;
4444 int32_t averagedY = 0;
4445 int32_t totalPressure = 0;
4446 for (;;) {
4447 int32_t historicalX = mAveragingTouchFilter.historyData[start].pointers[id].x;
4448 int32_t historicalY = mAveragingTouchFilter.historyData[start].pointers[id].y;
4449 int32_t historicalPressure = mAveragingTouchFilter.historyData[start]
4450 .pointers[id].pressure;
4451
4452 averagedX += historicalX * historicalPressure;
4453 averagedY += historicalY * historicalPressure;
4454 totalPressure += historicalPressure;
4455
4456 if (start == end) {
4457 break;
4458 }
4459
4460 start += 1;
4461 if (start > AVERAGING_HISTORY_SIZE) {
4462 start = 0;
4463 }
4464 }
4465
Jeff Brown8d608662010-08-30 03:02:23 -07004466 if (totalPressure != 0) {
4467 averagedX /= totalPressure;
4468 averagedY /= totalPressure;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004469
4470#if DEBUG_HACKS
Jeff Brown8d608662010-08-30 03:02:23 -07004471 LOGD("AveragingTouchFilter: Pointer id %d - "
4472 "totalPressure=%d, averagedX=%d, averagedY=%d", id, totalPressure,
4473 averagedX, averagedY);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004474#endif
4475
Jeff Brown8d608662010-08-30 03:02:23 -07004476 mCurrentTouch.pointers[currentIndex].x = averagedX;
4477 mCurrentTouch.pointers[currentIndex].y = averagedY;
4478 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004479 } else {
4480#if DEBUG_HACKS
4481 LOGD("AveragingTouchFilter: Pointer id %d - Exceeded max distance", id);
4482#endif
4483 }
4484 } else {
4485#if DEBUG_HACKS
4486 LOGD("AveragingTouchFilter: Pointer id %d - Pointer went up", id);
4487#endif
4488 }
4489
4490 // Reset pointer history.
4491 mAveragingTouchFilter.historyStart[id] = 0;
4492 mAveragingTouchFilter.historyEnd[id] = 0;
4493 mAveragingTouchFilter.historyData[0].pointers[id].x = x;
4494 mAveragingTouchFilter.historyData[0].pointers[id].y = y;
4495 mAveragingTouchFilter.historyData[0].pointers[id].pressure = pressure;
4496 }
4497}
4498
4499int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004500 { // acquire lock
4501 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004502
Jeff Brown6328cdc2010-07-29 18:18:33 -07004503 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.keyCode == keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004504 return AKEY_STATE_VIRTUAL;
4505 }
4506
Jeff Brown6328cdc2010-07-29 18:18:33 -07004507 size_t numVirtualKeys = mLocked.virtualKeys.size();
4508 for (size_t i = 0; i < numVirtualKeys; i++) {
4509 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004510 if (virtualKey.keyCode == keyCode) {
4511 return AKEY_STATE_UP;
4512 }
4513 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004514 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004515
4516 return AKEY_STATE_UNKNOWN;
4517}
4518
4519int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004520 { // acquire lock
4521 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004522
Jeff Brown6328cdc2010-07-29 18:18:33 -07004523 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004524 return AKEY_STATE_VIRTUAL;
4525 }
4526
Jeff Brown6328cdc2010-07-29 18:18:33 -07004527 size_t numVirtualKeys = mLocked.virtualKeys.size();
4528 for (size_t i = 0; i < numVirtualKeys; i++) {
4529 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004530 if (virtualKey.scanCode == scanCode) {
4531 return AKEY_STATE_UP;
4532 }
4533 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004534 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004535
4536 return AKEY_STATE_UNKNOWN;
4537}
4538
4539bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4540 const int32_t* keyCodes, uint8_t* outFlags) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004541 { // acquire lock
4542 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004543
Jeff Brown6328cdc2010-07-29 18:18:33 -07004544 size_t numVirtualKeys = mLocked.virtualKeys.size();
4545 for (size_t i = 0; i < numVirtualKeys; i++) {
4546 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004547
4548 for (size_t i = 0; i < numCodes; i++) {
4549 if (virtualKey.keyCode == keyCodes[i]) {
4550 outFlags[i] = 1;
4551 }
4552 }
4553 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004554 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004555
4556 return true;
4557}
4558
4559
4560// --- SingleTouchInputMapper ---
4561
Jeff Brown47e6b1b2010-11-29 17:37:49 -08004562SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
4563 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004564 initialize();
4565}
4566
4567SingleTouchInputMapper::~SingleTouchInputMapper() {
4568}
4569
4570void SingleTouchInputMapper::initialize() {
4571 mAccumulator.clear();
4572
4573 mDown = false;
4574 mX = 0;
4575 mY = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07004576 mPressure = 0; // default to 0 for devices that don't report pressure
4577 mToolWidth = 0; // default to 0 for devices that don't report tool width
Jeff Brown96ad3972011-03-09 17:39:48 -08004578 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004579}
4580
4581void SingleTouchInputMapper::reset() {
4582 TouchInputMapper::reset();
4583
Jeff Brown6d0fec22010-07-23 21:28:06 -07004584 initialize();
4585 }
4586
4587void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
4588 switch (rawEvent->type) {
4589 case EV_KEY:
4590 switch (rawEvent->scanCode) {
4591 case BTN_TOUCH:
4592 mAccumulator.fields |= Accumulator::FIELD_BTN_TOUCH;
4593 mAccumulator.btnTouch = rawEvent->value != 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004594 // Don't sync immediately. Wait until the next SYN_REPORT since we might
4595 // not have received valid position information yet. This logic assumes that
4596 // BTN_TOUCH is always followed by SYN_REPORT as part of a complete packet.
Jeff Brown6d0fec22010-07-23 21:28:06 -07004597 break;
Jeff Brown96ad3972011-03-09 17:39:48 -08004598 default:
4599 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
4600 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
4601 if (buttonState) {
4602 if (rawEvent->value) {
4603 mAccumulator.buttonDown |= buttonState;
4604 } else {
4605 mAccumulator.buttonUp |= buttonState;
4606 }
4607 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
4608 }
4609 }
4610 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004611 }
4612 break;
4613
4614 case EV_ABS:
4615 switch (rawEvent->scanCode) {
4616 case ABS_X:
4617 mAccumulator.fields |= Accumulator::FIELD_ABS_X;
4618 mAccumulator.absX = rawEvent->value;
4619 break;
4620 case ABS_Y:
4621 mAccumulator.fields |= Accumulator::FIELD_ABS_Y;
4622 mAccumulator.absY = rawEvent->value;
4623 break;
4624 case ABS_PRESSURE:
4625 mAccumulator.fields |= Accumulator::FIELD_ABS_PRESSURE;
4626 mAccumulator.absPressure = rawEvent->value;
4627 break;
4628 case ABS_TOOL_WIDTH:
4629 mAccumulator.fields |= Accumulator::FIELD_ABS_TOOL_WIDTH;
4630 mAccumulator.absToolWidth = rawEvent->value;
4631 break;
4632 }
4633 break;
4634
4635 case EV_SYN:
4636 switch (rawEvent->scanCode) {
4637 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004638 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004639 break;
4640 }
4641 break;
4642 }
4643}
4644
4645void SingleTouchInputMapper::sync(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004646 uint32_t fields = mAccumulator.fields;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004647 if (fields == 0) {
4648 return; // no new state changes, so nothing to do
4649 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004650
4651 if (fields & Accumulator::FIELD_BTN_TOUCH) {
4652 mDown = mAccumulator.btnTouch;
4653 }
4654
4655 if (fields & Accumulator::FIELD_ABS_X) {
4656 mX = mAccumulator.absX;
4657 }
4658
4659 if (fields & Accumulator::FIELD_ABS_Y) {
4660 mY = mAccumulator.absY;
4661 }
4662
4663 if (fields & Accumulator::FIELD_ABS_PRESSURE) {
4664 mPressure = mAccumulator.absPressure;
4665 }
4666
4667 if (fields & Accumulator::FIELD_ABS_TOOL_WIDTH) {
Jeff Brown8d608662010-08-30 03:02:23 -07004668 mToolWidth = mAccumulator.absToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004669 }
4670
Jeff Brown96ad3972011-03-09 17:39:48 -08004671 if (fields & Accumulator::FIELD_BUTTONS) {
4672 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
4673 }
4674
Jeff Brown6d0fec22010-07-23 21:28:06 -07004675 mCurrentTouch.clear();
4676
4677 if (mDown) {
4678 mCurrentTouch.pointerCount = 1;
4679 mCurrentTouch.pointers[0].id = 0;
4680 mCurrentTouch.pointers[0].x = mX;
4681 mCurrentTouch.pointers[0].y = mY;
4682 mCurrentTouch.pointers[0].pressure = mPressure;
Jeff Brown8d608662010-08-30 03:02:23 -07004683 mCurrentTouch.pointers[0].touchMajor = 0;
4684 mCurrentTouch.pointers[0].touchMinor = 0;
4685 mCurrentTouch.pointers[0].toolMajor = mToolWidth;
4686 mCurrentTouch.pointers[0].toolMinor = mToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004687 mCurrentTouch.pointers[0].orientation = 0;
4688 mCurrentTouch.idToIndex[0] = 0;
4689 mCurrentTouch.idBits.markBit(0);
Jeff Brown96ad3972011-03-09 17:39:48 -08004690 mCurrentTouch.buttonState = mButtonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004691 }
4692
4693 syncTouch(when, true);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004694
4695 mAccumulator.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07004696}
4697
Jeff Brown8d608662010-08-30 03:02:23 -07004698void SingleTouchInputMapper::configureRawAxes() {
4699 TouchInputMapper::configureRawAxes();
Jeff Brown6d0fec22010-07-23 21:28:06 -07004700
Jeff Brown8d608662010-08-30 03:02:23 -07004701 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_X, & mRawAxes.x);
4702 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_Y, & mRawAxes.y);
4703 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_PRESSURE, & mRawAxes.pressure);
4704 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_TOOL_WIDTH, & mRawAxes.toolMajor);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004705}
4706
4707
4708// --- MultiTouchInputMapper ---
4709
Jeff Brown47e6b1b2010-11-29 17:37:49 -08004710MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
4711 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004712 initialize();
4713}
4714
4715MultiTouchInputMapper::~MultiTouchInputMapper() {
4716}
4717
4718void MultiTouchInputMapper::initialize() {
4719 mAccumulator.clear();
Jeff Brown96ad3972011-03-09 17:39:48 -08004720 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004721}
4722
4723void MultiTouchInputMapper::reset() {
4724 TouchInputMapper::reset();
4725
Jeff Brown6d0fec22010-07-23 21:28:06 -07004726 initialize();
4727}
4728
4729void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
4730 switch (rawEvent->type) {
Jeff Brown96ad3972011-03-09 17:39:48 -08004731 case EV_KEY: {
4732 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
4733 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
4734 if (buttonState) {
4735 if (rawEvent->value) {
4736 mAccumulator.buttonDown |= buttonState;
4737 } else {
4738 mAccumulator.buttonUp |= buttonState;
4739 }
4740 }
4741 }
4742 break;
4743 }
4744
Jeff Brown6d0fec22010-07-23 21:28:06 -07004745 case EV_ABS: {
4746 uint32_t pointerIndex = mAccumulator.pointerCount;
4747 Accumulator::Pointer* pointer = & mAccumulator.pointers[pointerIndex];
4748
4749 switch (rawEvent->scanCode) {
4750 case ABS_MT_POSITION_X:
4751 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_X;
4752 pointer->absMTPositionX = rawEvent->value;
4753 break;
4754 case ABS_MT_POSITION_Y:
4755 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_Y;
4756 pointer->absMTPositionY = rawEvent->value;
4757 break;
4758 case ABS_MT_TOUCH_MAJOR:
4759 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MAJOR;
4760 pointer->absMTTouchMajor = rawEvent->value;
4761 break;
4762 case ABS_MT_TOUCH_MINOR:
4763 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MINOR;
4764 pointer->absMTTouchMinor = rawEvent->value;
4765 break;
4766 case ABS_MT_WIDTH_MAJOR:
4767 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MAJOR;
4768 pointer->absMTWidthMajor = rawEvent->value;
4769 break;
4770 case ABS_MT_WIDTH_MINOR:
4771 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MINOR;
4772 pointer->absMTWidthMinor = rawEvent->value;
4773 break;
4774 case ABS_MT_ORIENTATION:
4775 pointer->fields |= Accumulator::FIELD_ABS_MT_ORIENTATION;
4776 pointer->absMTOrientation = rawEvent->value;
4777 break;
4778 case ABS_MT_TRACKING_ID:
4779 pointer->fields |= Accumulator::FIELD_ABS_MT_TRACKING_ID;
4780 pointer->absMTTrackingId = rawEvent->value;
4781 break;
Jeff Brown8d608662010-08-30 03:02:23 -07004782 case ABS_MT_PRESSURE:
4783 pointer->fields |= Accumulator::FIELD_ABS_MT_PRESSURE;
4784 pointer->absMTPressure = rawEvent->value;
4785 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004786 }
4787 break;
4788 }
4789
4790 case EV_SYN:
4791 switch (rawEvent->scanCode) {
4792 case SYN_MT_REPORT: {
4793 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
4794 uint32_t pointerIndex = mAccumulator.pointerCount;
4795
4796 if (mAccumulator.pointers[pointerIndex].fields) {
4797 if (pointerIndex == MAX_POINTERS) {
4798 LOGW("MultiTouch device driver returned more than maximum of %d pointers.",
4799 MAX_POINTERS);
4800 } else {
4801 pointerIndex += 1;
4802 mAccumulator.pointerCount = pointerIndex;
4803 }
4804 }
4805
4806 mAccumulator.pointers[pointerIndex].clear();
4807 break;
4808 }
4809
4810 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004811 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004812 break;
4813 }
4814 break;
4815 }
4816}
4817
4818void MultiTouchInputMapper::sync(nsecs_t when) {
4819 static const uint32_t REQUIRED_FIELDS =
Jeff Brown8d608662010-08-30 03:02:23 -07004820 Accumulator::FIELD_ABS_MT_POSITION_X | Accumulator::FIELD_ABS_MT_POSITION_Y;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004821
Jeff Brown6d0fec22010-07-23 21:28:06 -07004822 uint32_t inCount = mAccumulator.pointerCount;
4823 uint32_t outCount = 0;
4824 bool havePointerIds = true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004825
Jeff Brown6d0fec22010-07-23 21:28:06 -07004826 mCurrentTouch.clear();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004827
Jeff Brown6d0fec22010-07-23 21:28:06 -07004828 for (uint32_t inIndex = 0; inIndex < inCount; inIndex++) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004829 const Accumulator::Pointer& inPointer = mAccumulator.pointers[inIndex];
4830 uint32_t fields = inPointer.fields;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004831
Jeff Brown6d0fec22010-07-23 21:28:06 -07004832 if ((fields & REQUIRED_FIELDS) != REQUIRED_FIELDS) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004833 // Some drivers send empty MT sync packets without X / Y to indicate a pointer up.
4834 // Drop this finger.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004835 continue;
4836 }
4837
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004838 PointerData& outPointer = mCurrentTouch.pointers[outCount];
4839 outPointer.x = inPointer.absMTPositionX;
4840 outPointer.y = inPointer.absMTPositionY;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004841
Jeff Brown8d608662010-08-30 03:02:23 -07004842 if (fields & Accumulator::FIELD_ABS_MT_PRESSURE) {
4843 if (inPointer.absMTPressure <= 0) {
Jeff Brownc3db8582010-10-20 15:33:38 -07004844 // Some devices send sync packets with X / Y but with a 0 pressure to indicate
4845 // a pointer going up. Drop this finger.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004846 continue;
4847 }
Jeff Brown8d608662010-08-30 03:02:23 -07004848 outPointer.pressure = inPointer.absMTPressure;
4849 } else {
4850 // Default pressure to 0 if absent.
4851 outPointer.pressure = 0;
4852 }
4853
4854 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MAJOR) {
4855 if (inPointer.absMTTouchMajor <= 0) {
4856 // Some devices send sync packets with X / Y but with a 0 touch major to indicate
4857 // a pointer going up. Drop this finger.
4858 continue;
4859 }
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004860 outPointer.touchMajor = inPointer.absMTTouchMajor;
4861 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004862 // Default touch area to 0 if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004863 outPointer.touchMajor = 0;
4864 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004865
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004866 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MINOR) {
4867 outPointer.touchMinor = inPointer.absMTTouchMinor;
4868 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004869 // Assume touch area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004870 outPointer.touchMinor = outPointer.touchMajor;
4871 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004872
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004873 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MAJOR) {
4874 outPointer.toolMajor = inPointer.absMTWidthMajor;
4875 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004876 // Default tool area to 0 if absent.
4877 outPointer.toolMajor = 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004878 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004879
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004880 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MINOR) {
4881 outPointer.toolMinor = inPointer.absMTWidthMinor;
4882 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004883 // Assume tool area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004884 outPointer.toolMinor = outPointer.toolMajor;
4885 }
4886
4887 if (fields & Accumulator::FIELD_ABS_MT_ORIENTATION) {
4888 outPointer.orientation = inPointer.absMTOrientation;
4889 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07004890 // Default orientation to vertical if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004891 outPointer.orientation = 0;
4892 }
4893
Jeff Brown8d608662010-08-30 03:02:23 -07004894 // Assign pointer id using tracking id if available.
Jeff Brown6d0fec22010-07-23 21:28:06 -07004895 if (havePointerIds) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004896 if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) {
4897 uint32_t id = uint32_t(inPointer.absMTTrackingId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004898
Jeff Brown6d0fec22010-07-23 21:28:06 -07004899 if (id > MAX_POINTER_ID) {
4900#if DEBUG_POINTERS
4901 LOGD("Pointers: Ignoring driver provided pointer id %d because "
Jeff Brown01ce2e92010-09-26 22:20:12 -07004902 "it is larger than max supported id %d",
Jeff Brown6d0fec22010-07-23 21:28:06 -07004903 id, MAX_POINTER_ID);
4904#endif
4905 havePointerIds = false;
4906 }
4907 else {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004908 outPointer.id = id;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004909 mCurrentTouch.idToIndex[id] = outCount;
4910 mCurrentTouch.idBits.markBit(id);
4911 }
4912 } else {
4913 havePointerIds = false;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004914 }
4915 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004916
Jeff Brown6d0fec22010-07-23 21:28:06 -07004917 outCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004918 }
4919
Jeff Brown6d0fec22010-07-23 21:28:06 -07004920 mCurrentTouch.pointerCount = outCount;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004921
Jeff Brown96ad3972011-03-09 17:39:48 -08004922 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
4923 mCurrentTouch.buttonState = mButtonState;
4924
Jeff Brown6d0fec22010-07-23 21:28:06 -07004925 syncTouch(when, havePointerIds);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004926
4927 mAccumulator.clear();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004928}
4929
Jeff Brown8d608662010-08-30 03:02:23 -07004930void MultiTouchInputMapper::configureRawAxes() {
4931 TouchInputMapper::configureRawAxes();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004932
Jeff Brown8d608662010-08-30 03:02:23 -07004933 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_X, & mRawAxes.x);
4934 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_Y, & mRawAxes.y);
4935 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MAJOR, & mRawAxes.touchMajor);
4936 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MINOR, & mRawAxes.touchMinor);
4937 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MAJOR, & mRawAxes.toolMajor);
4938 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MINOR, & mRawAxes.toolMinor);
4939 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_ORIENTATION, & mRawAxes.orientation);
4940 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_PRESSURE, & mRawAxes.pressure);
Jeff Brown9c3cda02010-06-15 01:31:58 -07004941}
4942
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004943
Jeff Browncb1404e2011-01-15 18:14:15 -08004944// --- JoystickInputMapper ---
4945
4946JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
4947 InputMapper(device) {
Jeff Browncb1404e2011-01-15 18:14:15 -08004948}
4949
4950JoystickInputMapper::~JoystickInputMapper() {
4951}
4952
4953uint32_t JoystickInputMapper::getSources() {
4954 return AINPUT_SOURCE_JOYSTICK;
4955}
4956
4957void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
4958 InputMapper::populateDeviceInfo(info);
4959
Jeff Brown6f2fba42011-02-19 01:08:02 -08004960 for (size_t i = 0; i < mAxes.size(); i++) {
4961 const Axis& axis = mAxes.valueAt(i);
Jeff Brownefd32662011-03-08 15:13:06 -08004962 info->addMotionRange(axis.axisInfo.axis, AINPUT_SOURCE_JOYSTICK,
4963 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08004964 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
Jeff Brownefd32662011-03-08 15:13:06 -08004965 info->addMotionRange(axis.axisInfo.highAxis, AINPUT_SOURCE_JOYSTICK,
4966 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08004967 }
Jeff Browncb1404e2011-01-15 18:14:15 -08004968 }
4969}
4970
4971void JoystickInputMapper::dump(String8& dump) {
4972 dump.append(INDENT2 "Joystick Input Mapper:\n");
4973
Jeff Brown6f2fba42011-02-19 01:08:02 -08004974 dump.append(INDENT3 "Axes:\n");
4975 size_t numAxes = mAxes.size();
4976 for (size_t i = 0; i < numAxes; i++) {
4977 const Axis& axis = mAxes.valueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08004978 const char* label = getAxisLabel(axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004979 if (label) {
Jeff Brown85297452011-03-04 13:07:49 -08004980 dump.appendFormat(INDENT4 "%s", label);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004981 } else {
Jeff Brown85297452011-03-04 13:07:49 -08004982 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08004983 }
Jeff Brown85297452011-03-04 13:07:49 -08004984 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
4985 label = getAxisLabel(axis.axisInfo.highAxis);
4986 if (label) {
4987 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
4988 } else {
4989 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
4990 axis.axisInfo.splitValue);
4991 }
4992 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
4993 dump.append(" (invert)");
4994 }
4995
4996 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f\n",
4997 axis.min, axis.max, axis.flat, axis.fuzz);
4998 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
4999 "highScale=%0.5f, highOffset=%0.5f\n",
5000 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005001 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, rawFlat=%d, rawFuzz=%d\n",
5002 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
5003 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz);
Jeff Browncb1404e2011-01-15 18:14:15 -08005004 }
5005}
5006
5007void JoystickInputMapper::configure() {
5008 InputMapper::configure();
5009
Jeff Brown6f2fba42011-02-19 01:08:02 -08005010 // Collect all axes.
5011 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
5012 RawAbsoluteAxisInfo rawAxisInfo;
5013 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), abs, &rawAxisInfo);
5014 if (rawAxisInfo.valid) {
Jeff Brown85297452011-03-04 13:07:49 -08005015 // Map axis.
5016 AxisInfo axisInfo;
5017 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005018 if (!explicitlyMapped) {
5019 // Axis is not explicitly mapped, will choose a generic axis later.
Jeff Brown85297452011-03-04 13:07:49 -08005020 axisInfo.mode = AxisInfo::MODE_NORMAL;
5021 axisInfo.axis = -1;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005022 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005023
Jeff Brown85297452011-03-04 13:07:49 -08005024 // Apply flat override.
5025 int32_t rawFlat = axisInfo.flatOverride < 0
5026 ? rawAxisInfo.flat : axisInfo.flatOverride;
5027
5028 // Calculate scaling factors and limits.
Jeff Brown6f2fba42011-02-19 01:08:02 -08005029 Axis axis;
Jeff Brown85297452011-03-04 13:07:49 -08005030 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
5031 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
5032 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
5033 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5034 scale, 0.0f, highScale, 0.0f,
5035 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
5036 } else if (isCenteredAxis(axisInfo.axis)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005037 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
5038 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
Jeff Brown85297452011-03-04 13:07:49 -08005039 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5040 scale, offset, scale, offset,
5041 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005042 } else {
5043 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
Jeff Brown85297452011-03-04 13:07:49 -08005044 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5045 scale, 0.0f, scale, 0.0f,
5046 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005047 }
5048
5049 // To eliminate noise while the joystick is at rest, filter out small variations
5050 // in axis values up front.
5051 axis.filter = axis.flat * 0.25f;
5052
5053 mAxes.add(abs, axis);
5054 }
5055 }
5056
5057 // If there are too many axes, start dropping them.
5058 // Prefer to keep explicitly mapped axes.
5059 if (mAxes.size() > PointerCoords::MAX_AXES) {
5060 LOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.",
5061 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
5062 pruneAxes(true);
5063 pruneAxes(false);
5064 }
5065
5066 // Assign generic axis ids to remaining axes.
5067 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
5068 size_t numAxes = mAxes.size();
5069 for (size_t i = 0; i < numAxes; i++) {
5070 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005071 if (axis.axisInfo.axis < 0) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005072 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
5073 && haveAxis(nextGenericAxisId)) {
5074 nextGenericAxisId += 1;
5075 }
5076
5077 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
Jeff Brown85297452011-03-04 13:07:49 -08005078 axis.axisInfo.axis = nextGenericAxisId;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005079 nextGenericAxisId += 1;
5080 } else {
5081 LOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
5082 "have already been assigned to other axes.",
5083 getDeviceName().string(), mAxes.keyAt(i));
5084 mAxes.removeItemsAt(i--);
5085 numAxes -= 1;
5086 }
5087 }
5088 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005089}
5090
Jeff Brown85297452011-03-04 13:07:49 -08005091bool JoystickInputMapper::haveAxis(int32_t axisId) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005092 size_t numAxes = mAxes.size();
5093 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005094 const Axis& axis = mAxes.valueAt(i);
5095 if (axis.axisInfo.axis == axisId
5096 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
5097 && axis.axisInfo.highAxis == axisId)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005098 return true;
5099 }
5100 }
5101 return false;
5102}
Jeff Browncb1404e2011-01-15 18:14:15 -08005103
Jeff Brown6f2fba42011-02-19 01:08:02 -08005104void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
5105 size_t i = mAxes.size();
5106 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
5107 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
5108 continue;
5109 }
5110 LOGI("Discarding joystick '%s' axis %d because there are too many axes.",
5111 getDeviceName().string(), mAxes.keyAt(i));
5112 mAxes.removeItemsAt(i);
5113 }
5114}
5115
5116bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
5117 switch (axis) {
5118 case AMOTION_EVENT_AXIS_X:
5119 case AMOTION_EVENT_AXIS_Y:
5120 case AMOTION_EVENT_AXIS_Z:
5121 case AMOTION_EVENT_AXIS_RX:
5122 case AMOTION_EVENT_AXIS_RY:
5123 case AMOTION_EVENT_AXIS_RZ:
5124 case AMOTION_EVENT_AXIS_HAT_X:
5125 case AMOTION_EVENT_AXIS_HAT_Y:
5126 case AMOTION_EVENT_AXIS_ORIENTATION:
Jeff Brown85297452011-03-04 13:07:49 -08005127 case AMOTION_EVENT_AXIS_RUDDER:
5128 case AMOTION_EVENT_AXIS_WHEEL:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005129 return true;
5130 default:
5131 return false;
5132 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005133}
5134
5135void JoystickInputMapper::reset() {
5136 // Recenter all axes.
5137 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Browncb1404e2011-01-15 18:14:15 -08005138
Jeff Brown6f2fba42011-02-19 01:08:02 -08005139 size_t numAxes = mAxes.size();
5140 for (size_t i = 0; i < numAxes; i++) {
5141 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005142 axis.resetValue();
Jeff Brown6f2fba42011-02-19 01:08:02 -08005143 }
5144
5145 sync(when, true /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005146
5147 InputMapper::reset();
5148}
5149
5150void JoystickInputMapper::process(const RawEvent* rawEvent) {
5151 switch (rawEvent->type) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005152 case EV_ABS: {
5153 ssize_t index = mAxes.indexOfKey(rawEvent->scanCode);
5154 if (index >= 0) {
5155 Axis& axis = mAxes.editValueAt(index);
Jeff Brown85297452011-03-04 13:07:49 -08005156 float newValue, highNewValue;
5157 switch (axis.axisInfo.mode) {
5158 case AxisInfo::MODE_INVERT:
5159 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
5160 * axis.scale + axis.offset;
5161 highNewValue = 0.0f;
5162 break;
5163 case AxisInfo::MODE_SPLIT:
5164 if (rawEvent->value < axis.axisInfo.splitValue) {
5165 newValue = (axis.axisInfo.splitValue - rawEvent->value)
5166 * axis.scale + axis.offset;
5167 highNewValue = 0.0f;
5168 } else if (rawEvent->value > axis.axisInfo.splitValue) {
5169 newValue = 0.0f;
5170 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
5171 * axis.highScale + axis.highOffset;
5172 } else {
5173 newValue = 0.0f;
5174 highNewValue = 0.0f;
5175 }
5176 break;
5177 default:
5178 newValue = rawEvent->value * axis.scale + axis.offset;
5179 highNewValue = 0.0f;
5180 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005181 }
Jeff Brown85297452011-03-04 13:07:49 -08005182 axis.newValue = newValue;
5183 axis.highNewValue = highNewValue;
Jeff Browncb1404e2011-01-15 18:14:15 -08005184 }
5185 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005186 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005187
5188 case EV_SYN:
5189 switch (rawEvent->scanCode) {
5190 case SYN_REPORT:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005191 sync(rawEvent->when, false /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005192 break;
5193 }
5194 break;
5195 }
5196}
5197
Jeff Brown6f2fba42011-02-19 01:08:02 -08005198void JoystickInputMapper::sync(nsecs_t when, bool force) {
Jeff Brown85297452011-03-04 13:07:49 -08005199 if (!filterAxes(force)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005200 return;
Jeff Browncb1404e2011-01-15 18:14:15 -08005201 }
5202
5203 int32_t metaState = mContext->getGlobalMetaState();
5204
Jeff Brown6f2fba42011-02-19 01:08:02 -08005205 PointerCoords pointerCoords;
5206 pointerCoords.clear();
5207
5208 size_t numAxes = mAxes.size();
5209 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005210 const Axis& axis = mAxes.valueAt(i);
5211 pointerCoords.setAxisValue(axis.axisInfo.axis, axis.currentValue);
5212 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5213 pointerCoords.setAxisValue(axis.axisInfo.highAxis, axis.highCurrentValue);
5214 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005215 }
5216
Jeff Brown56194eb2011-03-02 19:23:13 -08005217 // Moving a joystick axis should not wake the devide because joysticks can
5218 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
5219 // button will likely wake the device.
5220 // TODO: Use the input device configuration to control this behavior more finely.
5221 uint32_t policyFlags = 0;
5222
Jeff Brown6f2fba42011-02-19 01:08:02 -08005223 int32_t pointerId = 0;
Jeff Brown56194eb2011-03-02 19:23:13 -08005224 getDispatcher()->notifyMotion(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Jeff Brown6f2fba42011-02-19 01:08:02 -08005225 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
5226 1, &pointerId, &pointerCoords, 0, 0, 0);
Jeff Browncb1404e2011-01-15 18:14:15 -08005227}
5228
Jeff Brown85297452011-03-04 13:07:49 -08005229bool JoystickInputMapper::filterAxes(bool force) {
5230 bool atLeastOneSignificantChange = force;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005231 size_t numAxes = mAxes.size();
5232 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005233 Axis& axis = mAxes.editValueAt(i);
5234 if (force || hasValueChangedSignificantly(axis.filter,
5235 axis.newValue, axis.currentValue, axis.min, axis.max)) {
5236 axis.currentValue = axis.newValue;
5237 atLeastOneSignificantChange = true;
5238 }
5239 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5240 if (force || hasValueChangedSignificantly(axis.filter,
5241 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
5242 axis.highCurrentValue = axis.highNewValue;
5243 atLeastOneSignificantChange = true;
5244 }
5245 }
5246 }
5247 return atLeastOneSignificantChange;
5248}
5249
5250bool JoystickInputMapper::hasValueChangedSignificantly(
5251 float filter, float newValue, float currentValue, float min, float max) {
5252 if (newValue != currentValue) {
5253 // Filter out small changes in value unless the value is converging on the axis
5254 // bounds or center point. This is intended to reduce the amount of information
5255 // sent to applications by particularly noisy joysticks (such as PS3).
5256 if (fabs(newValue - currentValue) > filter
5257 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
5258 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
5259 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
5260 return true;
5261 }
5262 }
5263 return false;
5264}
5265
5266bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
5267 float filter, float newValue, float currentValue, float thresholdValue) {
5268 float newDistance = fabs(newValue - thresholdValue);
5269 if (newDistance < filter) {
5270 float oldDistance = fabs(currentValue - thresholdValue);
5271 if (newDistance < oldDistance) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005272 return true;
5273 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005274 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08005275 return false;
Jeff Browncb1404e2011-01-15 18:14:15 -08005276}
5277
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005278} // namespace android