blob: 1bc1bd1703a26d8707511019532abb8b1a901499 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070017#define LOG_TAG "InputReader"
18
19//#define LOG_NDEBUG 0
20
21// Log debug messages for each raw event received from the EventHub.
22#define DEBUG_RAW_EVENTS 0
23
24// Log debug messages about touch screen filtering hacks.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_HACKS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070026
27// Log debug messages about virtual key processing.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_VIRTUAL_KEYS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070029
30// Log debug messages about pointers.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_POINTERS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070032
Jeff Brown5c225b12010-06-16 01:53:36 -070033// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
Jeff Brownace13b12011-03-09 17:39:48 -080036// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
Jeff Brownb4ff35d2011-01-02 16:37:43 -080039#include "InputReader.h"
40
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070041#include <cutils/log.h>
Jeff Brown6b53e8d2010-11-10 16:03:06 -080042#include <ui/Keyboard.h>
Jeff Brown90655042010-12-02 13:50:46 -080043#include <ui/VirtualKeyMap.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070044
45#include <stddef.h>
Jeff Brown8d608662010-08-30 03:02:23 -070046#include <stdlib.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070047#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070048#include <errno.h>
49#include <limits.h>
Jeff Brownc5ed5912010-07-14 18:48:53 -070050#include <math.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070051
Jeff Brown8d608662010-08-30 03:02:23 -070052#define INDENT " "
Jeff Brownef3d7e82010-09-30 14:33:04 -070053#define INDENT2 " "
54#define INDENT3 " "
55#define INDENT4 " "
Jeff Brown8d608662010-08-30 03:02:23 -070056
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070057namespace android {
58
Jeff Brownace13b12011-03-09 17:39:48 -080059// --- Constants ---
60
61// Quiet time between certain gesture transitions.
62// Time to allow for all fingers or buttons to settle into a stable state before
63// starting a new gesture.
64static const nsecs_t QUIET_INTERVAL = 100 * 1000000; // 100 ms
65
66// The minimum speed that a pointer must travel for us to consider switching the active
67// touch pointer to it during a drag. This threshold is set to avoid switching due
68// to noise from a finger resting on the touch pad (perhaps just pressing it down).
69static const float DRAG_MIN_SWITCH_SPEED = 50.0f; // pixels per second
70
71// Tap gesture delay time.
72// The time between down and up must be less than this to be considered a tap.
Jeff Brown2352b972011-04-12 22:39:53 -070073static const nsecs_t TAP_INTERVAL = 150 * 1000000; // 150 ms
Jeff Brownace13b12011-03-09 17:39:48 -080074
75// The distance in pixels that the pointer is allowed to move from initial down
76// to up and still be called a tap.
77static const float TAP_SLOP = 5.0f; // 5 pixels
78
Jeff Brown2352b972011-04-12 22:39:53 -070079// Time after the first touch points go down to settle on an initial centroid.
80// This is intended to be enough time to handle cases where the user puts down two
81// fingers at almost but not quite exactly the same time.
82static const nsecs_t MULTITOUCH_SETTLE_INTERVAL = 100 * 1000000; // 100ms
Jeff Brownace13b12011-03-09 17:39:48 -080083
Jeff Brown2352b972011-04-12 22:39:53 -070084// The transition from PRESS to SWIPE or FREEFORM gesture mode is made when
85// both of the pointers are moving at least this fast.
86static const float MULTITOUCH_MIN_SPEED = 150.0f; // pixels per second
87
88// The transition from PRESS to SWIPE gesture mode can only occur when the
Jeff Brownace13b12011-03-09 17:39:48 -080089// cosine of the angle between the two vectors is greater than or equal to than this value
90// which indicates that the vectors are oriented in the same direction.
91// When the vectors are oriented in the exactly same direction, the cosine is 1.0.
92// (In exactly opposite directions, the cosine is -1.0.)
93static const float SWIPE_TRANSITION_ANGLE_COSINE = 0.5f; // cosine of 45 degrees
94
Jeff Brown2352b972011-04-12 22:39:53 -070095// The transition from PRESS to SWIPE gesture mode can only occur when the
96// fingers are no more than this far apart relative to the diagonal size of
97// the touch pad. For example, a ratio of 0.5 means that the fingers must be
98// no more than half the diagonal size of the touch pad apart.
99static const float SWIPE_MAX_WIDTH_RATIO = 0.333f; // 1/3
100
101// The gesture movement speed factor relative to the size of the display.
102// Movement speed applies when the fingers are moving in the same direction.
103// Without acceleration, a full swipe of the touch pad diagonal in movement mode
104// will cover this portion of the display diagonal.
105static const float GESTURE_MOVEMENT_SPEED_RATIO = 0.8f;
106
107// The gesture zoom speed factor relative to the size of the display.
108// Zoom speed applies when the fingers are mostly moving relative to each other
109// to execute a scale gesture or similar.
110// Without acceleration, a full swipe of the touch pad diagonal in zoom mode
111// will cover this portion of the display diagonal.
112static const float GESTURE_ZOOM_SPEED_RATIO = 0.3f;
113
Jeff Brownace13b12011-03-09 17:39:48 -0800114
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700115// --- Static Functions ---
116
117template<typename T>
118inline static T abs(const T& value) {
119 return value < 0 ? - value : value;
120}
121
122template<typename T>
123inline static T min(const T& a, const T& b) {
124 return a < b ? a : b;
125}
126
Jeff Brown5c225b12010-06-16 01:53:36 -0700127template<typename T>
128inline static void swap(T& a, T& b) {
129 T temp = a;
130 a = b;
131 b = temp;
132}
133
Jeff Brown8d608662010-08-30 03:02:23 -0700134inline static float avg(float x, float y) {
135 return (x + y) / 2;
136}
137
Jeff Brown2352b972011-04-12 22:39:53 -0700138inline static float distance(float x1, float y1, float x2, float y2) {
139 return hypotf(x1 - x2, y1 - y2);
Jeff Brownace13b12011-03-09 17:39:48 -0800140}
141
Jeff Brown517bb4c2011-01-14 19:09:23 -0800142inline static int32_t signExtendNybble(int32_t value) {
143 return value >= 8 ? value - 16 : value;
144}
145
Jeff Brownef3d7e82010-09-30 14:33:04 -0700146static inline const char* toString(bool value) {
147 return value ? "true" : "false";
148}
149
Jeff Brown9626b142011-03-03 02:09:54 -0800150static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
151 const int32_t map[][4], size_t mapSize) {
152 if (orientation != DISPLAY_ORIENTATION_0) {
153 for (size_t i = 0; i < mapSize; i++) {
154 if (value == map[i][0]) {
155 return map[i][orientation];
156 }
157 }
158 }
159 return value;
160}
161
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700162static const int32_t keyCodeRotationMap[][4] = {
163 // key codes enumerated counter-clockwise with the original (unrotated) key first
164 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
Jeff Brownfd0358292010-06-30 16:10:35 -0700165 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
166 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
167 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
168 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700169};
Jeff Brown9626b142011-03-03 02:09:54 -0800170static const size_t keyCodeRotationMapSize =
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700171 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
172
173int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Jeff Brown9626b142011-03-03 02:09:54 -0800174 return rotateValueUsingRotationMap(keyCode, orientation,
175 keyCodeRotationMap, keyCodeRotationMapSize);
176}
177
178static const int32_t edgeFlagRotationMap[][4] = {
179 // edge flags enumerated counter-clockwise with the original (unrotated) edge flag first
180 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
181 { AMOTION_EVENT_EDGE_FLAG_BOTTOM, AMOTION_EVENT_EDGE_FLAG_RIGHT,
182 AMOTION_EVENT_EDGE_FLAG_TOP, AMOTION_EVENT_EDGE_FLAG_LEFT },
183 { AMOTION_EVENT_EDGE_FLAG_RIGHT, AMOTION_EVENT_EDGE_FLAG_TOP,
184 AMOTION_EVENT_EDGE_FLAG_LEFT, AMOTION_EVENT_EDGE_FLAG_BOTTOM },
185 { AMOTION_EVENT_EDGE_FLAG_TOP, AMOTION_EVENT_EDGE_FLAG_LEFT,
186 AMOTION_EVENT_EDGE_FLAG_BOTTOM, AMOTION_EVENT_EDGE_FLAG_RIGHT },
187 { AMOTION_EVENT_EDGE_FLAG_LEFT, AMOTION_EVENT_EDGE_FLAG_BOTTOM,
188 AMOTION_EVENT_EDGE_FLAG_RIGHT, AMOTION_EVENT_EDGE_FLAG_TOP },
189};
190static const size_t edgeFlagRotationMapSize =
191 sizeof(edgeFlagRotationMap) / sizeof(edgeFlagRotationMap[0]);
192
193static int32_t rotateEdgeFlag(int32_t edgeFlag, int32_t orientation) {
194 return rotateValueUsingRotationMap(edgeFlag, orientation,
195 edgeFlagRotationMap, edgeFlagRotationMapSize);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700196}
197
Jeff Brown6d0fec22010-07-23 21:28:06 -0700198static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
199 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
200}
201
Jeff Brownefd32662011-03-08 15:13:06 -0800202static uint32_t getButtonStateForScanCode(int32_t scanCode) {
203 // Currently all buttons are mapped to the primary button.
204 switch (scanCode) {
205 case BTN_LEFT:
206 case BTN_RIGHT:
207 case BTN_MIDDLE:
208 case BTN_SIDE:
209 case BTN_EXTRA:
210 case BTN_FORWARD:
211 case BTN_BACK:
212 case BTN_TASK:
213 return BUTTON_STATE_PRIMARY;
214 default:
215 return 0;
216 }
217}
218
219// Returns true if the pointer should be reported as being down given the specified
220// button states.
221static bool isPointerDown(uint32_t buttonState) {
222 return buttonState & BUTTON_STATE_PRIMARY;
223}
224
225static int32_t calculateEdgeFlagsUsingPointerBounds(
226 const sp<PointerControllerInterface>& pointerController, float x, float y) {
227 int32_t edgeFlags = 0;
228 float minX, minY, maxX, maxY;
229 if (pointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
230 if (x <= minX) {
231 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_LEFT;
232 } else if (x >= maxX) {
233 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_RIGHT;
234 }
235 if (y <= minY) {
236 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_TOP;
237 } else if (y >= maxY) {
238 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_BOTTOM;
239 }
240 }
241 return edgeFlags;
242}
243
Jeff Brown2352b972011-04-12 22:39:53 -0700244static void clampPositionUsingPointerBounds(
245 const sp<PointerControllerInterface>& pointerController, float* x, float* y) {
246 float minX, minY, maxX, maxY;
247 if (pointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
248 if (*x < minX) {
249 *x = minX;
250 } else if (*x > maxX) {
251 *x = maxX;
252 }
253 if (*y < minY) {
254 *y = minY;
255 } else if (*y > maxY) {
256 *y = maxY;
257 }
258 }
259}
260
261static float calculateCommonVector(float a, float b) {
262 if (a > 0 && b > 0) {
263 return a < b ? a : b;
264 } else if (a < 0 && b < 0) {
265 return a > b ? a : b;
266 } else {
267 return 0;
268 }
269}
270
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700271
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700272// --- InputReader ---
273
274InputReader::InputReader(const sp<EventHubInterface>& eventHub,
Jeff Brown9c3cda02010-06-15 01:31:58 -0700275 const sp<InputReaderPolicyInterface>& policy,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700276 const sp<InputDispatcherInterface>& dispatcher) :
Jeff Brown6d0fec22010-07-23 21:28:06 -0700277 mEventHub(eventHub), mPolicy(policy), mDispatcher(dispatcher),
Jeff Brownaa3855d2011-03-17 01:34:19 -0700278 mGlobalMetaState(0), mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX) {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700279 configureExcludedDevices();
Jeff Brown6d0fec22010-07-23 21:28:06 -0700280 updateGlobalMetaState();
281 updateInputConfiguration();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700282}
283
284InputReader::~InputReader() {
285 for (size_t i = 0; i < mDevices.size(); i++) {
286 delete mDevices.valueAt(i);
287 }
288}
289
290void InputReader::loopOnce() {
Jeff Brownaa3855d2011-03-17 01:34:19 -0700291 int32_t timeoutMillis = -1;
292 if (mNextTimeout != LLONG_MAX) {
293 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
294 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
295 }
296
Jeff Brownb7198742011-03-18 18:14:26 -0700297 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
298 if (count) {
299 processEvents(mEventBuffer, count);
300 }
301 if (!count || timeoutMillis == 0) {
Jeff Brownaa3855d2011-03-17 01:34:19 -0700302 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
303#if DEBUG_RAW_EVENTS
304 LOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
305#endif
306 mNextTimeout = LLONG_MAX;
307 timeoutExpired(now);
308 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700309}
310
Jeff Brownb7198742011-03-18 18:14:26 -0700311void InputReader::processEvents(const RawEvent* rawEvents, size_t count) {
312 for (const RawEvent* rawEvent = rawEvents; count;) {
313 int32_t type = rawEvent->type;
314 size_t batchSize = 1;
315 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
316 int32_t deviceId = rawEvent->deviceId;
317 while (batchSize < count) {
318 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
319 || rawEvent[batchSize].deviceId != deviceId) {
320 break;
321 }
322 batchSize += 1;
323 }
324#if DEBUG_RAW_EVENTS
325 LOGD("BatchSize: %d Count: %d", batchSize, count);
326#endif
327 processEventsForDevice(deviceId, rawEvent, batchSize);
328 } else {
329 switch (rawEvent->type) {
330 case EventHubInterface::DEVICE_ADDED:
331 addDevice(rawEvent->deviceId);
332 break;
333 case EventHubInterface::DEVICE_REMOVED:
334 removeDevice(rawEvent->deviceId);
335 break;
336 case EventHubInterface::FINISHED_DEVICE_SCAN:
337 handleConfigurationChanged(rawEvent->when);
338 break;
339 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700340 LOG_ASSERT(false); // can't happen
Jeff Brownb7198742011-03-18 18:14:26 -0700341 break;
342 }
343 }
344 count -= batchSize;
345 rawEvent += batchSize;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700346 }
347}
348
Jeff Brown7342bb92010-10-01 18:55:43 -0700349void InputReader::addDevice(int32_t deviceId) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700350 String8 name = mEventHub->getDeviceName(deviceId);
351 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
352
353 InputDevice* device = createDevice(deviceId, name, classes);
354 device->configure();
355
Jeff Brown8d608662010-08-30 03:02:23 -0700356 if (device->isIgnored()) {
Jeff Brown90655042010-12-02 13:50:46 -0800357 LOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, name.string());
Jeff Brown8d608662010-08-30 03:02:23 -0700358 } else {
Jeff Brown90655042010-12-02 13:50:46 -0800359 LOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, name.string(),
Jeff Brownef3d7e82010-09-30 14:33:04 -0700360 device->getSources());
Jeff Brown8d608662010-08-30 03:02:23 -0700361 }
362
Jeff Brown6d0fec22010-07-23 21:28:06 -0700363 bool added = false;
364 { // acquire device registry writer lock
365 RWLock::AutoWLock _wl(mDeviceRegistryLock);
366
367 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
368 if (deviceIndex < 0) {
369 mDevices.add(deviceId, device);
370 added = true;
371 }
372 } // release device registry writer lock
373
374 if (! added) {
375 LOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
376 delete device;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700377 return;
378 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700379}
380
Jeff Brown7342bb92010-10-01 18:55:43 -0700381void InputReader::removeDevice(int32_t deviceId) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700382 bool removed = false;
383 InputDevice* device = NULL;
384 { // acquire device registry writer lock
385 RWLock::AutoWLock _wl(mDeviceRegistryLock);
386
387 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
388 if (deviceIndex >= 0) {
389 device = mDevices.valueAt(deviceIndex);
390 mDevices.removeItemsAt(deviceIndex, 1);
391 removed = true;
392 }
393 } // release device registry writer lock
394
395 if (! removed) {
396 LOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700397 return;
398 }
399
Jeff Brown6d0fec22010-07-23 21:28:06 -0700400 if (device->isIgnored()) {
Jeff Brown90655042010-12-02 13:50:46 -0800401 LOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Jeff Brown6d0fec22010-07-23 21:28:06 -0700402 device->getId(), device->getName().string());
403 } else {
Jeff Brown90655042010-12-02 13:50:46 -0800404 LOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Jeff Brown6d0fec22010-07-23 21:28:06 -0700405 device->getId(), device->getName().string(), device->getSources());
406 }
407
Jeff Brown8d608662010-08-30 03:02:23 -0700408 device->reset();
409
Jeff Brown6d0fec22010-07-23 21:28:06 -0700410 delete device;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700411}
412
Jeff Brown6d0fec22010-07-23 21:28:06 -0700413InputDevice* InputReader::createDevice(int32_t deviceId, const String8& name, uint32_t classes) {
414 InputDevice* device = new InputDevice(this, deviceId, name);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700415
Jeff Brown56194eb2011-03-02 19:23:13 -0800416 // External devices.
417 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
418 device->setExternal(true);
419 }
420
Jeff Brown6d0fec22010-07-23 21:28:06 -0700421 // Switch-like devices.
422 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
423 device->addMapper(new SwitchInputMapper(device));
424 }
425
426 // Keyboard-like devices.
Jeff Brownefd32662011-03-08 15:13:06 -0800427 uint32_t keyboardSource = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700428 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
429 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800430 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700431 }
432 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
433 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
434 }
435 if (classes & INPUT_DEVICE_CLASS_DPAD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800436 keyboardSource |= AINPUT_SOURCE_DPAD;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700437 }
Jeff Browncb1404e2011-01-15 18:14:15 -0800438 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800439 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
Jeff Browncb1404e2011-01-15 18:14:15 -0800440 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700441
Jeff Brownefd32662011-03-08 15:13:06 -0800442 if (keyboardSource != 0) {
443 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700444 }
445
Jeff Brown83c09682010-12-23 17:50:18 -0800446 // Cursor-like devices.
447 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
448 device->addMapper(new CursorInputMapper(device));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700449 }
450
Jeff Brown58a2da82011-01-25 16:02:22 -0800451 // Touchscreens and touchpad devices.
452 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800453 device->addMapper(new MultiTouchInputMapper(device));
Jeff Brown58a2da82011-01-25 16:02:22 -0800454 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800455 device->addMapper(new SingleTouchInputMapper(device));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700456 }
457
Jeff Browncb1404e2011-01-15 18:14:15 -0800458 // Joystick-like devices.
459 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
460 device->addMapper(new JoystickInputMapper(device));
461 }
462
Jeff Brown6d0fec22010-07-23 21:28:06 -0700463 return device;
464}
465
Jeff Brownb7198742011-03-18 18:14:26 -0700466void InputReader::processEventsForDevice(int32_t deviceId,
467 const RawEvent* rawEvents, size_t count) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700468 { // acquire device registry reader lock
469 RWLock::AutoRLock _rl(mDeviceRegistryLock);
470
471 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
472 if (deviceIndex < 0) {
473 LOGW("Discarding event for unknown deviceId %d.", deviceId);
474 return;
475 }
476
477 InputDevice* device = mDevices.valueAt(deviceIndex);
478 if (device->isIgnored()) {
479 //LOGD("Discarding event for ignored deviceId %d.", deviceId);
480 return;
481 }
482
Jeff Brownb7198742011-03-18 18:14:26 -0700483 device->process(rawEvents, count);
Jeff Brown6d0fec22010-07-23 21:28:06 -0700484 } // release device registry reader lock
485}
486
Jeff Brownaa3855d2011-03-17 01:34:19 -0700487void InputReader::timeoutExpired(nsecs_t when) {
488 { // acquire device registry reader lock
489 RWLock::AutoRLock _rl(mDeviceRegistryLock);
490
491 for (size_t i = 0; i < mDevices.size(); i++) {
492 InputDevice* device = mDevices.valueAt(i);
493 if (!device->isIgnored()) {
494 device->timeoutExpired(when);
495 }
496 }
497 } // release device registry reader lock
498}
499
Jeff Brownc3db8582010-10-20 15:33:38 -0700500void InputReader::handleConfigurationChanged(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700501 // Reset global meta state because it depends on the list of all configured devices.
502 updateGlobalMetaState();
503
504 // Update input configuration.
505 updateInputConfiguration();
506
507 // Enqueue configuration changed.
508 mDispatcher->notifyConfigurationChanged(when);
509}
510
511void InputReader::configureExcludedDevices() {
512 Vector<String8> excludedDeviceNames;
513 mPolicy->getExcludedDeviceNames(excludedDeviceNames);
514
515 for (size_t i = 0; i < excludedDeviceNames.size(); i++) {
516 mEventHub->addExcludedDevice(excludedDeviceNames[i]);
517 }
518}
519
520void InputReader::updateGlobalMetaState() {
521 { // acquire state lock
522 AutoMutex _l(mStateLock);
523
524 mGlobalMetaState = 0;
525
526 { // acquire device registry reader lock
527 RWLock::AutoRLock _rl(mDeviceRegistryLock);
528
529 for (size_t i = 0; i < mDevices.size(); i++) {
530 InputDevice* device = mDevices.valueAt(i);
531 mGlobalMetaState |= device->getMetaState();
532 }
533 } // release device registry reader lock
534 } // release state lock
535}
536
537int32_t InputReader::getGlobalMetaState() {
538 { // acquire state lock
539 AutoMutex _l(mStateLock);
540
541 return mGlobalMetaState;
542 } // release state lock
543}
544
545void InputReader::updateInputConfiguration() {
546 { // acquire state lock
547 AutoMutex _l(mStateLock);
548
549 int32_t touchScreenConfig = InputConfiguration::TOUCHSCREEN_NOTOUCH;
550 int32_t keyboardConfig = InputConfiguration::KEYBOARD_NOKEYS;
551 int32_t navigationConfig = InputConfiguration::NAVIGATION_NONAV;
552 { // acquire device registry reader lock
553 RWLock::AutoRLock _rl(mDeviceRegistryLock);
554
555 InputDeviceInfo deviceInfo;
556 for (size_t i = 0; i < mDevices.size(); i++) {
557 InputDevice* device = mDevices.valueAt(i);
558 device->getDeviceInfo(& deviceInfo);
559 uint32_t sources = deviceInfo.getSources();
560
561 if ((sources & AINPUT_SOURCE_TOUCHSCREEN) == AINPUT_SOURCE_TOUCHSCREEN) {
562 touchScreenConfig = InputConfiguration::TOUCHSCREEN_FINGER;
563 }
564 if ((sources & AINPUT_SOURCE_TRACKBALL) == AINPUT_SOURCE_TRACKBALL) {
565 navigationConfig = InputConfiguration::NAVIGATION_TRACKBALL;
566 } else if ((sources & AINPUT_SOURCE_DPAD) == AINPUT_SOURCE_DPAD) {
567 navigationConfig = InputConfiguration::NAVIGATION_DPAD;
568 }
569 if (deviceInfo.getKeyboardType() == AINPUT_KEYBOARD_TYPE_ALPHABETIC) {
570 keyboardConfig = InputConfiguration::KEYBOARD_QWERTY;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700571 }
572 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700573 } // release device registry reader lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700574
Jeff Brown6d0fec22010-07-23 21:28:06 -0700575 mInputConfiguration.touchScreen = touchScreenConfig;
576 mInputConfiguration.keyboard = keyboardConfig;
577 mInputConfiguration.navigation = navigationConfig;
578 } // release state lock
579}
580
Jeff Brownfe508922011-01-18 15:10:10 -0800581void InputReader::disableVirtualKeysUntil(nsecs_t time) {
582 mDisableVirtualKeysTimeout = time;
583}
584
585bool InputReader::shouldDropVirtualKey(nsecs_t now,
586 InputDevice* device, int32_t keyCode, int32_t scanCode) {
587 if (now < mDisableVirtualKeysTimeout) {
588 LOGI("Dropping virtual key from device %s because virtual keys are "
589 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
590 device->getName().string(),
591 (mDisableVirtualKeysTimeout - now) * 0.000001,
592 keyCode, scanCode);
593 return true;
594 } else {
595 return false;
596 }
597}
598
Jeff Brown05dc66a2011-03-02 14:41:58 -0800599void InputReader::fadePointer() {
600 { // acquire device registry reader lock
601 RWLock::AutoRLock _rl(mDeviceRegistryLock);
602
603 for (size_t i = 0; i < mDevices.size(); i++) {
604 InputDevice* device = mDevices.valueAt(i);
605 device->fadePointer();
606 }
607 } // release device registry reader lock
608}
609
Jeff Brownaa3855d2011-03-17 01:34:19 -0700610void InputReader::requestTimeoutAtTime(nsecs_t when) {
611 if (when < mNextTimeout) {
612 mNextTimeout = when;
613 }
614}
615
Jeff Brown6d0fec22010-07-23 21:28:06 -0700616void InputReader::getInputConfiguration(InputConfiguration* outConfiguration) {
617 { // acquire state lock
618 AutoMutex _l(mStateLock);
619
620 *outConfiguration = mInputConfiguration;
621 } // release state lock
622}
623
624status_t InputReader::getInputDeviceInfo(int32_t deviceId, InputDeviceInfo* outDeviceInfo) {
625 { // acquire device registry reader lock
626 RWLock::AutoRLock _rl(mDeviceRegistryLock);
627
628 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
629 if (deviceIndex < 0) {
630 return NAME_NOT_FOUND;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700631 }
632
Jeff Brown6d0fec22010-07-23 21:28:06 -0700633 InputDevice* device = mDevices.valueAt(deviceIndex);
634 if (device->isIgnored()) {
635 return NAME_NOT_FOUND;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700636 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700637
638 device->getDeviceInfo(outDeviceInfo);
639 return OK;
640 } // release device registy reader lock
641}
642
643void InputReader::getInputDeviceIds(Vector<int32_t>& outDeviceIds) {
644 outDeviceIds.clear();
645
646 { // acquire device registry reader lock
647 RWLock::AutoRLock _rl(mDeviceRegistryLock);
648
649 size_t numDevices = mDevices.size();
650 for (size_t i = 0; i < numDevices; i++) {
651 InputDevice* device = mDevices.valueAt(i);
652 if (! device->isIgnored()) {
653 outDeviceIds.add(device->getId());
654 }
655 }
656 } // release device registy reader lock
657}
658
659int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
660 int32_t keyCode) {
661 return getState(deviceId, sourceMask, keyCode, & InputDevice::getKeyCodeState);
662}
663
664int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
665 int32_t scanCode) {
666 return getState(deviceId, sourceMask, scanCode, & InputDevice::getScanCodeState);
667}
668
669int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
670 return getState(deviceId, sourceMask, switchCode, & InputDevice::getSwitchState);
671}
672
673int32_t InputReader::getState(int32_t deviceId, uint32_t sourceMask, int32_t code,
674 GetStateFunc getStateFunc) {
675 { // acquire device registry reader lock
676 RWLock::AutoRLock _rl(mDeviceRegistryLock);
677
678 int32_t result = AKEY_STATE_UNKNOWN;
679 if (deviceId >= 0) {
680 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
681 if (deviceIndex >= 0) {
682 InputDevice* device = mDevices.valueAt(deviceIndex);
683 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
684 result = (device->*getStateFunc)(sourceMask, code);
685 }
686 }
687 } else {
688 size_t numDevices = mDevices.size();
689 for (size_t i = 0; i < numDevices; i++) {
690 InputDevice* device = mDevices.valueAt(i);
691 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
692 result = (device->*getStateFunc)(sourceMask, code);
693 if (result >= AKEY_STATE_DOWN) {
694 return result;
695 }
696 }
697 }
698 }
699 return result;
700 } // release device registy reader lock
701}
702
703bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
704 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
705 memset(outFlags, 0, numCodes);
706 return markSupportedKeyCodes(deviceId, sourceMask, numCodes, keyCodes, outFlags);
707}
708
709bool InputReader::markSupportedKeyCodes(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
710 const int32_t* keyCodes, uint8_t* outFlags) {
711 { // acquire device registry reader lock
712 RWLock::AutoRLock _rl(mDeviceRegistryLock);
713 bool result = false;
714 if (deviceId >= 0) {
715 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
716 if (deviceIndex >= 0) {
717 InputDevice* device = mDevices.valueAt(deviceIndex);
718 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
719 result = device->markSupportedKeyCodes(sourceMask,
720 numCodes, keyCodes, outFlags);
721 }
722 }
723 } else {
724 size_t numDevices = mDevices.size();
725 for (size_t i = 0; i < numDevices; i++) {
726 InputDevice* device = mDevices.valueAt(i);
727 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
728 result |= device->markSupportedKeyCodes(sourceMask,
729 numCodes, keyCodes, outFlags);
730 }
731 }
732 }
733 return result;
734 } // release device registy reader lock
735}
736
Jeff Brownb88102f2010-09-08 11:49:43 -0700737void InputReader::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -0700738 mEventHub->dump(dump);
739 dump.append("\n");
740
741 dump.append("Input Reader State:\n");
742
Jeff Brownef3d7e82010-09-30 14:33:04 -0700743 { // acquire device registry reader lock
744 RWLock::AutoRLock _rl(mDeviceRegistryLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700745
Jeff Brownef3d7e82010-09-30 14:33:04 -0700746 for (size_t i = 0; i < mDevices.size(); i++) {
747 mDevices.valueAt(i)->dump(dump);
Jeff Brownb88102f2010-09-08 11:49:43 -0700748 }
Jeff Brownef3d7e82010-09-30 14:33:04 -0700749 } // release device registy reader lock
Jeff Brownb88102f2010-09-08 11:49:43 -0700750}
751
Jeff Brown6d0fec22010-07-23 21:28:06 -0700752
753// --- InputReaderThread ---
754
755InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
756 Thread(/*canCallJava*/ true), mReader(reader) {
757}
758
759InputReaderThread::~InputReaderThread() {
760}
761
762bool InputReaderThread::threadLoop() {
763 mReader->loopOnce();
764 return true;
765}
766
767
768// --- InputDevice ---
769
770InputDevice::InputDevice(InputReaderContext* context, int32_t id, const String8& name) :
Jeff Brown56194eb2011-03-02 19:23:13 -0800771 mContext(context), mId(id), mName(name), mSources(0), mIsExternal(false) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700772}
773
774InputDevice::~InputDevice() {
775 size_t numMappers = mMappers.size();
776 for (size_t i = 0; i < numMappers; i++) {
777 delete mMappers[i];
778 }
779 mMappers.clear();
780}
781
Jeff Brownef3d7e82010-09-30 14:33:04 -0700782void InputDevice::dump(String8& dump) {
783 InputDeviceInfo deviceInfo;
784 getDeviceInfo(& deviceInfo);
785
Jeff Brown90655042010-12-02 13:50:46 -0800786 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
Jeff Brownef3d7e82010-09-30 14:33:04 -0700787 deviceInfo.getName().string());
Jeff Brown56194eb2011-03-02 19:23:13 -0800788 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Jeff Brownef3d7e82010-09-30 14:33:04 -0700789 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
790 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Jeff Browncc0c1592011-02-19 05:07:28 -0800791
Jeff Brownefd32662011-03-08 15:13:06 -0800792 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
Jeff Browncc0c1592011-02-19 05:07:28 -0800793 if (!ranges.isEmpty()) {
Jeff Brownef3d7e82010-09-30 14:33:04 -0700794 dump.append(INDENT2 "Motion Ranges:\n");
Jeff Browncc0c1592011-02-19 05:07:28 -0800795 for (size_t i = 0; i < ranges.size(); i++) {
Jeff Brownefd32662011-03-08 15:13:06 -0800796 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
797 const char* label = getAxisLabel(range.axis);
Jeff Browncc0c1592011-02-19 05:07:28 -0800798 char name[32];
799 if (label) {
800 strncpy(name, label, sizeof(name));
801 name[sizeof(name) - 1] = '\0';
802 } else {
Jeff Brownefd32662011-03-08 15:13:06 -0800803 snprintf(name, sizeof(name), "%d", range.axis);
Jeff Browncc0c1592011-02-19 05:07:28 -0800804 }
Jeff Brownefd32662011-03-08 15:13:06 -0800805 dump.appendFormat(INDENT3 "%s: source=0x%08x, "
806 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f\n",
807 name, range.source, range.min, range.max, range.flat, range.fuzz);
Jeff Browncc0c1592011-02-19 05:07:28 -0800808 }
Jeff Brownef3d7e82010-09-30 14:33:04 -0700809 }
810
811 size_t numMappers = mMappers.size();
812 for (size_t i = 0; i < numMappers; i++) {
813 InputMapper* mapper = mMappers[i];
814 mapper->dump(dump);
815 }
816}
817
Jeff Brown6d0fec22010-07-23 21:28:06 -0700818void InputDevice::addMapper(InputMapper* mapper) {
819 mMappers.add(mapper);
820}
821
822void InputDevice::configure() {
Jeff Brown8d608662010-08-30 03:02:23 -0700823 if (! isIgnored()) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800824 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
Jeff Brown8d608662010-08-30 03:02:23 -0700825 }
826
Jeff Brown6d0fec22010-07-23 21:28:06 -0700827 mSources = 0;
828
829 size_t numMappers = mMappers.size();
830 for (size_t i = 0; i < numMappers; i++) {
831 InputMapper* mapper = mMappers[i];
832 mapper->configure();
833 mSources |= mapper->getSources();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700834 }
835}
836
Jeff Brown6d0fec22010-07-23 21:28:06 -0700837void InputDevice::reset() {
838 size_t numMappers = mMappers.size();
839 for (size_t i = 0; i < numMappers; i++) {
840 InputMapper* mapper = mMappers[i];
841 mapper->reset();
842 }
843}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700844
Jeff Brownb7198742011-03-18 18:14:26 -0700845void InputDevice::process(const RawEvent* rawEvents, size_t count) {
846 // Process all of the events in order for each mapper.
847 // We cannot simply ask each mapper to process them in bulk because mappers may
848 // have side-effects that must be interleaved. For example, joystick movement events and
849 // gamepad button presses are handled by different mappers but they should be dispatched
850 // in the order received.
Jeff Brown6d0fec22010-07-23 21:28:06 -0700851 size_t numMappers = mMappers.size();
Jeff Brownb7198742011-03-18 18:14:26 -0700852 for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
853#if DEBUG_RAW_EVENTS
854 LOGD("Input event: device=%d type=0x%04x scancode=0x%04x "
855 "keycode=0x%04x value=0x%04x flags=0x%08x",
856 rawEvent->deviceId, rawEvent->type, rawEvent->scanCode, rawEvent->keyCode,
857 rawEvent->value, rawEvent->flags);
858#endif
859
860 for (size_t i = 0; i < numMappers; i++) {
861 InputMapper* mapper = mMappers[i];
862 mapper->process(rawEvent);
863 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700864 }
865}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700866
Jeff Brownaa3855d2011-03-17 01:34:19 -0700867void InputDevice::timeoutExpired(nsecs_t when) {
868 size_t numMappers = mMappers.size();
869 for (size_t i = 0; i < numMappers; i++) {
870 InputMapper* mapper = mMappers[i];
871 mapper->timeoutExpired(when);
872 }
873}
874
Jeff Brown6d0fec22010-07-23 21:28:06 -0700875void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
876 outDeviceInfo->initialize(mId, mName);
877
878 size_t numMappers = mMappers.size();
879 for (size_t i = 0; i < numMappers; i++) {
880 InputMapper* mapper = mMappers[i];
881 mapper->populateDeviceInfo(outDeviceInfo);
882 }
883}
884
885int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
886 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
887}
888
889int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
890 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
891}
892
893int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
894 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
895}
896
897int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
898 int32_t result = AKEY_STATE_UNKNOWN;
899 size_t numMappers = mMappers.size();
900 for (size_t i = 0; i < numMappers; i++) {
901 InputMapper* mapper = mMappers[i];
902 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
903 result = (mapper->*getStateFunc)(sourceMask, code);
904 if (result >= AKEY_STATE_DOWN) {
905 return result;
906 }
907 }
908 }
909 return result;
910}
911
912bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
913 const int32_t* keyCodes, uint8_t* outFlags) {
914 bool result = false;
915 size_t numMappers = mMappers.size();
916 for (size_t i = 0; i < numMappers; i++) {
917 InputMapper* mapper = mMappers[i];
918 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
919 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
920 }
921 }
922 return result;
923}
924
925int32_t InputDevice::getMetaState() {
926 int32_t result = 0;
927 size_t numMappers = mMappers.size();
928 for (size_t i = 0; i < numMappers; i++) {
929 InputMapper* mapper = mMappers[i];
930 result |= mapper->getMetaState();
931 }
932 return result;
933}
934
Jeff Brown05dc66a2011-03-02 14:41:58 -0800935void InputDevice::fadePointer() {
936 size_t numMappers = mMappers.size();
937 for (size_t i = 0; i < numMappers; i++) {
938 InputMapper* mapper = mMappers[i];
939 mapper->fadePointer();
940 }
941}
942
Jeff Brown6d0fec22010-07-23 21:28:06 -0700943
944// --- InputMapper ---
945
946InputMapper::InputMapper(InputDevice* device) :
947 mDevice(device), mContext(device->getContext()) {
948}
949
950InputMapper::~InputMapper() {
951}
952
953void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
954 info->addSource(getSources());
955}
956
Jeff Brownef3d7e82010-09-30 14:33:04 -0700957void InputMapper::dump(String8& dump) {
958}
959
Jeff Brown6d0fec22010-07-23 21:28:06 -0700960void InputMapper::configure() {
961}
962
963void InputMapper::reset() {
964}
965
Jeff Brownaa3855d2011-03-17 01:34:19 -0700966void InputMapper::timeoutExpired(nsecs_t when) {
967}
968
Jeff Brown6d0fec22010-07-23 21:28:06 -0700969int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
970 return AKEY_STATE_UNKNOWN;
971}
972
973int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
974 return AKEY_STATE_UNKNOWN;
975}
976
977int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
978 return AKEY_STATE_UNKNOWN;
979}
980
981bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
982 const int32_t* keyCodes, uint8_t* outFlags) {
983 return false;
984}
985
986int32_t InputMapper::getMetaState() {
987 return 0;
988}
989
Jeff Brown05dc66a2011-03-02 14:41:58 -0800990void InputMapper::fadePointer() {
991}
992
Jeff Browncb1404e2011-01-15 18:14:15 -0800993void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
994 const RawAbsoluteAxisInfo& axis, const char* name) {
995 if (axis.valid) {
996 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d\n",
997 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz);
998 } else {
999 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
1000 }
1001}
1002
Jeff Brown6d0fec22010-07-23 21:28:06 -07001003
1004// --- SwitchInputMapper ---
1005
1006SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
1007 InputMapper(device) {
1008}
1009
1010SwitchInputMapper::~SwitchInputMapper() {
1011}
1012
1013uint32_t SwitchInputMapper::getSources() {
Jeff Brown89de57a2011-01-19 18:41:38 -08001014 return AINPUT_SOURCE_SWITCH;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001015}
1016
1017void SwitchInputMapper::process(const RawEvent* rawEvent) {
1018 switch (rawEvent->type) {
1019 case EV_SW:
1020 processSwitch(rawEvent->when, rawEvent->scanCode, rawEvent->value);
1021 break;
1022 }
1023}
1024
1025void SwitchInputMapper::processSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue) {
Jeff Brownb6997262010-10-08 22:31:17 -07001026 getDispatcher()->notifySwitch(when, switchCode, switchValue, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001027}
1028
1029int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1030 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
1031}
1032
1033
1034// --- KeyboardInputMapper ---
1035
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001036KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
Jeff Brownefd32662011-03-08 15:13:06 -08001037 uint32_t source, int32_t keyboardType) :
1038 InputMapper(device), mSource(source),
Jeff Brown6d0fec22010-07-23 21:28:06 -07001039 mKeyboardType(keyboardType) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001040 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001041}
1042
1043KeyboardInputMapper::~KeyboardInputMapper() {
1044}
1045
Jeff Brown6328cdc2010-07-29 18:18:33 -07001046void KeyboardInputMapper::initializeLocked() {
1047 mLocked.metaState = AMETA_NONE;
1048 mLocked.downTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001049}
1050
1051uint32_t KeyboardInputMapper::getSources() {
Jeff Brownefd32662011-03-08 15:13:06 -08001052 return mSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001053}
1054
1055void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1056 InputMapper::populateDeviceInfo(info);
1057
1058 info->setKeyboardType(mKeyboardType);
1059}
1060
Jeff Brownef3d7e82010-09-30 14:33:04 -07001061void KeyboardInputMapper::dump(String8& dump) {
1062 { // acquire lock
1063 AutoMutex _l(mLock);
1064 dump.append(INDENT2 "Keyboard Input Mapper:\n");
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001065 dumpParameters(dump);
Jeff Brownef3d7e82010-09-30 14:33:04 -07001066 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
1067 dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mLocked.keyDowns.size());
1068 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mLocked.metaState);
1069 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
1070 } // release lock
1071}
1072
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001073
1074void KeyboardInputMapper::configure() {
1075 InputMapper::configure();
1076
1077 // Configure basic parameters.
1078 configureParameters();
Jeff Brown49ed71d2010-12-06 17:13:33 -08001079
1080 // Reset LEDs.
1081 {
1082 AutoMutex _l(mLock);
1083 resetLedStateLocked();
1084 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001085}
1086
1087void KeyboardInputMapper::configureParameters() {
1088 mParameters.orientationAware = false;
1089 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
1090 mParameters.orientationAware);
1091
1092 mParameters.associatedDisplayId = mParameters.orientationAware ? 0 : -1;
1093}
1094
1095void KeyboardInputMapper::dumpParameters(String8& dump) {
1096 dump.append(INDENT3 "Parameters:\n");
1097 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1098 mParameters.associatedDisplayId);
1099 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1100 toString(mParameters.orientationAware));
1101}
1102
Jeff Brown6d0fec22010-07-23 21:28:06 -07001103void KeyboardInputMapper::reset() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001104 for (;;) {
1105 int32_t keyCode, scanCode;
1106 { // acquire lock
1107 AutoMutex _l(mLock);
1108
1109 // Synthesize key up event on reset if keys are currently down.
1110 if (mLocked.keyDowns.isEmpty()) {
1111 initializeLocked();
Jeff Brown49ed71d2010-12-06 17:13:33 -08001112 resetLedStateLocked();
Jeff Brown6328cdc2010-07-29 18:18:33 -07001113 break; // done
1114 }
1115
1116 const KeyDown& keyDown = mLocked.keyDowns.top();
1117 keyCode = keyDown.keyCode;
1118 scanCode = keyDown.scanCode;
1119 } // release lock
1120
Jeff Brown6d0fec22010-07-23 21:28:06 -07001121 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown6328cdc2010-07-29 18:18:33 -07001122 processKey(when, false, keyCode, scanCode, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001123 }
1124
1125 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001126 getContext()->updateGlobalMetaState();
1127}
1128
1129void KeyboardInputMapper::process(const RawEvent* rawEvent) {
1130 switch (rawEvent->type) {
1131 case EV_KEY: {
1132 int32_t scanCode = rawEvent->scanCode;
1133 if (isKeyboardOrGamepadKey(scanCode)) {
1134 processKey(rawEvent->when, rawEvent->value != 0, rawEvent->keyCode, scanCode,
1135 rawEvent->flags);
1136 }
1137 break;
1138 }
1139 }
1140}
1141
1142bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
1143 return scanCode < BTN_MOUSE
1144 || scanCode >= KEY_OK
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001145 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
Jeff Browncb1404e2011-01-15 18:14:15 -08001146 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001147}
1148
Jeff Brown6328cdc2010-07-29 18:18:33 -07001149void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode,
1150 int32_t scanCode, uint32_t policyFlags) {
1151 int32_t newMetaState;
1152 nsecs_t downTime;
1153 bool metaStateChanged = false;
1154
1155 { // acquire lock
1156 AutoMutex _l(mLock);
1157
1158 if (down) {
1159 // Rotate key codes according to orientation if needed.
1160 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001161 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001162 int32_t orientation;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001163 if (!getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1164 NULL, NULL, & orientation)) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001165 orientation = DISPLAY_ORIENTATION_0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001166 }
1167
1168 keyCode = rotateKeyCode(keyCode, orientation);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001169 }
1170
Jeff Brown6328cdc2010-07-29 18:18:33 -07001171 // Add key down.
1172 ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1173 if (keyDownIndex >= 0) {
1174 // key repeat, be sure to use same keycode as before in case of rotation
Jeff Brown6b53e8d2010-11-10 16:03:06 -08001175 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001176 } else {
1177 // key down
Jeff Brownfe508922011-01-18 15:10:10 -08001178 if ((policyFlags & POLICY_FLAG_VIRTUAL)
1179 && mContext->shouldDropVirtualKey(when,
1180 getDevice(), keyCode, scanCode)) {
1181 return;
1182 }
1183
Jeff Brown6328cdc2010-07-29 18:18:33 -07001184 mLocked.keyDowns.push();
1185 KeyDown& keyDown = mLocked.keyDowns.editTop();
1186 keyDown.keyCode = keyCode;
1187 keyDown.scanCode = scanCode;
1188 }
1189
1190 mLocked.downTime = when;
1191 } else {
1192 // Remove key down.
1193 ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1194 if (keyDownIndex >= 0) {
1195 // key up, be sure to use same keycode as before in case of rotation
Jeff Brown6b53e8d2010-11-10 16:03:06 -08001196 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001197 mLocked.keyDowns.removeAt(size_t(keyDownIndex));
1198 } else {
1199 // key was not actually down
1200 LOGI("Dropping key up from device %s because the key was not down. "
1201 "keyCode=%d, scanCode=%d",
1202 getDeviceName().string(), keyCode, scanCode);
1203 return;
1204 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001205 }
1206
Jeff Brown6328cdc2010-07-29 18:18:33 -07001207 int32_t oldMetaState = mLocked.metaState;
1208 newMetaState = updateMetaState(keyCode, down, oldMetaState);
1209 if (oldMetaState != newMetaState) {
1210 mLocked.metaState = newMetaState;
1211 metaStateChanged = true;
Jeff Brown497a92c2010-09-12 17:55:08 -07001212 updateLedStateLocked(false);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001213 }
Jeff Brownfd0358292010-06-30 16:10:35 -07001214
Jeff Brown6328cdc2010-07-29 18:18:33 -07001215 downTime = mLocked.downTime;
1216 } // release lock
1217
Jeff Brown56194eb2011-03-02 19:23:13 -08001218 // Key down on external an keyboard should wake the device.
1219 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
1220 // For internal keyboards, the key layout file should specify the policy flags for
1221 // each wake key individually.
1222 // TODO: Use the input device configuration to control this behavior more finely.
1223 if (down && getDevice()->isExternal()
1224 && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) {
1225 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1226 }
1227
Jeff Brown6328cdc2010-07-29 18:18:33 -07001228 if (metaStateChanged) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001229 getContext()->updateGlobalMetaState();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001230 }
1231
Jeff Brown05dc66a2011-03-02 14:41:58 -08001232 if (down && !isMetaKey(keyCode)) {
1233 getContext()->fadePointer();
1234 }
1235
Jeff Brownefd32662011-03-08 15:13:06 -08001236 getDispatcher()->notifyKey(when, getDeviceId(), mSource, policyFlags,
Jeff Brownb6997262010-10-08 22:31:17 -07001237 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
1238 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001239}
1240
Jeff Brown6328cdc2010-07-29 18:18:33 -07001241ssize_t KeyboardInputMapper::findKeyDownLocked(int32_t scanCode) {
1242 size_t n = mLocked.keyDowns.size();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001243 for (size_t i = 0; i < n; i++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001244 if (mLocked.keyDowns[i].scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001245 return i;
1246 }
1247 }
1248 return -1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001249}
1250
Jeff Brown6d0fec22010-07-23 21:28:06 -07001251int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1252 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
1253}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001254
Jeff Brown6d0fec22010-07-23 21:28:06 -07001255int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1256 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1257}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001258
Jeff Brown6d0fec22010-07-23 21:28:06 -07001259bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1260 const int32_t* keyCodes, uint8_t* outFlags) {
1261 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
1262}
1263
1264int32_t KeyboardInputMapper::getMetaState() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001265 { // acquire lock
1266 AutoMutex _l(mLock);
1267 return mLocked.metaState;
1268 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001269}
1270
Jeff Brown49ed71d2010-12-06 17:13:33 -08001271void KeyboardInputMapper::resetLedStateLocked() {
1272 initializeLedStateLocked(mLocked.capsLockLedState, LED_CAPSL);
1273 initializeLedStateLocked(mLocked.numLockLedState, LED_NUML);
1274 initializeLedStateLocked(mLocked.scrollLockLedState, LED_SCROLLL);
1275
1276 updateLedStateLocked(true);
1277}
1278
1279void KeyboardInputMapper::initializeLedStateLocked(LockedState::LedState& ledState, int32_t led) {
1280 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
1281 ledState.on = false;
1282}
1283
Jeff Brown497a92c2010-09-12 17:55:08 -07001284void KeyboardInputMapper::updateLedStateLocked(bool reset) {
1285 updateLedStateForModifierLocked(mLocked.capsLockLedState, LED_CAPSL,
Jeff Brown51e7fe752010-10-29 22:19:53 -07001286 AMETA_CAPS_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001287 updateLedStateForModifierLocked(mLocked.numLockLedState, LED_NUML,
Jeff Brown51e7fe752010-10-29 22:19:53 -07001288 AMETA_NUM_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001289 updateLedStateForModifierLocked(mLocked.scrollLockLedState, LED_SCROLLL,
Jeff Brown51e7fe752010-10-29 22:19:53 -07001290 AMETA_SCROLL_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001291}
1292
1293void KeyboardInputMapper::updateLedStateForModifierLocked(LockedState::LedState& ledState,
1294 int32_t led, int32_t modifier, bool reset) {
1295 if (ledState.avail) {
1296 bool desiredState = (mLocked.metaState & modifier) != 0;
Jeff Brown49ed71d2010-12-06 17:13:33 -08001297 if (reset || ledState.on != desiredState) {
Jeff Brown497a92c2010-09-12 17:55:08 -07001298 getEventHub()->setLedState(getDeviceId(), led, desiredState);
1299 ledState.on = desiredState;
1300 }
1301 }
1302}
1303
Jeff Brown6d0fec22010-07-23 21:28:06 -07001304
Jeff Brown83c09682010-12-23 17:50:18 -08001305// --- CursorInputMapper ---
Jeff Brown6d0fec22010-07-23 21:28:06 -07001306
Jeff Brown83c09682010-12-23 17:50:18 -08001307CursorInputMapper::CursorInputMapper(InputDevice* device) :
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001308 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001309 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001310}
1311
Jeff Brown83c09682010-12-23 17:50:18 -08001312CursorInputMapper::~CursorInputMapper() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001313}
1314
Jeff Brown83c09682010-12-23 17:50:18 -08001315uint32_t CursorInputMapper::getSources() {
Jeff Brownefd32662011-03-08 15:13:06 -08001316 return mSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001317}
1318
Jeff Brown83c09682010-12-23 17:50:18 -08001319void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001320 InputMapper::populateDeviceInfo(info);
1321
Jeff Brown83c09682010-12-23 17:50:18 -08001322 if (mParameters.mode == Parameters::MODE_POINTER) {
1323 float minX, minY, maxX, maxY;
1324 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
Jeff Brownefd32662011-03-08 15:13:06 -08001325 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f);
1326 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f);
Jeff Brown83c09682010-12-23 17:50:18 -08001327 }
1328 } else {
Jeff Brownefd32662011-03-08 15:13:06 -08001329 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale);
1330 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale);
Jeff Brown83c09682010-12-23 17:50:18 -08001331 }
Jeff Brownefd32662011-03-08 15:13:06 -08001332 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001333
1334 if (mHaveVWheel) {
Jeff Brownefd32662011-03-08 15:13:06 -08001335 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001336 }
1337 if (mHaveHWheel) {
Jeff Brownefd32662011-03-08 15:13:06 -08001338 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001339 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001340}
1341
Jeff Brown83c09682010-12-23 17:50:18 -08001342void CursorInputMapper::dump(String8& dump) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07001343 { // acquire lock
1344 AutoMutex _l(mLock);
Jeff Brown83c09682010-12-23 17:50:18 -08001345 dump.append(INDENT2 "Cursor Input Mapper:\n");
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001346 dumpParameters(dump);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001347 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
1348 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
Jeff Brownef3d7e82010-09-30 14:33:04 -07001349 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
1350 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001351 dump.appendFormat(INDENT3 "HaveVWheel: %s\n", toString(mHaveVWheel));
1352 dump.appendFormat(INDENT3 "HaveHWheel: %s\n", toString(mHaveHWheel));
1353 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
1354 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001355 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mLocked.buttonState);
1356 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mLocked.buttonState)));
Jeff Brownef3d7e82010-09-30 14:33:04 -07001357 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
1358 } // release lock
1359}
1360
Jeff Brown83c09682010-12-23 17:50:18 -08001361void CursorInputMapper::configure() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001362 InputMapper::configure();
1363
1364 // Configure basic parameters.
1365 configureParameters();
Jeff Brown83c09682010-12-23 17:50:18 -08001366
1367 // Configure device mode.
1368 switch (mParameters.mode) {
1369 case Parameters::MODE_POINTER:
Jeff Brownefd32662011-03-08 15:13:06 -08001370 mSource = AINPUT_SOURCE_MOUSE;
Jeff Brown83c09682010-12-23 17:50:18 -08001371 mXPrecision = 1.0f;
1372 mYPrecision = 1.0f;
1373 mXScale = 1.0f;
1374 mYScale = 1.0f;
1375 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
1376 break;
1377 case Parameters::MODE_NAVIGATION:
Jeff Brownefd32662011-03-08 15:13:06 -08001378 mSource = AINPUT_SOURCE_TRACKBALL;
Jeff Brown83c09682010-12-23 17:50:18 -08001379 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1380 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1381 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1382 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1383 break;
1384 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08001385
1386 mVWheelScale = 1.0f;
1387 mHWheelScale = 1.0f;
Jeff Browncc0c1592011-02-19 05:07:28 -08001388
1389 mHaveVWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_WHEEL);
1390 mHaveHWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_HWHEEL);
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001391}
1392
Jeff Brown83c09682010-12-23 17:50:18 -08001393void CursorInputMapper::configureParameters() {
1394 mParameters.mode = Parameters::MODE_POINTER;
1395 String8 cursorModeString;
1396 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
1397 if (cursorModeString == "navigation") {
1398 mParameters.mode = Parameters::MODE_NAVIGATION;
1399 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
1400 LOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
1401 }
1402 }
1403
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001404 mParameters.orientationAware = false;
Jeff Brown83c09682010-12-23 17:50:18 -08001405 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001406 mParameters.orientationAware);
1407
Jeff Brown83c09682010-12-23 17:50:18 -08001408 mParameters.associatedDisplayId = mParameters.mode == Parameters::MODE_POINTER
1409 || mParameters.orientationAware ? 0 : -1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001410}
1411
Jeff Brown83c09682010-12-23 17:50:18 -08001412void CursorInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001413 dump.append(INDENT3 "Parameters:\n");
1414 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1415 mParameters.associatedDisplayId);
Jeff Brown83c09682010-12-23 17:50:18 -08001416
1417 switch (mParameters.mode) {
1418 case Parameters::MODE_POINTER:
1419 dump.append(INDENT4 "Mode: pointer\n");
1420 break;
1421 case Parameters::MODE_NAVIGATION:
1422 dump.append(INDENT4 "Mode: navigation\n");
1423 break;
1424 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07001425 LOG_ASSERT(false);
Jeff Brown83c09682010-12-23 17:50:18 -08001426 }
1427
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001428 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1429 toString(mParameters.orientationAware));
1430}
1431
Jeff Brown83c09682010-12-23 17:50:18 -08001432void CursorInputMapper::initializeLocked() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001433 mAccumulator.clear();
1434
Jeff Brownefd32662011-03-08 15:13:06 -08001435 mLocked.buttonState = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001436 mLocked.downTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001437}
1438
Jeff Brown83c09682010-12-23 17:50:18 -08001439void CursorInputMapper::reset() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001440 for (;;) {
Jeff Brownefd32662011-03-08 15:13:06 -08001441 uint32_t buttonState;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001442 { // acquire lock
1443 AutoMutex _l(mLock);
1444
Jeff Brownefd32662011-03-08 15:13:06 -08001445 buttonState = mLocked.buttonState;
1446 if (!buttonState) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001447 initializeLocked();
1448 break; // done
1449 }
1450 } // release lock
1451
Jeff Brown83c09682010-12-23 17:50:18 -08001452 // Synthesize button up event on reset.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001453 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brownefd32662011-03-08 15:13:06 -08001454 mAccumulator.clear();
1455 mAccumulator.buttonDown = 0;
1456 mAccumulator.buttonUp = buttonState;
1457 mAccumulator.fields = Accumulator::FIELD_BUTTONS;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001458 sync(when);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001459 }
1460
Jeff Brown6d0fec22010-07-23 21:28:06 -07001461 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001462}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001463
Jeff Brown83c09682010-12-23 17:50:18 -08001464void CursorInputMapper::process(const RawEvent* rawEvent) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001465 switch (rawEvent->type) {
Jeff Brownefd32662011-03-08 15:13:06 -08001466 case EV_KEY: {
1467 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
1468 if (buttonState) {
1469 if (rawEvent->value) {
1470 mAccumulator.buttonDown = buttonState;
1471 mAccumulator.buttonUp = 0;
1472 } else {
1473 mAccumulator.buttonDown = 0;
1474 mAccumulator.buttonUp = buttonState;
1475 }
1476 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
1477
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001478 // Sync now since BTN_MOUSE is not necessarily followed by SYN_REPORT and
1479 // we need to ensure that we report the up/down promptly.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001480 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001481 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001482 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001483 break;
Jeff Brownefd32662011-03-08 15:13:06 -08001484 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001485
Jeff Brown6d0fec22010-07-23 21:28:06 -07001486 case EV_REL:
1487 switch (rawEvent->scanCode) {
1488 case REL_X:
1489 mAccumulator.fields |= Accumulator::FIELD_REL_X;
1490 mAccumulator.relX = rawEvent->value;
1491 break;
1492 case REL_Y:
1493 mAccumulator.fields |= Accumulator::FIELD_REL_Y;
1494 mAccumulator.relY = rawEvent->value;
1495 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001496 case REL_WHEEL:
1497 mAccumulator.fields |= Accumulator::FIELD_REL_WHEEL;
1498 mAccumulator.relWheel = rawEvent->value;
1499 break;
1500 case REL_HWHEEL:
1501 mAccumulator.fields |= Accumulator::FIELD_REL_HWHEEL;
1502 mAccumulator.relHWheel = rawEvent->value;
1503 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001504 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001505 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001506
Jeff Brown6d0fec22010-07-23 21:28:06 -07001507 case EV_SYN:
1508 switch (rawEvent->scanCode) {
1509 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001510 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001511 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001512 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001513 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001514 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001515}
1516
Jeff Brown83c09682010-12-23 17:50:18 -08001517void CursorInputMapper::sync(nsecs_t when) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001518 uint32_t fields = mAccumulator.fields;
1519 if (fields == 0) {
1520 return; // no new state changes, so nothing to do
1521 }
1522
Jeff Brown9626b142011-03-03 02:09:54 -08001523 int32_t motionEventAction;
1524 int32_t motionEventEdgeFlags;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001525 PointerCoords pointerCoords;
1526 nsecs_t downTime;
Jeff Brown33bbfd22011-02-24 20:55:35 -08001527 float vscroll, hscroll;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001528 { // acquire lock
1529 AutoMutex _l(mLock);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001530
Jeff Brownefd32662011-03-08 15:13:06 -08001531 bool down, downChanged;
1532 bool wasDown = isPointerDown(mLocked.buttonState);
1533 bool buttonsChanged = fields & Accumulator::FIELD_BUTTONS;
1534 if (buttonsChanged) {
1535 mLocked.buttonState = (mLocked.buttonState | mAccumulator.buttonDown)
1536 & ~mAccumulator.buttonUp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001537
Jeff Brownefd32662011-03-08 15:13:06 -08001538 down = isPointerDown(mLocked.buttonState);
1539
1540 if (!wasDown && down) {
1541 mLocked.downTime = when;
1542 downChanged = true;
1543 } else if (wasDown && !down) {
1544 downChanged = true;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001545 } else {
Jeff Brownefd32662011-03-08 15:13:06 -08001546 downChanged = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001547 }
Jeff Brownefd32662011-03-08 15:13:06 -08001548 } else {
1549 down = wasDown;
1550 downChanged = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001551 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001552
Jeff Brown6328cdc2010-07-29 18:18:33 -07001553 downTime = mLocked.downTime;
Jeff Brown83c09682010-12-23 17:50:18 -08001554 float deltaX = fields & Accumulator::FIELD_REL_X ? mAccumulator.relX * mXScale : 0.0f;
1555 float deltaY = fields & Accumulator::FIELD_REL_Y ? mAccumulator.relY * mYScale : 0.0f;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001556
Jeff Brown6328cdc2010-07-29 18:18:33 -07001557 if (downChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08001558 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
1559 } else if (down || mPointerController == NULL) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001560 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
Jeff Browncc0c1592011-02-19 05:07:28 -08001561 } else {
1562 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001563 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001564
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001565 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0
Jeff Brown83c09682010-12-23 17:50:18 -08001566 && (deltaX != 0.0f || deltaY != 0.0f)) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001567 // Rotate motion based on display orientation if needed.
1568 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
1569 int32_t orientation;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001570 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1571 NULL, NULL, & orientation)) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001572 orientation = DISPLAY_ORIENTATION_0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001573 }
1574
1575 float temp;
1576 switch (orientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001577 case DISPLAY_ORIENTATION_90:
Jeff Brown83c09682010-12-23 17:50:18 -08001578 temp = deltaX;
1579 deltaX = deltaY;
1580 deltaY = -temp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001581 break;
1582
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001583 case DISPLAY_ORIENTATION_180:
Jeff Brown83c09682010-12-23 17:50:18 -08001584 deltaX = -deltaX;
1585 deltaY = -deltaY;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001586 break;
1587
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001588 case DISPLAY_ORIENTATION_270:
Jeff Brown83c09682010-12-23 17:50:18 -08001589 temp = deltaX;
1590 deltaX = -deltaY;
1591 deltaY = temp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001592 break;
1593 }
1594 }
Jeff Brown83c09682010-12-23 17:50:18 -08001595
Jeff Brown91c69ab2011-02-14 17:03:18 -08001596 pointerCoords.clear();
1597
Jeff Brown9626b142011-03-03 02:09:54 -08001598 motionEventEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
1599
Jeff Brown2352b972011-04-12 22:39:53 -07001600 if (mHaveVWheel && (fields & Accumulator::FIELD_REL_WHEEL)) {
1601 vscroll = mAccumulator.relWheel;
1602 } else {
1603 vscroll = 0;
1604 }
1605 if (mHaveHWheel && (fields & Accumulator::FIELD_REL_HWHEEL)) {
1606 hscroll = mAccumulator.relHWheel;
1607 } else {
1608 hscroll = 0;
1609 }
1610
Jeff Brown83c09682010-12-23 17:50:18 -08001611 if (mPointerController != NULL) {
Jeff Brown2352b972011-04-12 22:39:53 -07001612 if (deltaX != 0 || deltaY != 0 || vscroll != 0 || hscroll != 0
1613 || buttonsChanged) {
1614 mPointerController->setPresentation(
1615 PointerControllerInterface::PRESENTATION_POINTER);
1616
1617 if (deltaX != 0 || deltaY != 0) {
1618 mPointerController->move(deltaX, deltaY);
1619 }
1620
1621 if (buttonsChanged) {
1622 mPointerController->setButtonState(mLocked.buttonState);
1623 }
1624
1625 mPointerController->unfade();
Jeff Brown83c09682010-12-23 17:50:18 -08001626 }
Jeff Brownefd32662011-03-08 15:13:06 -08001627
Jeff Brown91c69ab2011-02-14 17:03:18 -08001628 float x, y;
1629 mPointerController->getPosition(&x, &y);
Jeff Brownebbd5d12011-02-17 13:01:34 -08001630 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
1631 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jeff Brown9626b142011-03-03 02:09:54 -08001632
1633 if (motionEventAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownefd32662011-03-08 15:13:06 -08001634 motionEventEdgeFlags = calculateEdgeFlagsUsingPointerBounds(
1635 mPointerController, x, y);
Jeff Brown9626b142011-03-03 02:09:54 -08001636 }
Jeff Brown83c09682010-12-23 17:50:18 -08001637 } else {
Jeff Brownebbd5d12011-02-17 13:01:34 -08001638 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
1639 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
Jeff Brown83c09682010-12-23 17:50:18 -08001640 }
1641
Jeff Brownefd32662011-03-08 15:13:06 -08001642 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
Jeff Brown6328cdc2010-07-29 18:18:33 -07001643 } // release lock
1644
Jeff Brown56194eb2011-03-02 19:23:13 -08001645 // Moving an external trackball or mouse should wake the device.
1646 // We don't do this for internal cursor devices to prevent them from waking up
1647 // the device in your pocket.
1648 // TODO: Use the input device configuration to control this behavior more finely.
1649 uint32_t policyFlags = 0;
1650 if (getDevice()->isExternal()) {
1651 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1652 }
1653
Jeff Brown6d0fec22010-07-23 21:28:06 -07001654 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown6328cdc2010-07-29 18:18:33 -07001655 int32_t pointerId = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08001656 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brown9626b142011-03-03 02:09:54 -08001657 motionEventAction, 0, metaState, motionEventEdgeFlags,
Jeff Brownb6997262010-10-08 22:31:17 -07001658 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1659
Jeff Browna032cc02011-03-07 16:56:21 -08001660 // Send hover move after UP to tell the application that the mouse is hovering now.
1661 if (motionEventAction == AMOTION_EVENT_ACTION_UP
1662 && mPointerController != NULL) {
1663 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
1664 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
1665 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1666 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001667
Jeff Browna032cc02011-03-07 16:56:21 -08001668 // Send scroll events.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001669 if (vscroll != 0 || hscroll != 0) {
1670 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
1671 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
1672
Jeff Brownefd32662011-03-08 15:13:06 -08001673 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brown33bbfd22011-02-24 20:55:35 -08001674 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
1675 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1676 }
Jeff Browna032cc02011-03-07 16:56:21 -08001677
1678 mAccumulator.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001679}
1680
Jeff Brown83c09682010-12-23 17:50:18 -08001681int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brownc3fc2d02010-08-10 15:47:53 -07001682 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
1683 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1684 } else {
1685 return AKEY_STATE_UNKNOWN;
1686 }
1687}
1688
Jeff Brown05dc66a2011-03-02 14:41:58 -08001689void CursorInputMapper::fadePointer() {
1690 { // acquire lock
1691 AutoMutex _l(mLock);
Jeff Brownefd32662011-03-08 15:13:06 -08001692 if (mPointerController != NULL) {
1693 mPointerController->fade();
1694 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001695 } // release lock
1696}
1697
Jeff Brown6d0fec22010-07-23 21:28:06 -07001698
1699// --- TouchInputMapper ---
1700
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001701TouchInputMapper::TouchInputMapper(InputDevice* device) :
1702 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001703 mLocked.surfaceOrientation = -1;
1704 mLocked.surfaceWidth = -1;
1705 mLocked.surfaceHeight = -1;
1706
1707 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001708}
1709
1710TouchInputMapper::~TouchInputMapper() {
1711}
1712
1713uint32_t TouchInputMapper::getSources() {
Jeff Brownace13b12011-03-09 17:39:48 -08001714 return mTouchSource | mPointerSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001715}
1716
1717void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1718 InputMapper::populateDeviceInfo(info);
1719
Jeff Brown6328cdc2010-07-29 18:18:33 -07001720 { // acquire lock
1721 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001722
Jeff Brown6328cdc2010-07-29 18:18:33 -07001723 // Ensure surface information is up to date so that orientation changes are
1724 // noticed immediately.
Jeff Brownefd32662011-03-08 15:13:06 -08001725 if (!configureSurfaceLocked()) {
1726 return;
1727 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001728
Jeff Brownefd32662011-03-08 15:13:06 -08001729 info->addMotionRange(mLocked.orientedRanges.x);
1730 info->addMotionRange(mLocked.orientedRanges.y);
Jeff Brown8d608662010-08-30 03:02:23 -07001731
1732 if (mLocked.orientedRanges.havePressure) {
Jeff Brownefd32662011-03-08 15:13:06 -08001733 info->addMotionRange(mLocked.orientedRanges.pressure);
Jeff Brown8d608662010-08-30 03:02:23 -07001734 }
1735
1736 if (mLocked.orientedRanges.haveSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001737 info->addMotionRange(mLocked.orientedRanges.size);
Jeff Brown8d608662010-08-30 03:02:23 -07001738 }
1739
Jeff Brownc6d282b2010-10-14 21:42:15 -07001740 if (mLocked.orientedRanges.haveTouchSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001741 info->addMotionRange(mLocked.orientedRanges.touchMajor);
1742 info->addMotionRange(mLocked.orientedRanges.touchMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001743 }
1744
Jeff Brownc6d282b2010-10-14 21:42:15 -07001745 if (mLocked.orientedRanges.haveToolSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001746 info->addMotionRange(mLocked.orientedRanges.toolMajor);
1747 info->addMotionRange(mLocked.orientedRanges.toolMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001748 }
1749
1750 if (mLocked.orientedRanges.haveOrientation) {
Jeff Brownefd32662011-03-08 15:13:06 -08001751 info->addMotionRange(mLocked.orientedRanges.orientation);
Jeff Brown8d608662010-08-30 03:02:23 -07001752 }
Jeff Brownace13b12011-03-09 17:39:48 -08001753
1754 if (mPointerController != NULL) {
1755 float minX, minY, maxX, maxY;
1756 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
1757 info->addMotionRange(AMOTION_EVENT_AXIS_X, mPointerSource,
1758 minX, maxX, 0.0f, 0.0f);
1759 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mPointerSource,
1760 minY, maxY, 0.0f, 0.0f);
1761 }
1762 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mPointerSource,
1763 0.0f, 1.0f, 0.0f, 0.0f);
1764 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001765 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001766}
1767
Jeff Brownef3d7e82010-09-30 14:33:04 -07001768void TouchInputMapper::dump(String8& dump) {
1769 { // acquire lock
1770 AutoMutex _l(mLock);
1771 dump.append(INDENT2 "Touch Input Mapper:\n");
Jeff Brownef3d7e82010-09-30 14:33:04 -07001772 dumpParameters(dump);
1773 dumpVirtualKeysLocked(dump);
1774 dumpRawAxes(dump);
1775 dumpCalibration(dump);
1776 dumpSurfaceLocked(dump);
Jeff Brownefd32662011-03-08 15:13:06 -08001777
Jeff Brown511ee5f2010-10-18 13:32:20 -07001778 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
Jeff Brownc6d282b2010-10-14 21:42:15 -07001779 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mLocked.xScale);
1780 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mLocked.yScale);
1781 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mLocked.xPrecision);
1782 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mLocked.yPrecision);
1783 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mLocked.geometricScale);
1784 dump.appendFormat(INDENT4 "ToolSizeLinearScale: %0.3f\n", mLocked.toolSizeLinearScale);
1785 dump.appendFormat(INDENT4 "ToolSizeLinearBias: %0.3f\n", mLocked.toolSizeLinearBias);
1786 dump.appendFormat(INDENT4 "ToolSizeAreaScale: %0.3f\n", mLocked.toolSizeAreaScale);
1787 dump.appendFormat(INDENT4 "ToolSizeAreaBias: %0.3f\n", mLocked.toolSizeAreaBias);
1788 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mLocked.pressureScale);
1789 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mLocked.sizeScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001790 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mLocked.orientationScale);
1791
1792 dump.appendFormat(INDENT3 "Last Touch:\n");
1793 dump.appendFormat(INDENT4 "Pointer Count: %d\n", mLastTouch.pointerCount);
Jeff Brownace13b12011-03-09 17:39:48 -08001794 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", mLastTouch.buttonState);
1795
1796 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
1797 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
1798 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
1799 mLocked.pointerGestureXMovementScale);
1800 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
1801 mLocked.pointerGestureYMovementScale);
1802 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
1803 mLocked.pointerGestureXZoomScale);
1804 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
1805 mLocked.pointerGestureYZoomScale);
Jeff Brown2352b972011-04-12 22:39:53 -07001806 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
1807 mLocked.pointerGestureMaxSwipeWidth);
Jeff Brownace13b12011-03-09 17:39:48 -08001808 }
Jeff Brownef3d7e82010-09-30 14:33:04 -07001809 } // release lock
1810}
1811
Jeff Brown6328cdc2010-07-29 18:18:33 -07001812void TouchInputMapper::initializeLocked() {
1813 mCurrentTouch.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001814 mLastTouch.clear();
1815 mDownTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001816
1817 for (uint32_t i = 0; i < MAX_POINTERS; i++) {
1818 mAveragingTouchFilter.historyStart[i] = 0;
1819 mAveragingTouchFilter.historyEnd[i] = 0;
1820 }
1821
1822 mJumpyTouchFilter.jumpyPointsDropped = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001823
1824 mLocked.currentVirtualKey.down = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001825
1826 mLocked.orientedRanges.havePressure = false;
1827 mLocked.orientedRanges.haveSize = false;
Jeff Brownc6d282b2010-10-14 21:42:15 -07001828 mLocked.orientedRanges.haveTouchSize = false;
1829 mLocked.orientedRanges.haveToolSize = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001830 mLocked.orientedRanges.haveOrientation = false;
Jeff Brownace13b12011-03-09 17:39:48 -08001831
1832 mPointerGesture.reset();
Jeff Brown8d608662010-08-30 03:02:23 -07001833}
1834
Jeff Brown6d0fec22010-07-23 21:28:06 -07001835void TouchInputMapper::configure() {
1836 InputMapper::configure();
1837
1838 // Configure basic parameters.
Jeff Brown8d608662010-08-30 03:02:23 -07001839 configureParameters();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001840
Jeff Brown83c09682010-12-23 17:50:18 -08001841 // Configure sources.
1842 switch (mParameters.deviceType) {
1843 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Jeff Brownefd32662011-03-08 15:13:06 -08001844 mTouchSource = AINPUT_SOURCE_TOUCHSCREEN;
Jeff Brownace13b12011-03-09 17:39:48 -08001845 mPointerSource = 0;
Jeff Brown83c09682010-12-23 17:50:18 -08001846 break;
1847 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Jeff Brownefd32662011-03-08 15:13:06 -08001848 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
Jeff Brownace13b12011-03-09 17:39:48 -08001849 mPointerSource = 0;
1850 break;
1851 case Parameters::DEVICE_TYPE_POINTER:
1852 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
1853 mPointerSource = AINPUT_SOURCE_MOUSE;
Jeff Brown83c09682010-12-23 17:50:18 -08001854 break;
1855 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07001856 LOG_ASSERT(false);
Jeff Brown83c09682010-12-23 17:50:18 -08001857 }
1858
Jeff Brown6d0fec22010-07-23 21:28:06 -07001859 // Configure absolute axis information.
Jeff Brown8d608662010-08-30 03:02:23 -07001860 configureRawAxes();
Jeff Brown8d608662010-08-30 03:02:23 -07001861
1862 // Prepare input device calibration.
1863 parseCalibration();
1864 resolveCalibration();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001865
Jeff Brown6328cdc2010-07-29 18:18:33 -07001866 { // acquire lock
1867 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001868
Jeff Brown8d608662010-08-30 03:02:23 -07001869 // Configure surface dimensions and orientation.
Jeff Brown6328cdc2010-07-29 18:18:33 -07001870 configureSurfaceLocked();
1871 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001872}
1873
Jeff Brown8d608662010-08-30 03:02:23 -07001874void TouchInputMapper::configureParameters() {
1875 mParameters.useBadTouchFilter = getPolicy()->filterTouchEvents();
1876 mParameters.useAveragingTouchFilter = getPolicy()->filterTouchEvents();
1877 mParameters.useJumpyTouchFilter = getPolicy()->filterJumpyTouchEvents();
Jeff Brownfe508922011-01-18 15:10:10 -08001878 mParameters.virtualKeyQuietTime = getPolicy()->getVirtualKeyQuietTime();
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001879
Jeff Brown2352b972011-04-12 22:39:53 -07001880 // TODO: Make this configurable.
1881 //mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER;
1882 mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
1883
Jeff Brownace13b12011-03-09 17:39:48 -08001884 if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
1885 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
1886 // The device is a cursor device with a touch pad attached.
1887 // By default don't use the touch pad to move the pointer.
1888 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
1889 } else {
1890 // The device is just a touch pad.
1891 // By default use the touch pad to move the pointer and to perform related gestures.
1892 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
1893 }
1894
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001895 String8 deviceTypeString;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001896 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
1897 deviceTypeString)) {
Jeff Brown58a2da82011-01-25 16:02:22 -08001898 if (deviceTypeString == "touchScreen") {
1899 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brownefd32662011-03-08 15:13:06 -08001900 } else if (deviceTypeString == "touchPad") {
1901 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
Jeff Brownace13b12011-03-09 17:39:48 -08001902 } else if (deviceTypeString == "pointer") {
1903 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
Jeff Brownefd32662011-03-08 15:13:06 -08001904 } else {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001905 LOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
1906 }
1907 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001908
Jeff Brownefd32662011-03-08 15:13:06 -08001909 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001910 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
1911 mParameters.orientationAware);
1912
Jeff Brownefd32662011-03-08 15:13:06 -08001913 mParameters.associatedDisplayId = mParameters.orientationAware
1914 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
Jeff Brownace13b12011-03-09 17:39:48 -08001915 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
Jeff Brownefd32662011-03-08 15:13:06 -08001916 ? 0 : -1;
Jeff Brown8d608662010-08-30 03:02:23 -07001917}
1918
Jeff Brownef3d7e82010-09-30 14:33:04 -07001919void TouchInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001920 dump.append(INDENT3 "Parameters:\n");
1921
1922 switch (mParameters.deviceType) {
1923 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
1924 dump.append(INDENT4 "DeviceType: touchScreen\n");
1925 break;
1926 case Parameters::DEVICE_TYPE_TOUCH_PAD:
1927 dump.append(INDENT4 "DeviceType: touchPad\n");
1928 break;
Jeff Brownace13b12011-03-09 17:39:48 -08001929 case Parameters::DEVICE_TYPE_POINTER:
1930 dump.append(INDENT4 "DeviceType: pointer\n");
1931 break;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001932 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07001933 LOG_ASSERT(false);
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001934 }
1935
1936 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1937 mParameters.associatedDisplayId);
1938 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1939 toString(mParameters.orientationAware));
1940
1941 dump.appendFormat(INDENT4 "UseBadTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001942 toString(mParameters.useBadTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001943 dump.appendFormat(INDENT4 "UseAveragingTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001944 toString(mParameters.useAveragingTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001945 dump.appendFormat(INDENT4 "UseJumpyTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001946 toString(mParameters.useJumpyTouchFilter));
Jeff Brownb88102f2010-09-08 11:49:43 -07001947}
1948
Jeff Brown8d608662010-08-30 03:02:23 -07001949void TouchInputMapper::configureRawAxes() {
1950 mRawAxes.x.clear();
1951 mRawAxes.y.clear();
1952 mRawAxes.pressure.clear();
1953 mRawAxes.touchMajor.clear();
1954 mRawAxes.touchMinor.clear();
1955 mRawAxes.toolMajor.clear();
1956 mRawAxes.toolMinor.clear();
1957 mRawAxes.orientation.clear();
1958}
1959
Jeff Brownef3d7e82010-09-30 14:33:04 -07001960void TouchInputMapper::dumpRawAxes(String8& dump) {
1961 dump.append(INDENT3 "Raw Axes:\n");
Jeff Browncb1404e2011-01-15 18:14:15 -08001962 dumpRawAbsoluteAxisInfo(dump, mRawAxes.x, "X");
1963 dumpRawAbsoluteAxisInfo(dump, mRawAxes.y, "Y");
1964 dumpRawAbsoluteAxisInfo(dump, mRawAxes.pressure, "Pressure");
1965 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMajor, "TouchMajor");
1966 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMinor, "TouchMinor");
1967 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMajor, "ToolMajor");
1968 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMinor, "ToolMinor");
1969 dumpRawAbsoluteAxisInfo(dump, mRawAxes.orientation, "Orientation");
Jeff Brown6d0fec22010-07-23 21:28:06 -07001970}
1971
Jeff Brown6328cdc2010-07-29 18:18:33 -07001972bool TouchInputMapper::configureSurfaceLocked() {
Jeff Brown9626b142011-03-03 02:09:54 -08001973 // Ensure we have valid X and Y axes.
1974 if (!mRawAxes.x.valid || !mRawAxes.y.valid) {
1975 LOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
1976 "The device will be inoperable.", getDeviceName().string());
1977 return false;
1978 }
1979
Jeff Brown6d0fec22010-07-23 21:28:06 -07001980 // Update orientation and dimensions if needed.
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001981 int32_t orientation = DISPLAY_ORIENTATION_0;
Jeff Brown9626b142011-03-03 02:09:54 -08001982 int32_t width = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
1983 int32_t height = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001984
1985 if (mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001986 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001987 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
Jeff Brownefd32662011-03-08 15:13:06 -08001988 &mLocked.associatedDisplayWidth, &mLocked.associatedDisplayHeight,
1989 &mLocked.associatedDisplayOrientation)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001990 return false;
1991 }
Jeff Brownefd32662011-03-08 15:13:06 -08001992
1993 // A touch screen inherits the dimensions of the display.
1994 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
1995 width = mLocked.associatedDisplayWidth;
1996 height = mLocked.associatedDisplayHeight;
1997 }
1998
1999 // The device inherits the orientation of the display if it is orientation aware.
2000 if (mParameters.orientationAware) {
2001 orientation = mLocked.associatedDisplayOrientation;
2002 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002003 }
2004
Jeff Brownace13b12011-03-09 17:39:48 -08002005 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
2006 && mPointerController == NULL) {
2007 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2008 }
2009
Jeff Brown6328cdc2010-07-29 18:18:33 -07002010 bool orientationChanged = mLocked.surfaceOrientation != orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002011 if (orientationChanged) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002012 mLocked.surfaceOrientation = orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002013 }
2014
Jeff Brown6328cdc2010-07-29 18:18:33 -07002015 bool sizeChanged = mLocked.surfaceWidth != width || mLocked.surfaceHeight != height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002016 if (sizeChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08002017 LOGI("Device reconfigured: id=%d, name='%s', surface size is now %dx%d",
Jeff Brownef3d7e82010-09-30 14:33:04 -07002018 getDeviceId(), getDeviceName().string(), width, height);
Jeff Brown8d608662010-08-30 03:02:23 -07002019
Jeff Brown6328cdc2010-07-29 18:18:33 -07002020 mLocked.surfaceWidth = width;
2021 mLocked.surfaceHeight = height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002022
Jeff Brown8d608662010-08-30 03:02:23 -07002023 // Configure X and Y factors.
Jeff Brown9626b142011-03-03 02:09:54 -08002024 mLocked.xScale = float(width) / (mRawAxes.x.maxValue - mRawAxes.x.minValue + 1);
2025 mLocked.yScale = float(height) / (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1);
2026 mLocked.xPrecision = 1.0f / mLocked.xScale;
2027 mLocked.yPrecision = 1.0f / mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002028
Jeff Brownefd32662011-03-08 15:13:06 -08002029 mLocked.orientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
2030 mLocked.orientedRanges.x.source = mTouchSource;
2031 mLocked.orientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
2032 mLocked.orientedRanges.y.source = mTouchSource;
2033
Jeff Brown9626b142011-03-03 02:09:54 -08002034 configureVirtualKeysLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002035
Jeff Brown8d608662010-08-30 03:02:23 -07002036 // Scale factor for terms that are not oriented in a particular axis.
2037 // If the pixels are square then xScale == yScale otherwise we fake it
2038 // by choosing an average.
2039 mLocked.geometricScale = avg(mLocked.xScale, mLocked.yScale);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002040
Jeff Brown8d608662010-08-30 03:02:23 -07002041 // Size of diagonal axis.
Jeff Brown2352b972011-04-12 22:39:53 -07002042 float diagonalSize = hypotf(width, height);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002043
Jeff Brown8d608662010-08-30 03:02:23 -07002044 // TouchMajor and TouchMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002045 if (mCalibration.touchSizeCalibration != Calibration::TOUCH_SIZE_CALIBRATION_NONE) {
2046 mLocked.orientedRanges.haveTouchSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002047
2048 mLocked.orientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
2049 mLocked.orientedRanges.touchMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002050 mLocked.orientedRanges.touchMajor.min = 0;
2051 mLocked.orientedRanges.touchMajor.max = diagonalSize;
2052 mLocked.orientedRanges.touchMajor.flat = 0;
2053 mLocked.orientedRanges.touchMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08002054
Jeff Brown8d608662010-08-30 03:02:23 -07002055 mLocked.orientedRanges.touchMinor = mLocked.orientedRanges.touchMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08002056 mLocked.orientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002057 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002058
Jeff Brown8d608662010-08-30 03:02:23 -07002059 // ToolMajor and ToolMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002060 mLocked.toolSizeLinearScale = 0;
2061 mLocked.toolSizeLinearBias = 0;
2062 mLocked.toolSizeAreaScale = 0;
2063 mLocked.toolSizeAreaBias = 0;
2064 if (mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2065 if (mCalibration.toolSizeCalibration == Calibration::TOOL_SIZE_CALIBRATION_LINEAR) {
2066 if (mCalibration.haveToolSizeLinearScale) {
2067 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
Jeff Brown8d608662010-08-30 03:02:23 -07002068 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002069 mLocked.toolSizeLinearScale = float(min(width, height))
Jeff Brown8d608662010-08-30 03:02:23 -07002070 / mRawAxes.toolMajor.maxValue;
2071 }
2072
Jeff Brownc6d282b2010-10-14 21:42:15 -07002073 if (mCalibration.haveToolSizeLinearBias) {
2074 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2075 }
2076 } else if (mCalibration.toolSizeCalibration ==
2077 Calibration::TOOL_SIZE_CALIBRATION_AREA) {
2078 if (mCalibration.haveToolSizeLinearScale) {
2079 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
2080 } else {
2081 mLocked.toolSizeLinearScale = min(width, height);
2082 }
2083
2084 if (mCalibration.haveToolSizeLinearBias) {
2085 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2086 }
2087
2088 if (mCalibration.haveToolSizeAreaScale) {
2089 mLocked.toolSizeAreaScale = mCalibration.toolSizeAreaScale;
2090 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2091 mLocked.toolSizeAreaScale = 1.0f / mRawAxes.toolMajor.maxValue;
2092 }
2093
2094 if (mCalibration.haveToolSizeAreaBias) {
2095 mLocked.toolSizeAreaBias = mCalibration.toolSizeAreaBias;
Jeff Brown8d608662010-08-30 03:02:23 -07002096 }
2097 }
2098
Jeff Brownc6d282b2010-10-14 21:42:15 -07002099 mLocked.orientedRanges.haveToolSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002100
2101 mLocked.orientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
2102 mLocked.orientedRanges.toolMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002103 mLocked.orientedRanges.toolMajor.min = 0;
2104 mLocked.orientedRanges.toolMajor.max = diagonalSize;
2105 mLocked.orientedRanges.toolMajor.flat = 0;
2106 mLocked.orientedRanges.toolMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08002107
Jeff Brown8d608662010-08-30 03:02:23 -07002108 mLocked.orientedRanges.toolMinor = mLocked.orientedRanges.toolMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08002109 mLocked.orientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002110 }
2111
2112 // Pressure factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002113 mLocked.pressureScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002114 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE) {
2115 RawAbsoluteAxisInfo rawPressureAxis;
2116 switch (mCalibration.pressureSource) {
2117 case Calibration::PRESSURE_SOURCE_PRESSURE:
2118 rawPressureAxis = mRawAxes.pressure;
2119 break;
2120 case Calibration::PRESSURE_SOURCE_TOUCH:
2121 rawPressureAxis = mRawAxes.touchMajor;
2122 break;
2123 default:
2124 rawPressureAxis.clear();
2125 }
2126
Jeff Brown8d608662010-08-30 03:02:23 -07002127 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
2128 || mCalibration.pressureCalibration
2129 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
2130 if (mCalibration.havePressureScale) {
2131 mLocked.pressureScale = mCalibration.pressureScale;
2132 } else if (rawPressureAxis.valid && rawPressureAxis.maxValue != 0) {
2133 mLocked.pressureScale = 1.0f / rawPressureAxis.maxValue;
2134 }
2135 }
2136
2137 mLocked.orientedRanges.havePressure = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002138
2139 mLocked.orientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
2140 mLocked.orientedRanges.pressure.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002141 mLocked.orientedRanges.pressure.min = 0;
2142 mLocked.orientedRanges.pressure.max = 1.0;
2143 mLocked.orientedRanges.pressure.flat = 0;
2144 mLocked.orientedRanges.pressure.fuzz = 0;
2145 }
2146
2147 // Size factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002148 mLocked.sizeScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002149 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002150 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_NORMALIZED) {
2151 if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2152 mLocked.sizeScale = 1.0f / mRawAxes.toolMajor.maxValue;
2153 }
2154 }
2155
2156 mLocked.orientedRanges.haveSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002157
2158 mLocked.orientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
2159 mLocked.orientedRanges.size.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002160 mLocked.orientedRanges.size.min = 0;
2161 mLocked.orientedRanges.size.max = 1.0;
2162 mLocked.orientedRanges.size.flat = 0;
2163 mLocked.orientedRanges.size.fuzz = 0;
2164 }
2165
2166 // Orientation
Jeff Brownc6d282b2010-10-14 21:42:15 -07002167 mLocked.orientationScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002168 if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002169 if (mCalibration.orientationCalibration
2170 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
2171 if (mRawAxes.orientation.valid && mRawAxes.orientation.maxValue != 0) {
2172 mLocked.orientationScale = float(M_PI_2) / mRawAxes.orientation.maxValue;
2173 }
2174 }
2175
Jeff Brownefd32662011-03-08 15:13:06 -08002176 mLocked.orientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
2177 mLocked.orientedRanges.orientation.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002178 mLocked.orientedRanges.orientation.min = - M_PI_2;
2179 mLocked.orientedRanges.orientation.max = M_PI_2;
2180 mLocked.orientedRanges.orientation.flat = 0;
2181 mLocked.orientedRanges.orientation.fuzz = 0;
2182 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002183 }
2184
2185 if (orientationChanged || sizeChanged) {
Jeff Brown9626b142011-03-03 02:09:54 -08002186 // Compute oriented surface dimensions, precision, scales and ranges.
2187 // Note that the maximum value reported is an inclusive maximum value so it is one
2188 // unit less than the total width or height of surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002189 switch (mLocked.surfaceOrientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08002190 case DISPLAY_ORIENTATION_90:
2191 case DISPLAY_ORIENTATION_270:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002192 mLocked.orientedSurfaceWidth = mLocked.surfaceHeight;
2193 mLocked.orientedSurfaceHeight = mLocked.surfaceWidth;
Jeff Brown9626b142011-03-03 02:09:54 -08002194
Jeff Brown6328cdc2010-07-29 18:18:33 -07002195 mLocked.orientedXPrecision = mLocked.yPrecision;
2196 mLocked.orientedYPrecision = mLocked.xPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002197
2198 mLocked.orientedRanges.x.min = 0;
2199 mLocked.orientedRanges.x.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2200 * mLocked.yScale;
2201 mLocked.orientedRanges.x.flat = 0;
2202 mLocked.orientedRanges.x.fuzz = mLocked.yScale;
2203
2204 mLocked.orientedRanges.y.min = 0;
2205 mLocked.orientedRanges.y.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2206 * mLocked.xScale;
2207 mLocked.orientedRanges.y.flat = 0;
2208 mLocked.orientedRanges.y.fuzz = mLocked.xScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002209 break;
Jeff Brown9626b142011-03-03 02:09:54 -08002210
Jeff Brown6d0fec22010-07-23 21:28:06 -07002211 default:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002212 mLocked.orientedSurfaceWidth = mLocked.surfaceWidth;
2213 mLocked.orientedSurfaceHeight = mLocked.surfaceHeight;
Jeff Brown9626b142011-03-03 02:09:54 -08002214
Jeff Brown6328cdc2010-07-29 18:18:33 -07002215 mLocked.orientedXPrecision = mLocked.xPrecision;
2216 mLocked.orientedYPrecision = mLocked.yPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002217
2218 mLocked.orientedRanges.x.min = 0;
2219 mLocked.orientedRanges.x.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2220 * mLocked.xScale;
2221 mLocked.orientedRanges.x.flat = 0;
2222 mLocked.orientedRanges.x.fuzz = mLocked.xScale;
2223
2224 mLocked.orientedRanges.y.min = 0;
2225 mLocked.orientedRanges.y.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2226 * mLocked.yScale;
2227 mLocked.orientedRanges.y.flat = 0;
2228 mLocked.orientedRanges.y.fuzz = mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002229 break;
2230 }
Jeff Brownace13b12011-03-09 17:39:48 -08002231
2232 // Compute pointer gesture detection parameters.
2233 // TODO: These factors should not be hardcoded.
2234 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
2235 int32_t rawWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2236 int32_t rawHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown2352b972011-04-12 22:39:53 -07002237 float rawDiagonal = hypotf(rawWidth, rawHeight);
2238 float displayDiagonal = hypotf(mLocked.associatedDisplayWidth,
2239 mLocked.associatedDisplayHeight);
Jeff Brownace13b12011-03-09 17:39:48 -08002240
Jeff Brown2352b972011-04-12 22:39:53 -07002241 // Scale movements such that one whole swipe of the touch pad covers a
2242 // given area relative to the diagonal size of the display.
Jeff Brownace13b12011-03-09 17:39:48 -08002243 // Assume that the touch pad has a square aspect ratio such that movements in
2244 // X and Y of the same number of raw units cover the same physical distance.
2245 const float scaleFactor = 0.8f;
2246
Jeff Brown2352b972011-04-12 22:39:53 -07002247 mLocked.pointerGestureXMovementScale = GESTURE_MOVEMENT_SPEED_RATIO
2248 * displayDiagonal / rawDiagonal;
Jeff Brownace13b12011-03-09 17:39:48 -08002249 mLocked.pointerGestureYMovementScale = mLocked.pointerGestureXMovementScale;
2250
2251 // Scale zooms to cover a smaller range of the display than movements do.
2252 // This value determines the area around the pointer that is affected by freeform
2253 // pointer gestures.
Jeff Brown2352b972011-04-12 22:39:53 -07002254 mLocked.pointerGestureXZoomScale = GESTURE_ZOOM_SPEED_RATIO
2255 * displayDiagonal / rawDiagonal;
2256 mLocked.pointerGestureYZoomScale = mLocked.pointerGestureXZoomScale;
Jeff Brownace13b12011-03-09 17:39:48 -08002257
Jeff Brown2352b972011-04-12 22:39:53 -07002258 // Max width between pointers to detect a swipe gesture is more than some fraction
2259 // of the diagonal axis of the touch pad. Touches that are wider than this are
2260 // translated into freeform gestures.
2261 mLocked.pointerGestureMaxSwipeWidth = SWIPE_MAX_WIDTH_RATIO * rawDiagonal;
2262
2263 // Reset the current pointer gesture.
2264 mPointerGesture.reset();
2265
2266 // Remove any current spots.
2267 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
2268 mPointerController->clearSpots();
2269 }
Jeff Brownace13b12011-03-09 17:39:48 -08002270 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002271 }
2272
2273 return true;
2274}
2275
Jeff Brownef3d7e82010-09-30 14:33:04 -07002276void TouchInputMapper::dumpSurfaceLocked(String8& dump) {
2277 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mLocked.surfaceWidth);
2278 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mLocked.surfaceHeight);
2279 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mLocked.surfaceOrientation);
Jeff Brownb88102f2010-09-08 11:49:43 -07002280}
2281
Jeff Brown6328cdc2010-07-29 18:18:33 -07002282void TouchInputMapper::configureVirtualKeysLocked() {
Jeff Brown8d608662010-08-30 03:02:23 -07002283 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
Jeff Brown90655042010-12-02 13:50:46 -08002284 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002285
Jeff Brown6328cdc2010-07-29 18:18:33 -07002286 mLocked.virtualKeys.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002287
Jeff Brown6328cdc2010-07-29 18:18:33 -07002288 if (virtualKeyDefinitions.size() == 0) {
2289 return;
2290 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002291
Jeff Brown6328cdc2010-07-29 18:18:33 -07002292 mLocked.virtualKeys.setCapacity(virtualKeyDefinitions.size());
2293
Jeff Brown8d608662010-08-30 03:02:23 -07002294 int32_t touchScreenLeft = mRawAxes.x.minValue;
2295 int32_t touchScreenTop = mRawAxes.y.minValue;
Jeff Brown9626b142011-03-03 02:09:54 -08002296 int32_t touchScreenWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2297 int32_t touchScreenHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002298
2299 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002300 const VirtualKeyDefinition& virtualKeyDefinition =
Jeff Brown6328cdc2010-07-29 18:18:33 -07002301 virtualKeyDefinitions[i];
2302
2303 mLocked.virtualKeys.add();
2304 VirtualKey& virtualKey = mLocked.virtualKeys.editTop();
2305
2306 virtualKey.scanCode = virtualKeyDefinition.scanCode;
2307 int32_t keyCode;
2308 uint32_t flags;
Jeff Brown6f2fba42011-02-19 01:08:02 -08002309 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode,
Jeff Brown6328cdc2010-07-29 18:18:33 -07002310 & keyCode, & flags)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002311 LOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
2312 virtualKey.scanCode);
Jeff Brown6328cdc2010-07-29 18:18:33 -07002313 mLocked.virtualKeys.pop(); // drop the key
2314 continue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002315 }
2316
Jeff Brown6328cdc2010-07-29 18:18:33 -07002317 virtualKey.keyCode = keyCode;
2318 virtualKey.flags = flags;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002319
Jeff Brown6328cdc2010-07-29 18:18:33 -07002320 // convert the key definition's display coordinates into touch coordinates for a hit box
2321 int32_t halfWidth = virtualKeyDefinition.width / 2;
2322 int32_t halfHeight = virtualKeyDefinition.height / 2;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002323
Jeff Brown6328cdc2010-07-29 18:18:33 -07002324 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
2325 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2326 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
2327 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2328 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
2329 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
2330 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
2331 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
Jeff Brownef3d7e82010-09-30 14:33:04 -07002332 }
2333}
2334
2335void TouchInputMapper::dumpVirtualKeysLocked(String8& dump) {
2336 if (!mLocked.virtualKeys.isEmpty()) {
2337 dump.append(INDENT3 "Virtual Keys:\n");
2338
2339 for (size_t i = 0; i < mLocked.virtualKeys.size(); i++) {
2340 const VirtualKey& virtualKey = mLocked.virtualKeys.itemAt(i);
2341 dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, "
2342 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
2343 i, virtualKey.scanCode, virtualKey.keyCode,
2344 virtualKey.hitLeft, virtualKey.hitRight,
2345 virtualKey.hitTop, virtualKey.hitBottom);
2346 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002347 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002348}
2349
Jeff Brown8d608662010-08-30 03:02:23 -07002350void TouchInputMapper::parseCalibration() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002351 const PropertyMap& in = getDevice()->getConfiguration();
Jeff Brown8d608662010-08-30 03:02:23 -07002352 Calibration& out = mCalibration;
2353
Jeff Brownc6d282b2010-10-14 21:42:15 -07002354 // Touch Size
2355 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT;
2356 String8 touchSizeCalibrationString;
2357 if (in.tryGetProperty(String8("touch.touchSize.calibration"), touchSizeCalibrationString)) {
2358 if (touchSizeCalibrationString == "none") {
2359 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
2360 } else if (touchSizeCalibrationString == "geometric") {
2361 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC;
2362 } else if (touchSizeCalibrationString == "pressure") {
2363 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
2364 } else if (touchSizeCalibrationString != "default") {
2365 LOGW("Invalid value for touch.touchSize.calibration: '%s'",
2366 touchSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002367 }
2368 }
2369
Jeff Brownc6d282b2010-10-14 21:42:15 -07002370 // Tool Size
2371 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_DEFAULT;
2372 String8 toolSizeCalibrationString;
2373 if (in.tryGetProperty(String8("touch.toolSize.calibration"), toolSizeCalibrationString)) {
2374 if (toolSizeCalibrationString == "none") {
2375 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
2376 } else if (toolSizeCalibrationString == "geometric") {
2377 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC;
2378 } else if (toolSizeCalibrationString == "linear") {
2379 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
2380 } else if (toolSizeCalibrationString == "area") {
2381 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_AREA;
2382 } else if (toolSizeCalibrationString != "default") {
2383 LOGW("Invalid value for touch.toolSize.calibration: '%s'",
2384 toolSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002385 }
2386 }
2387
Jeff Brownc6d282b2010-10-14 21:42:15 -07002388 out.haveToolSizeLinearScale = in.tryGetProperty(String8("touch.toolSize.linearScale"),
2389 out.toolSizeLinearScale);
2390 out.haveToolSizeLinearBias = in.tryGetProperty(String8("touch.toolSize.linearBias"),
2391 out.toolSizeLinearBias);
2392 out.haveToolSizeAreaScale = in.tryGetProperty(String8("touch.toolSize.areaScale"),
2393 out.toolSizeAreaScale);
2394 out.haveToolSizeAreaBias = in.tryGetProperty(String8("touch.toolSize.areaBias"),
2395 out.toolSizeAreaBias);
2396 out.haveToolSizeIsSummed = in.tryGetProperty(String8("touch.toolSize.isSummed"),
2397 out.toolSizeIsSummed);
Jeff Brown8d608662010-08-30 03:02:23 -07002398
2399 // Pressure
2400 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
2401 String8 pressureCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002402 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002403 if (pressureCalibrationString == "none") {
2404 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2405 } else if (pressureCalibrationString == "physical") {
2406 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
2407 } else if (pressureCalibrationString == "amplitude") {
2408 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2409 } else if (pressureCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002410 LOGW("Invalid value for touch.pressure.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002411 pressureCalibrationString.string());
2412 }
2413 }
2414
2415 out.pressureSource = Calibration::PRESSURE_SOURCE_DEFAULT;
2416 String8 pressureSourceString;
2417 if (in.tryGetProperty(String8("touch.pressure.source"), pressureSourceString)) {
2418 if (pressureSourceString == "pressure") {
2419 out.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2420 } else if (pressureSourceString == "touch") {
2421 out.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2422 } else if (pressureSourceString != "default") {
2423 LOGW("Invalid value for touch.pressure.source: '%s'",
2424 pressureSourceString.string());
2425 }
2426 }
2427
2428 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
2429 out.pressureScale);
2430
2431 // Size
2432 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
2433 String8 sizeCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002434 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002435 if (sizeCalibrationString == "none") {
2436 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2437 } else if (sizeCalibrationString == "normalized") {
2438 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2439 } else if (sizeCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002440 LOGW("Invalid value for touch.size.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002441 sizeCalibrationString.string());
2442 }
2443 }
2444
2445 // Orientation
2446 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
2447 String8 orientationCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002448 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002449 if (orientationCalibrationString == "none") {
2450 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2451 } else if (orientationCalibrationString == "interpolated") {
2452 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002453 } else if (orientationCalibrationString == "vector") {
2454 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002455 } else if (orientationCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002456 LOGW("Invalid value for touch.orientation.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002457 orientationCalibrationString.string());
2458 }
2459 }
2460}
2461
2462void TouchInputMapper::resolveCalibration() {
2463 // Pressure
2464 switch (mCalibration.pressureSource) {
2465 case Calibration::PRESSURE_SOURCE_DEFAULT:
2466 if (mRawAxes.pressure.valid) {
2467 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2468 } else if (mRawAxes.touchMajor.valid) {
2469 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2470 }
2471 break;
2472
2473 case Calibration::PRESSURE_SOURCE_PRESSURE:
2474 if (! mRawAxes.pressure.valid) {
2475 LOGW("Calibration property touch.pressure.source is 'pressure' but "
2476 "the pressure axis is not available.");
2477 }
2478 break;
2479
2480 case Calibration::PRESSURE_SOURCE_TOUCH:
2481 if (! mRawAxes.touchMajor.valid) {
2482 LOGW("Calibration property touch.pressure.source is 'touch' but "
2483 "the touchMajor axis is not available.");
2484 }
2485 break;
2486
2487 default:
2488 break;
2489 }
2490
2491 switch (mCalibration.pressureCalibration) {
2492 case Calibration::PRESSURE_CALIBRATION_DEFAULT:
2493 if (mCalibration.pressureSource != Calibration::PRESSURE_SOURCE_DEFAULT) {
2494 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2495 } else {
2496 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2497 }
2498 break;
2499
2500 default:
2501 break;
2502 }
2503
Jeff Brownc6d282b2010-10-14 21:42:15 -07002504 // Tool Size
2505 switch (mCalibration.toolSizeCalibration) {
2506 case Calibration::TOOL_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002507 if (mRawAxes.toolMajor.valid) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002508 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
Jeff Brown8d608662010-08-30 03:02:23 -07002509 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002510 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002511 }
2512 break;
2513
2514 default:
2515 break;
2516 }
2517
Jeff Brownc6d282b2010-10-14 21:42:15 -07002518 // Touch Size
2519 switch (mCalibration.touchSizeCalibration) {
2520 case Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002521 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE
Jeff Brownc6d282b2010-10-14 21:42:15 -07002522 && mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2523 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
Jeff Brown8d608662010-08-30 03:02:23 -07002524 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002525 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002526 }
2527 break;
2528
2529 default:
2530 break;
2531 }
2532
2533 // Size
2534 switch (mCalibration.sizeCalibration) {
2535 case Calibration::SIZE_CALIBRATION_DEFAULT:
2536 if (mRawAxes.toolMajor.valid) {
2537 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2538 } else {
2539 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2540 }
2541 break;
2542
2543 default:
2544 break;
2545 }
2546
2547 // Orientation
2548 switch (mCalibration.orientationCalibration) {
2549 case Calibration::ORIENTATION_CALIBRATION_DEFAULT:
2550 if (mRawAxes.orientation.valid) {
2551 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
2552 } else {
2553 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2554 }
2555 break;
2556
2557 default:
2558 break;
2559 }
2560}
2561
Jeff Brownef3d7e82010-09-30 14:33:04 -07002562void TouchInputMapper::dumpCalibration(String8& dump) {
2563 dump.append(INDENT3 "Calibration:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002564
Jeff Brownc6d282b2010-10-14 21:42:15 -07002565 // Touch Size
2566 switch (mCalibration.touchSizeCalibration) {
2567 case Calibration::TOUCH_SIZE_CALIBRATION_NONE:
2568 dump.append(INDENT4 "touch.touchSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002569 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002570 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
2571 dump.append(INDENT4 "touch.touchSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002572 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002573 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
2574 dump.append(INDENT4 "touch.touchSize.calibration: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002575 break;
2576 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002577 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002578 }
2579
Jeff Brownc6d282b2010-10-14 21:42:15 -07002580 // Tool Size
2581 switch (mCalibration.toolSizeCalibration) {
2582 case Calibration::TOOL_SIZE_CALIBRATION_NONE:
2583 dump.append(INDENT4 "touch.toolSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002584 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002585 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
2586 dump.append(INDENT4 "touch.toolSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002587 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002588 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
2589 dump.append(INDENT4 "touch.toolSize.calibration: linear\n");
2590 break;
2591 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
2592 dump.append(INDENT4 "touch.toolSize.calibration: area\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002593 break;
2594 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002595 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002596 }
2597
Jeff Brownc6d282b2010-10-14 21:42:15 -07002598 if (mCalibration.haveToolSizeLinearScale) {
2599 dump.appendFormat(INDENT4 "touch.toolSize.linearScale: %0.3f\n",
2600 mCalibration.toolSizeLinearScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002601 }
2602
Jeff Brownc6d282b2010-10-14 21:42:15 -07002603 if (mCalibration.haveToolSizeLinearBias) {
2604 dump.appendFormat(INDENT4 "touch.toolSize.linearBias: %0.3f\n",
2605 mCalibration.toolSizeLinearBias);
Jeff Brown8d608662010-08-30 03:02:23 -07002606 }
2607
Jeff Brownc6d282b2010-10-14 21:42:15 -07002608 if (mCalibration.haveToolSizeAreaScale) {
2609 dump.appendFormat(INDENT4 "touch.toolSize.areaScale: %0.3f\n",
2610 mCalibration.toolSizeAreaScale);
2611 }
2612
2613 if (mCalibration.haveToolSizeAreaBias) {
2614 dump.appendFormat(INDENT4 "touch.toolSize.areaBias: %0.3f\n",
2615 mCalibration.toolSizeAreaBias);
2616 }
2617
2618 if (mCalibration.haveToolSizeIsSummed) {
Jeff Brown1f245102010-11-18 20:53:46 -08002619 dump.appendFormat(INDENT4 "touch.toolSize.isSummed: %s\n",
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002620 toString(mCalibration.toolSizeIsSummed));
Jeff Brown8d608662010-08-30 03:02:23 -07002621 }
2622
2623 // Pressure
2624 switch (mCalibration.pressureCalibration) {
2625 case Calibration::PRESSURE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002626 dump.append(INDENT4 "touch.pressure.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002627 break;
2628 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002629 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002630 break;
2631 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002632 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002633 break;
2634 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002635 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002636 }
2637
2638 switch (mCalibration.pressureSource) {
2639 case Calibration::PRESSURE_SOURCE_PRESSURE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002640 dump.append(INDENT4 "touch.pressure.source: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002641 break;
2642 case Calibration::PRESSURE_SOURCE_TOUCH:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002643 dump.append(INDENT4 "touch.pressure.source: touch\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002644 break;
2645 case Calibration::PRESSURE_SOURCE_DEFAULT:
2646 break;
2647 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002648 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002649 }
2650
2651 if (mCalibration.havePressureScale) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07002652 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
2653 mCalibration.pressureScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002654 }
2655
2656 // Size
2657 switch (mCalibration.sizeCalibration) {
2658 case Calibration::SIZE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002659 dump.append(INDENT4 "touch.size.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002660 break;
2661 case Calibration::SIZE_CALIBRATION_NORMALIZED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002662 dump.append(INDENT4 "touch.size.calibration: normalized\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002663 break;
2664 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002665 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002666 }
2667
2668 // Orientation
2669 switch (mCalibration.orientationCalibration) {
2670 case Calibration::ORIENTATION_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002671 dump.append(INDENT4 "touch.orientation.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002672 break;
2673 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002674 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002675 break;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002676 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
2677 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
2678 break;
Jeff Brown8d608662010-08-30 03:02:23 -07002679 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002680 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002681 }
2682}
2683
Jeff Brown6d0fec22010-07-23 21:28:06 -07002684void TouchInputMapper::reset() {
2685 // Synthesize touch up event if touch is currently down.
2686 // This will also take care of finishing virtual key processing if needed.
2687 if (mLastTouch.pointerCount != 0) {
2688 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
2689 mCurrentTouch.clear();
2690 syncTouch(when, true);
2691 }
2692
Jeff Brown6328cdc2010-07-29 18:18:33 -07002693 { // acquire lock
2694 AutoMutex _l(mLock);
2695 initializeLocked();
Jeff Brown2352b972011-04-12 22:39:53 -07002696
2697 if (mPointerController != NULL
2698 && mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
2699 mPointerController->clearSpots();
2700 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002701 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002702
Jeff Brown6328cdc2010-07-29 18:18:33 -07002703 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002704}
2705
2706void TouchInputMapper::syncTouch(nsecs_t when, bool havePointerIds) {
Jeff Brownaa3855d2011-03-17 01:34:19 -07002707#if DEBUG_RAW_EVENTS
2708 if (!havePointerIds) {
2709 LOGD("syncTouch: pointerCount=%d, no pointer ids", mCurrentTouch.pointerCount);
2710 } else {
2711 LOGD("syncTouch: pointerCount=%d, up=0x%08x, down=0x%08x, move=0x%08x, "
2712 "last=0x%08x, current=0x%08x", mCurrentTouch.pointerCount,
2713 mLastTouch.idBits.value & ~mCurrentTouch.idBits.value,
2714 mCurrentTouch.idBits.value & ~mLastTouch.idBits.value,
2715 mLastTouch.idBits.value & mCurrentTouch.idBits.value,
2716 mLastTouch.idBits.value, mCurrentTouch.idBits.value);
2717 }
2718#endif
2719
Jeff Brown6328cdc2010-07-29 18:18:33 -07002720 // Preprocess pointer data.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002721 if (mParameters.useBadTouchFilter) {
2722 if (applyBadTouchFilter()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002723 havePointerIds = false;
2724 }
2725 }
2726
Jeff Brown6d0fec22010-07-23 21:28:06 -07002727 if (mParameters.useJumpyTouchFilter) {
2728 if (applyJumpyTouchFilter()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002729 havePointerIds = false;
2730 }
2731 }
2732
Jeff Brownaa3855d2011-03-17 01:34:19 -07002733 if (!havePointerIds) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002734 calculatePointerIds();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002735 }
2736
Jeff Brown6d0fec22010-07-23 21:28:06 -07002737 TouchData temp;
2738 TouchData* savedTouch;
2739 if (mParameters.useAveragingTouchFilter) {
2740 temp.copyFrom(mCurrentTouch);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002741 savedTouch = & temp;
2742
Jeff Brown6d0fec22010-07-23 21:28:06 -07002743 applyAveragingTouchFilter();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002744 } else {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002745 savedTouch = & mCurrentTouch;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002746 }
2747
Jeff Brown56194eb2011-03-02 19:23:13 -08002748 uint32_t policyFlags = 0;
Jeff Brown05dc66a2011-03-02 14:41:58 -08002749 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
Jeff Brownefd32662011-03-08 15:13:06 -08002750 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
2751 // If this is a touch screen, hide the pointer on an initial down.
2752 getContext()->fadePointer();
2753 }
Jeff Brown56194eb2011-03-02 19:23:13 -08002754
2755 // Initial downs on external touch devices should wake the device.
2756 // We don't do this for internal touch screens to prevent them from waking
2757 // up in your pocket.
2758 // TODO: Use the input device configuration to control this behavior more finely.
2759 if (getDevice()->isExternal()) {
2760 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
2761 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08002762 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002763
Jeff Brown05dc66a2011-03-02 14:41:58 -08002764 // Process touches and virtual keys.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002765 TouchResult touchResult = consumeOffScreenTouches(when, policyFlags);
2766 if (touchResult == DISPATCH_TOUCH) {
Jeff Brownefd32662011-03-08 15:13:06 -08002767 suppressSwipeOntoVirtualKeys(when);
Jeff Brownace13b12011-03-09 17:39:48 -08002768 if (mPointerController != NULL) {
2769 dispatchPointerGestures(when, policyFlags);
2770 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002771 dispatchTouches(when, policyFlags);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002772 }
2773
Jeff Brown6328cdc2010-07-29 18:18:33 -07002774 // Copy current touch to last touch in preparation for the next cycle.
Jeff Brownace13b12011-03-09 17:39:48 -08002775 // Keep the button state so we can track edge-triggered button state changes.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002776 if (touchResult == DROP_STROKE) {
2777 mLastTouch.clear();
Jeff Brownace13b12011-03-09 17:39:48 -08002778 mLastTouch.buttonState = savedTouch->buttonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002779 } else {
2780 mLastTouch.copyFrom(*savedTouch);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002781 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002782}
2783
Jeff Brown6d0fec22010-07-23 21:28:06 -07002784TouchInputMapper::TouchResult TouchInputMapper::consumeOffScreenTouches(
2785 nsecs_t when, uint32_t policyFlags) {
2786 int32_t keyEventAction, keyEventFlags;
2787 int32_t keyCode, scanCode, downTime;
2788 TouchResult touchResult;
Jeff Brown349703e2010-06-22 01:27:15 -07002789
Jeff Brown6328cdc2010-07-29 18:18:33 -07002790 { // acquire lock
2791 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002792
Jeff Brown6328cdc2010-07-29 18:18:33 -07002793 // Update surface size and orientation, including virtual key positions.
2794 if (! configureSurfaceLocked()) {
2795 return DROP_STROKE;
2796 }
2797
2798 // Check for virtual key press.
2799 if (mLocked.currentVirtualKey.down) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002800 if (mCurrentTouch.pointerCount == 0) {
2801 // Pointer went up while virtual key was down.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002802 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002803#if DEBUG_VIRTUAL_KEYS
2804 LOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002805 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002806#endif
2807 keyEventAction = AKEY_EVENT_ACTION_UP;
2808 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2809 touchResult = SKIP_TOUCH;
2810 goto DispatchVirtualKey;
2811 }
2812
2813 if (mCurrentTouch.pointerCount == 1) {
2814 int32_t x = mCurrentTouch.pointers[0].x;
2815 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002816 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
2817 if (virtualKey && virtualKey->keyCode == mLocked.currentVirtualKey.keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002818 // Pointer is still within the space of the virtual key.
2819 return SKIP_TOUCH;
2820 }
2821 }
2822
2823 // Pointer left virtual key area or another pointer also went down.
2824 // Send key cancellation and drop the stroke so subsequent motions will be
2825 // considered fresh downs. This is useful when the user swipes away from the
2826 // virtual key area into the main display surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002827 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002828#if DEBUG_VIRTUAL_KEYS
2829 LOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002830 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002831#endif
2832 keyEventAction = AKEY_EVENT_ACTION_UP;
2833 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
2834 | AKEY_EVENT_FLAG_CANCELED;
Jeff Brownc3db8582010-10-20 15:33:38 -07002835
2836 // Check whether the pointer moved inside the display area where we should
2837 // start a new stroke.
2838 int32_t x = mCurrentTouch.pointers[0].x;
2839 int32_t y = mCurrentTouch.pointers[0].y;
2840 if (isPointInsideSurfaceLocked(x, y)) {
2841 mLastTouch.clear();
2842 touchResult = DISPATCH_TOUCH;
2843 } else {
2844 touchResult = DROP_STROKE;
2845 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002846 } else {
2847 if (mCurrentTouch.pointerCount >= 1 && mLastTouch.pointerCount == 0) {
2848 // Pointer just went down. Handle off-screen touches, if needed.
2849 int32_t x = mCurrentTouch.pointers[0].x;
2850 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002851 if (! isPointInsideSurfaceLocked(x, y)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002852 // If exactly one pointer went down, check for virtual key hit.
2853 // Otherwise we will drop the entire stroke.
2854 if (mCurrentTouch.pointerCount == 1) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002855 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002856 if (virtualKey) {
Jeff Brownfe508922011-01-18 15:10:10 -08002857 if (mContext->shouldDropVirtualKey(when, getDevice(),
2858 virtualKey->keyCode, virtualKey->scanCode)) {
2859 return DROP_STROKE;
2860 }
2861
Jeff Brown6328cdc2010-07-29 18:18:33 -07002862 mLocked.currentVirtualKey.down = true;
2863 mLocked.currentVirtualKey.downTime = when;
2864 mLocked.currentVirtualKey.keyCode = virtualKey->keyCode;
2865 mLocked.currentVirtualKey.scanCode = virtualKey->scanCode;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002866#if DEBUG_VIRTUAL_KEYS
2867 LOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002868 mLocked.currentVirtualKey.keyCode,
2869 mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002870#endif
2871 keyEventAction = AKEY_EVENT_ACTION_DOWN;
2872 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM
2873 | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2874 touchResult = SKIP_TOUCH;
2875 goto DispatchVirtualKey;
2876 }
2877 }
2878 return DROP_STROKE;
2879 }
2880 }
2881 return DISPATCH_TOUCH;
2882 }
2883
2884 DispatchVirtualKey:
2885 // Collect remaining state needed to dispatch virtual key.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002886 keyCode = mLocked.currentVirtualKey.keyCode;
2887 scanCode = mLocked.currentVirtualKey.scanCode;
2888 downTime = mLocked.currentVirtualKey.downTime;
2889 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002890
2891 // Dispatch virtual key.
2892 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown0eaf3932010-10-01 14:55:30 -07002893 policyFlags |= POLICY_FLAG_VIRTUAL;
Jeff Brownb6997262010-10-08 22:31:17 -07002894 getDispatcher()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
2895 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
2896 return touchResult;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002897}
2898
Jeff Brownefd32662011-03-08 15:13:06 -08002899void TouchInputMapper::suppressSwipeOntoVirtualKeys(nsecs_t when) {
Jeff Brownfe508922011-01-18 15:10:10 -08002900 // Disable all virtual key touches that happen within a short time interval of the
2901 // most recent touch. The idea is to filter out stray virtual key presses when
2902 // interacting with the touch screen.
2903 //
2904 // Problems we're trying to solve:
2905 //
2906 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
2907 // virtual key area that is implemented by a separate touch panel and accidentally
2908 // triggers a virtual key.
2909 //
2910 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
2911 // area and accidentally triggers a virtual key. This often happens when virtual keys
2912 // are layed out below the screen near to where the on screen keyboard's space bar
2913 // is displayed.
2914 if (mParameters.virtualKeyQuietTime > 0 && mCurrentTouch.pointerCount != 0) {
2915 mContext->disableVirtualKeysUntil(when + mParameters.virtualKeyQuietTime);
2916 }
2917}
2918
Jeff Brown6d0fec22010-07-23 21:28:06 -07002919void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
2920 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
2921 uint32_t lastPointerCount = mLastTouch.pointerCount;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002922 if (currentPointerCount == 0 && lastPointerCount == 0) {
2923 return; // nothing to do!
2924 }
2925
Jeff Brownace13b12011-03-09 17:39:48 -08002926 // Update current touch coordinates.
2927 int32_t edgeFlags;
2928 float xPrecision, yPrecision;
2929 prepareTouches(&edgeFlags, &xPrecision, &yPrecision);
2930
2931 // Dispatch motions.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002932 BitSet32 currentIdBits = mCurrentTouch.idBits;
2933 BitSet32 lastIdBits = mLastTouch.idBits;
Jeff Brownace13b12011-03-09 17:39:48 -08002934 uint32_t metaState = getContext()->getGlobalMetaState();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002935
2936 if (currentIdBits == lastIdBits) {
2937 // No pointer id changes so this is a move event.
2938 // The dispatcher takes care of batching moves so we don't have to deal with that here.
Jeff Brownace13b12011-03-09 17:39:48 -08002939 dispatchMotion(when, policyFlags, mTouchSource,
2940 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
2941 mCurrentTouchCoords, mCurrentTouch.idToIndex, currentIdBits, -1,
2942 xPrecision, yPrecision, mDownTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002943 } else {
Jeff Brownc3db8582010-10-20 15:33:38 -07002944 // There may be pointers going up and pointers going down and pointers moving
2945 // all at the same time.
Jeff Brownace13b12011-03-09 17:39:48 -08002946 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2947 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002948 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
Jeff Brownace13b12011-03-09 17:39:48 -08002949 BitSet32 dispatchedIdBits(lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002950
Jeff Brownace13b12011-03-09 17:39:48 -08002951 // Update last coordinates of pointers that have moved so that we observe the new
2952 // pointer positions at the same time as other pointers that have just gone up.
2953 bool moveNeeded = updateMovedPointerCoords(
2954 mCurrentTouchCoords, mCurrentTouch.idToIndex,
2955 mLastTouchCoords, mLastTouch.idToIndex,
2956 moveIdBits);
Jeff Brownc3db8582010-10-20 15:33:38 -07002957
Jeff Brownace13b12011-03-09 17:39:48 -08002958 // Dispatch pointer up events.
Jeff Brownc3db8582010-10-20 15:33:38 -07002959 while (!upIdBits.isEmpty()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002960 uint32_t upId = upIdBits.firstMarkedBit();
2961 upIdBits.clearBit(upId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002962
Jeff Brownace13b12011-03-09 17:39:48 -08002963 dispatchMotion(when, policyFlags, mTouchSource,
2964 AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, 0,
2965 mLastTouchCoords, mLastTouch.idToIndex, dispatchedIdBits, upId,
2966 xPrecision, yPrecision, mDownTime);
2967 dispatchedIdBits.clearBit(upId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002968 }
2969
Jeff Brownc3db8582010-10-20 15:33:38 -07002970 // Dispatch move events if any of the remaining pointers moved from their old locations.
2971 // Although applications receive new locations as part of individual pointer up
2972 // events, they do not generally handle them except when presented in a move event.
2973 if (moveNeeded) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002974 LOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Jeff Brownace13b12011-03-09 17:39:48 -08002975 dispatchMotion(when, policyFlags, mTouchSource,
2976 AMOTION_EVENT_ACTION_MOVE, 0, metaState, 0,
2977 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, -1,
2978 xPrecision, yPrecision, mDownTime);
Jeff Brownc3db8582010-10-20 15:33:38 -07002979 }
2980
2981 // Dispatch pointer down events using the new pointer locations.
2982 while (!downIdBits.isEmpty()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002983 uint32_t downId = downIdBits.firstMarkedBit();
2984 downIdBits.clearBit(downId);
Jeff Brownace13b12011-03-09 17:39:48 -08002985 dispatchedIdBits.markBit(downId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002986
Jeff Brownace13b12011-03-09 17:39:48 -08002987 if (dispatchedIdBits.count() == 1) {
2988 // First pointer is going down. Set down time.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002989 mDownTime = when;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002990 } else {
Jeff Brownace13b12011-03-09 17:39:48 -08002991 // Only send edge flags with first pointer down.
2992 edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002993 }
2994
Jeff Brownace13b12011-03-09 17:39:48 -08002995 dispatchMotion(when, policyFlags, mTouchSource,
2996 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
2997 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, downId,
2998 xPrecision, yPrecision, mDownTime);
2999 }
3000 }
3001
3002 // Update state for next time.
3003 for (uint32_t i = 0; i < currentPointerCount; i++) {
3004 mLastTouchCoords[i].copyFrom(mCurrentTouchCoords[i]);
3005 }
3006}
3007
3008void TouchInputMapper::prepareTouches(int32_t* outEdgeFlags,
3009 float* outXPrecision, float* outYPrecision) {
3010 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
3011 uint32_t lastPointerCount = mLastTouch.pointerCount;
3012
3013 AutoMutex _l(mLock);
3014
3015 // Walk through the the active pointers and map touch screen coordinates (TouchData) into
3016 // display or surface coordinates (PointerCoords) and adjust for display orientation.
3017 for (uint32_t i = 0; i < currentPointerCount; i++) {
3018 const PointerData& in = mCurrentTouch.pointers[i];
3019
3020 // ToolMajor and ToolMinor
3021 float toolMajor, toolMinor;
3022 switch (mCalibration.toolSizeCalibration) {
3023 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
3024 toolMajor = in.toolMajor * mLocked.geometricScale;
3025 if (mRawAxes.toolMinor.valid) {
3026 toolMinor = in.toolMinor * mLocked.geometricScale;
3027 } else {
3028 toolMinor = toolMajor;
3029 }
3030 break;
3031 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
3032 toolMajor = in.toolMajor != 0
3033 ? in.toolMajor * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias
3034 : 0;
3035 if (mRawAxes.toolMinor.valid) {
3036 toolMinor = in.toolMinor != 0
3037 ? in.toolMinor * mLocked.toolSizeLinearScale
3038 + mLocked.toolSizeLinearBias
3039 : 0;
3040 } else {
3041 toolMinor = toolMajor;
3042 }
3043 break;
3044 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
3045 if (in.toolMajor != 0) {
3046 float diameter = sqrtf(in.toolMajor
3047 * mLocked.toolSizeAreaScale + mLocked.toolSizeAreaBias);
3048 toolMajor = diameter * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias;
3049 } else {
3050 toolMajor = 0;
3051 }
3052 toolMinor = toolMajor;
3053 break;
3054 default:
3055 toolMajor = 0;
3056 toolMinor = 0;
3057 break;
3058 }
3059
3060 if (mCalibration.haveToolSizeIsSummed && mCalibration.toolSizeIsSummed) {
3061 toolMajor /= currentPointerCount;
3062 toolMinor /= currentPointerCount;
3063 }
3064
3065 // Pressure
3066 float rawPressure;
3067 switch (mCalibration.pressureSource) {
3068 case Calibration::PRESSURE_SOURCE_PRESSURE:
3069 rawPressure = in.pressure;
3070 break;
3071 case Calibration::PRESSURE_SOURCE_TOUCH:
3072 rawPressure = in.touchMajor;
3073 break;
3074 default:
3075 rawPressure = 0;
3076 }
3077
3078 float pressure;
3079 switch (mCalibration.pressureCalibration) {
3080 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3081 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3082 pressure = rawPressure * mLocked.pressureScale;
3083 break;
3084 default:
3085 pressure = 1;
3086 break;
3087 }
3088
3089 // TouchMajor and TouchMinor
3090 float touchMajor, touchMinor;
3091 switch (mCalibration.touchSizeCalibration) {
3092 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
3093 touchMajor = in.touchMajor * mLocked.geometricScale;
3094 if (mRawAxes.touchMinor.valid) {
3095 touchMinor = in.touchMinor * mLocked.geometricScale;
3096 } else {
3097 touchMinor = touchMajor;
3098 }
3099 break;
3100 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
3101 touchMajor = toolMajor * pressure;
3102 touchMinor = toolMinor * pressure;
3103 break;
3104 default:
3105 touchMajor = 0;
3106 touchMinor = 0;
3107 break;
3108 }
3109
3110 if (touchMajor > toolMajor) {
3111 touchMajor = toolMajor;
3112 }
3113 if (touchMinor > toolMinor) {
3114 touchMinor = toolMinor;
3115 }
3116
3117 // Size
3118 float size;
3119 switch (mCalibration.sizeCalibration) {
3120 case Calibration::SIZE_CALIBRATION_NORMALIZED: {
3121 float rawSize = mRawAxes.toolMinor.valid
3122 ? avg(in.toolMajor, in.toolMinor)
3123 : in.toolMajor;
3124 size = rawSize * mLocked.sizeScale;
3125 break;
3126 }
3127 default:
3128 size = 0;
3129 break;
3130 }
3131
3132 // Orientation
3133 float orientation;
3134 switch (mCalibration.orientationCalibration) {
3135 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3136 orientation = in.orientation * mLocked.orientationScale;
3137 break;
3138 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
3139 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
3140 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
3141 if (c1 != 0 || c2 != 0) {
3142 orientation = atan2f(c1, c2) * 0.5f;
Jeff Brown2352b972011-04-12 22:39:53 -07003143 float scale = 1.0f + hypotf(c1, c2) / 16.0f;
Jeff Brownace13b12011-03-09 17:39:48 -08003144 touchMajor *= scale;
3145 touchMinor /= scale;
3146 toolMajor *= scale;
3147 toolMinor /= scale;
3148 } else {
3149 orientation = 0;
3150 }
3151 break;
3152 }
3153 default:
3154 orientation = 0;
3155 }
3156
3157 // X and Y
3158 // Adjust coords for surface orientation.
3159 float x, y;
3160 switch (mLocked.surfaceOrientation) {
3161 case DISPLAY_ORIENTATION_90:
3162 x = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3163 y = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3164 orientation -= M_PI_2;
3165 if (orientation < - M_PI_2) {
3166 orientation += M_PI;
3167 }
3168 break;
3169 case DISPLAY_ORIENTATION_180:
3170 x = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3171 y = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3172 break;
3173 case DISPLAY_ORIENTATION_270:
3174 x = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3175 y = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3176 orientation += M_PI_2;
3177 if (orientation > M_PI_2) {
3178 orientation -= M_PI;
3179 }
3180 break;
3181 default:
3182 x = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3183 y = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3184 break;
3185 }
3186
3187 // Write output coords.
3188 PointerCoords& out = mCurrentTouchCoords[i];
3189 out.clear();
3190 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3191 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3192 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
3193 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
3194 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
3195 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
3196 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
3197 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
3198 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
3199 }
3200
3201 // Check edge flags by looking only at the first pointer since the flags are
3202 // global to the event.
3203 *outEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3204 if (lastPointerCount == 0 && currentPointerCount > 0) {
3205 const PointerData& in = mCurrentTouch.pointers[0];
3206
3207 if (in.x <= mRawAxes.x.minValue) {
3208 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_LEFT,
3209 mLocked.surfaceOrientation);
3210 } else if (in.x >= mRawAxes.x.maxValue) {
3211 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_RIGHT,
3212 mLocked.surfaceOrientation);
3213 }
3214 if (in.y <= mRawAxes.y.minValue) {
3215 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_TOP,
3216 mLocked.surfaceOrientation);
3217 } else if (in.y >= mRawAxes.y.maxValue) {
3218 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_BOTTOM,
3219 mLocked.surfaceOrientation);
3220 }
3221 }
3222
3223 *outXPrecision = mLocked.orientedXPrecision;
3224 *outYPrecision = mLocked.orientedYPrecision;
3225}
3226
3227void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags) {
Jeff Brown2352b972011-04-12 22:39:53 -07003228 // Switch pointer presentation.
3229 mPointerController->setPresentation(
3230 mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
3231 ? PointerControllerInterface::PRESENTATION_SPOT
3232 : PointerControllerInterface::PRESENTATION_POINTER);
3233
Jeff Brownace13b12011-03-09 17:39:48 -08003234 // Update current gesture coordinates.
3235 bool cancelPreviousGesture, finishPreviousGesture;
3236 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture);
3237
Jeff Brown2352b972011-04-12 22:39:53 -07003238 // Show the pointer if needed.
3239 if (mPointerGesture.currentGestureMode != PointerGesture::NEUTRAL
3240 && mPointerGesture.currentGestureMode != PointerGesture::QUIET) {
3241 mPointerController->unfade();
3242 }
3243
Jeff Brownace13b12011-03-09 17:39:48 -08003244 // Send events!
3245 uint32_t metaState = getContext()->getGlobalMetaState();
3246
3247 // Update last coordinates of pointers that have moved so that we observe the new
3248 // pointer positions at the same time as other pointers that have just gone up.
3249 bool down = mPointerGesture.currentGestureMode == PointerGesture::CLICK_OR_DRAG
Jeff Brown2352b972011-04-12 22:39:53 -07003250 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
Jeff Brownace13b12011-03-09 17:39:48 -08003251 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
3252 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
3253 bool moveNeeded = false;
3254 if (down && !cancelPreviousGesture && !finishPreviousGesture
Jeff Brown2352b972011-04-12 22:39:53 -07003255 && !mPointerGesture.lastGestureIdBits.isEmpty()
3256 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
Jeff Brownace13b12011-03-09 17:39:48 -08003257 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
3258 & mPointerGesture.lastGestureIdBits.value);
3259 moveNeeded = updateMovedPointerCoords(
3260 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3261 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3262 movedGestureIdBits);
3263 }
3264
3265 // Send motion events for all pointers that went up or were canceled.
3266 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
3267 if (!dispatchedGestureIdBits.isEmpty()) {
3268 if (cancelPreviousGesture) {
3269 dispatchMotion(when, policyFlags, mPointerSource,
3270 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3271 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3272 dispatchedGestureIdBits, -1,
3273 0, 0, mPointerGesture.downTime);
3274
3275 dispatchedGestureIdBits.clear();
3276 } else {
3277 BitSet32 upGestureIdBits;
3278 if (finishPreviousGesture) {
3279 upGestureIdBits = dispatchedGestureIdBits;
3280 } else {
3281 upGestureIdBits.value = dispatchedGestureIdBits.value
3282 & ~mPointerGesture.currentGestureIdBits.value;
3283 }
3284 while (!upGestureIdBits.isEmpty()) {
3285 uint32_t id = upGestureIdBits.firstMarkedBit();
3286 upGestureIdBits.clearBit(id);
3287
3288 dispatchMotion(when, policyFlags, mPointerSource,
3289 AMOTION_EVENT_ACTION_POINTER_UP, 0,
3290 metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3291 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3292 dispatchedGestureIdBits, id,
3293 0, 0, mPointerGesture.downTime);
3294
3295 dispatchedGestureIdBits.clearBit(id);
3296 }
3297 }
3298 }
3299
3300 // Send motion events for all pointers that moved.
3301 if (moveNeeded) {
3302 dispatchMotion(when, policyFlags, mPointerSource,
3303 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3304 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3305 dispatchedGestureIdBits, -1,
3306 0, 0, mPointerGesture.downTime);
3307 }
3308
3309 // Send motion events for all pointers that went down.
3310 if (down) {
3311 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
3312 & ~dispatchedGestureIdBits.value);
3313 while (!downGestureIdBits.isEmpty()) {
3314 uint32_t id = downGestureIdBits.firstMarkedBit();
3315 downGestureIdBits.clearBit(id);
3316 dispatchedGestureIdBits.markBit(id);
3317
3318 int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3319 if (dispatchedGestureIdBits.count() == 1) {
3320 // First pointer is going down. Calculate edge flags and set down time.
3321 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3322 const PointerCoords& downCoords = mPointerGesture.currentGestureCoords[index];
3323 edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3324 downCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
3325 downCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3326 mPointerGesture.downTime = when;
3327 }
3328
3329 dispatchMotion(when, policyFlags, mPointerSource,
3330 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
3331 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3332 dispatchedGestureIdBits, id,
3333 0, 0, mPointerGesture.downTime);
3334 }
3335 }
3336
3337 // Send down and up for a tap.
3338 if (mPointerGesture.currentGestureMode == PointerGesture::TAP) {
3339 const PointerCoords& coords = mPointerGesture.currentGestureCoords[0];
3340 int32_t edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3341 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3342 coords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3343 nsecs_t downTime = mPointerGesture.downTime = mPointerGesture.tapTime;
3344 mPointerGesture.resetTapTime();
3345
3346 dispatchMotion(downTime, policyFlags, mPointerSource,
3347 AMOTION_EVENT_ACTION_DOWN, 0, metaState, edgeFlags,
3348 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3349 mPointerGesture.currentGestureIdBits, -1,
3350 0, 0, downTime);
3351 dispatchMotion(when, policyFlags, mPointerSource,
3352 AMOTION_EVENT_ACTION_UP, 0, metaState, edgeFlags,
3353 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3354 mPointerGesture.currentGestureIdBits, -1,
3355 0, 0, downTime);
3356 }
3357
3358 // Send motion events for hover.
3359 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
3360 dispatchMotion(when, policyFlags, mPointerSource,
3361 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3362 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3363 mPointerGesture.currentGestureIdBits, -1,
3364 0, 0, mPointerGesture.downTime);
3365 }
3366
3367 // Update state.
3368 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
3369 if (!down) {
Jeff Brownace13b12011-03-09 17:39:48 -08003370 mPointerGesture.lastGestureIdBits.clear();
3371 } else {
Jeff Brownace13b12011-03-09 17:39:48 -08003372 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
3373 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
3374 uint32_t id = idBits.firstMarkedBit();
3375 idBits.clearBit(id);
3376 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3377 mPointerGesture.lastGestureCoords[index].copyFrom(
3378 mPointerGesture.currentGestureCoords[index]);
3379 mPointerGesture.lastGestureIdToIndex[id] = index;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003380 }
3381 }
3382}
3383
Jeff Brownace13b12011-03-09 17:39:48 -08003384void TouchInputMapper::preparePointerGestures(nsecs_t when,
3385 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture) {
3386 *outCancelPreviousGesture = false;
3387 *outFinishPreviousGesture = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003388
Jeff Brownace13b12011-03-09 17:39:48 -08003389 AutoMutex _l(mLock);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003390
Jeff Brownace13b12011-03-09 17:39:48 -08003391 // Update the velocity tracker.
3392 {
3393 VelocityTracker::Position positions[MAX_POINTERS];
3394 uint32_t count = 0;
3395 for (BitSet32 idBits(mCurrentTouch.idBits); !idBits.isEmpty(); count++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07003396 uint32_t id = idBits.firstMarkedBit();
3397 idBits.clearBit(id);
Jeff Brownace13b12011-03-09 17:39:48 -08003398 uint32_t index = mCurrentTouch.idToIndex[id];
3399 positions[count].x = mCurrentTouch.pointers[index].x
3400 * mLocked.pointerGestureXMovementScale;
3401 positions[count].y = mCurrentTouch.pointers[index].y
3402 * mLocked.pointerGestureYMovementScale;
3403 }
3404 mPointerGesture.velocityTracker.addMovement(when, mCurrentTouch.idBits, positions);
3405 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003406
Jeff Brownace13b12011-03-09 17:39:48 -08003407 // Pick a new active touch id if needed.
3408 // Choose an arbitrary pointer that just went down, if there is one.
3409 // Otherwise choose an arbitrary remaining pointer.
3410 // This guarantees we always have an active touch id when there is at least one pointer.
Jeff Brown2352b972011-04-12 22:39:53 -07003411 // We keep the same active touch id for as long as possible.
3412 bool activeTouchChanged = false;
3413 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
3414 int32_t activeTouchId = lastActiveTouchId;
3415 if (activeTouchId < 0) {
3416 if (!mCurrentTouch.idBits.isEmpty()) {
3417 activeTouchChanged = true;
3418 activeTouchId = mPointerGesture.activeTouchId = mCurrentTouch.idBits.firstMarkedBit();
3419 mPointerGesture.firstTouchTime = when;
Jeff Brownace13b12011-03-09 17:39:48 -08003420 }
Jeff Brown2352b972011-04-12 22:39:53 -07003421 } else if (!mCurrentTouch.idBits.hasBit(activeTouchId)) {
3422 activeTouchChanged = true;
3423 if (!mCurrentTouch.idBits.isEmpty()) {
3424 activeTouchId = mPointerGesture.activeTouchId = mCurrentTouch.idBits.firstMarkedBit();
3425 } else {
3426 activeTouchId = mPointerGesture.activeTouchId = -1;
Jeff Brownace13b12011-03-09 17:39:48 -08003427 }
3428 }
3429
3430 // Determine whether we are in quiet time.
Jeff Brown2352b972011-04-12 22:39:53 -07003431 bool isQuietTime = false;
3432 if (activeTouchId < 0) {
3433 mPointerGesture.resetQuietTime();
3434 } else {
3435 isQuietTime = when < mPointerGesture.quietTime + QUIET_INTERVAL;
3436 if (!isQuietTime) {
3437 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
3438 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
3439 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
3440 && mCurrentTouch.pointerCount < 2) {
3441 // Enter quiet time when exiting swipe or freeform state.
3442 // This is to prevent accidentally entering the hover state and flinging the
3443 // pointer when finishing a swipe and there is still one pointer left onscreen.
3444 isQuietTime = true;
3445 } else if (mPointerGesture.lastGestureMode == PointerGesture::CLICK_OR_DRAG
3446 && mCurrentTouch.pointerCount >= 2
3447 && !isPointerDown(mCurrentTouch.buttonState)) {
3448 // Enter quiet time when releasing the button and there are still two or more
3449 // fingers down. This may indicate that one finger was used to press the button
3450 // but it has not gone up yet.
3451 isQuietTime = true;
3452 }
3453 if (isQuietTime) {
3454 mPointerGesture.quietTime = when;
3455 }
Jeff Brownace13b12011-03-09 17:39:48 -08003456 }
3457 }
3458
3459 // Switch states based on button and pointer state.
3460 if (isQuietTime) {
3461 // Case 1: Quiet time. (QUIET)
3462#if DEBUG_GESTURES
3463 LOGD("Gestures: QUIET for next %0.3fms",
3464 (mPointerGesture.quietTime + QUIET_INTERVAL - when) * 0.000001f);
3465#endif
3466 *outFinishPreviousGesture = true;
3467
3468 mPointerGesture.activeGestureId = -1;
3469 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
Jeff Brownace13b12011-03-09 17:39:48 -08003470 mPointerGesture.currentGestureIdBits.clear();
Jeff Brown2352b972011-04-12 22:39:53 -07003471
3472 mPointerController->setButtonState(0);
3473
3474 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3475 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_NEUTRAL;
3476 mPointerGesture.spotIdBits.clear();
3477 moveSpotsLocked();
3478 }
Jeff Brownace13b12011-03-09 17:39:48 -08003479 } else if (isPointerDown(mCurrentTouch.buttonState)) {
Jeff Brown2352b972011-04-12 22:39:53 -07003480 // Case 2: Button is pressed. (CLICK_OR_DRAG)
Jeff Brownace13b12011-03-09 17:39:48 -08003481 // The pointer follows the active touch point.
3482 // Emit DOWN, MOVE, UP events at the pointer location.
3483 //
3484 // Only the active touch matters; other fingers are ignored. This policy helps
3485 // to handle the case where the user places a second finger on the touch pad
3486 // to apply the necessary force to depress an integrated button below the surface.
3487 // We don't want the second finger to be delivered to applications.
3488 //
3489 // For this to work well, we need to make sure to track the pointer that is really
3490 // active. If the user first puts one finger down to click then adds another
3491 // finger to drag then the active pointer should switch to the finger that is
3492 // being dragged.
3493#if DEBUG_GESTURES
3494 LOGD("Gestures: CLICK_OR_DRAG activeTouchId=%d, "
3495 "currentTouchPointerCount=%d", activeTouchId, mCurrentTouch.pointerCount);
3496#endif
3497 // Reset state when just starting.
3498 if (mPointerGesture.lastGestureMode != PointerGesture::CLICK_OR_DRAG) {
3499 *outFinishPreviousGesture = true;
3500 mPointerGesture.activeGestureId = 0;
3501 }
3502
3503 // Switch pointers if needed.
3504 // Find the fastest pointer and follow it.
3505 if (activeTouchId >= 0) {
3506 if (mCurrentTouch.pointerCount > 1) {
3507 int32_t bestId = -1;
3508 float bestSpeed = DRAG_MIN_SWITCH_SPEED;
3509 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3510 uint32_t id = mCurrentTouch.pointers[i].id;
3511 float vx, vy;
3512 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
Jeff Brown2352b972011-04-12 22:39:53 -07003513 float speed = hypotf(vx, vy);
Jeff Brownace13b12011-03-09 17:39:48 -08003514 if (speed > bestSpeed) {
3515 bestId = id;
3516 bestSpeed = speed;
3517 }
3518 }
Jeff Brown8d608662010-08-30 03:02:23 -07003519 }
Jeff Brownace13b12011-03-09 17:39:48 -08003520 if (bestId >= 0 && bestId != activeTouchId) {
3521 mPointerGesture.activeTouchId = activeTouchId = bestId;
Jeff Brown2352b972011-04-12 22:39:53 -07003522 activeTouchChanged = true;
Jeff Brownace13b12011-03-09 17:39:48 -08003523#if DEBUG_GESTURES
3524 LOGD("Gestures: CLICK_OR_DRAG switched pointers, "
3525 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
3526#endif
Jeff Brown8d608662010-08-30 03:02:23 -07003527 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003528 }
3529
Jeff Brownace13b12011-03-09 17:39:48 -08003530 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3531 const PointerData& currentPointer =
3532 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3533 const PointerData& lastPointer =
3534 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3535 float deltaX = (currentPointer.x - lastPointer.x)
3536 * mLocked.pointerGestureXMovementScale;
3537 float deltaY = (currentPointer.y - lastPointer.y)
3538 * mLocked.pointerGestureYMovementScale;
Jeff Brown2352b972011-04-12 22:39:53 -07003539
3540 // Move the pointer using a relative motion.
3541 // When using spots, the click will occur at the position of the anchor
3542 // spot and all other spots will move there.
Jeff Brownace13b12011-03-09 17:39:48 -08003543 mPointerController->move(deltaX, deltaY);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003544 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003545 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003546
Jeff Brownace13b12011-03-09 17:39:48 -08003547 float x, y;
3548 mPointerController->getPosition(&x, &y);
Jeff Brown91c69ab2011-02-14 17:03:18 -08003549
Jeff Brownace13b12011-03-09 17:39:48 -08003550 mPointerGesture.currentGestureMode = PointerGesture::CLICK_OR_DRAG;
Jeff Brownace13b12011-03-09 17:39:48 -08003551 mPointerGesture.currentGestureIdBits.clear();
3552 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3553 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3554 mPointerGesture.currentGestureCoords[0].clear();
3555 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3556 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3557 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown2352b972011-04-12 22:39:53 -07003558
3559 mPointerController->setButtonState(BUTTON_STATE_PRIMARY);
3560
3561 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3562 if (activeTouchId >= 0) {
3563 // Collapse all spots into one point at the pointer location.
3564 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_BUTTON_DRAG;
3565 mPointerGesture.spotIdBits.clear();
3566 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3567 uint32_t id = mCurrentTouch.pointers[i].id;
3568 mPointerGesture.spotIdBits.markBit(id);
3569 mPointerGesture.spotIdToIndex[id] = i;
3570 mPointerGesture.spotCoords[i] = mPointerGesture.currentGestureCoords[0];
3571 }
3572 } else {
3573 // No fingers. Generate a spot at the pointer location so the
3574 // anchor appears to be pressed.
3575 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_BUTTON_CLICK;
3576 mPointerGesture.spotIdBits.clear();
3577 mPointerGesture.spotIdBits.markBit(0);
3578 mPointerGesture.spotIdToIndex[0] = 0;
3579 mPointerGesture.spotCoords[0] = mPointerGesture.currentGestureCoords[0];
3580 }
3581 moveSpotsLocked();
3582 }
Jeff Brownace13b12011-03-09 17:39:48 -08003583 } else if (mCurrentTouch.pointerCount == 0) {
3584 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
3585 *outFinishPreviousGesture = true;
3586
Jeff Brown2352b972011-04-12 22:39:53 -07003587 // Watch for taps coming out of HOVER mode.
Jeff Brownace13b12011-03-09 17:39:48 -08003588 bool tapped = false;
3589 if (mPointerGesture.lastGestureMode == PointerGesture::HOVER
Jeff Brown2352b972011-04-12 22:39:53 -07003590 && mLastTouch.pointerCount == 1) {
Jeff Brownace13b12011-03-09 17:39:48 -08003591 if (when <= mPointerGesture.tapTime + TAP_INTERVAL) {
3592 float x, y;
3593 mPointerController->getPosition(&x, &y);
Jeff Brown2352b972011-04-12 22:39:53 -07003594 if (fabs(x - mPointerGesture.tapX) <= TAP_SLOP
3595 && fabs(y - mPointerGesture.tapY) <= TAP_SLOP) {
Jeff Brownace13b12011-03-09 17:39:48 -08003596#if DEBUG_GESTURES
3597 LOGD("Gestures: TAP");
3598#endif
3599 mPointerGesture.activeGestureId = 0;
3600 mPointerGesture.currentGestureMode = PointerGesture::TAP;
Jeff Brownace13b12011-03-09 17:39:48 -08003601 mPointerGesture.currentGestureIdBits.clear();
3602 mPointerGesture.currentGestureIdBits.markBit(
3603 mPointerGesture.activeGestureId);
3604 mPointerGesture.currentGestureIdToIndex[
3605 mPointerGesture.activeGestureId] = 0;
3606 mPointerGesture.currentGestureCoords[0].clear();
3607 mPointerGesture.currentGestureCoords[0].setAxisValue(
Jeff Brown2352b972011-04-12 22:39:53 -07003608 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
Jeff Brownace13b12011-03-09 17:39:48 -08003609 mPointerGesture.currentGestureCoords[0].setAxisValue(
Jeff Brown2352b972011-04-12 22:39:53 -07003610 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
Jeff Brownace13b12011-03-09 17:39:48 -08003611 mPointerGesture.currentGestureCoords[0].setAxisValue(
3612 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown2352b972011-04-12 22:39:53 -07003613
3614 mPointerController->setButtonState(BUTTON_STATE_PRIMARY);
3615 mPointerController->setButtonState(0);
3616
3617 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3618 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_TAP;
3619 mPointerGesture.spotIdBits.clear();
3620 mPointerGesture.spotIdBits.markBit(lastActiveTouchId);
3621 mPointerGesture.spotIdToIndex[lastActiveTouchId] = 0;
3622 mPointerGesture.spotCoords[0] = mPointerGesture.currentGestureCoords[0];
3623 moveSpotsLocked();
3624 }
3625
Jeff Brownace13b12011-03-09 17:39:48 -08003626 tapped = true;
3627 } else {
3628#if DEBUG_GESTURES
3629 LOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
Jeff Brown2352b972011-04-12 22:39:53 -07003630 x - mPointerGesture.tapX,
3631 y - mPointerGesture.tapY);
Jeff Brownace13b12011-03-09 17:39:48 -08003632#endif
3633 }
3634 } else {
3635#if DEBUG_GESTURES
3636 LOGD("Gestures: Not a TAP, delay=%lld",
3637 when - mPointerGesture.tapTime);
3638#endif
Jeff Brown6328cdc2010-07-29 18:18:33 -07003639 }
Jeff Brownace13b12011-03-09 17:39:48 -08003640 }
Jeff Brown2352b972011-04-12 22:39:53 -07003641
Jeff Brownace13b12011-03-09 17:39:48 -08003642 if (!tapped) {
3643#if DEBUG_GESTURES
3644 LOGD("Gestures: NEUTRAL");
3645#endif
3646 mPointerGesture.activeGestureId = -1;
3647 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
Jeff Brownace13b12011-03-09 17:39:48 -08003648 mPointerGesture.currentGestureIdBits.clear();
Jeff Brown2352b972011-04-12 22:39:53 -07003649
3650 mPointerController->setButtonState(0);
3651
3652 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3653 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_NEUTRAL;
3654 mPointerGesture.spotIdBits.clear();
3655 moveSpotsLocked();
3656 }
Jeff Brownace13b12011-03-09 17:39:48 -08003657 }
3658 } else if (mCurrentTouch.pointerCount == 1) {
3659 // Case 4. Exactly one finger down, button is not pressed. (HOVER)
3660 // The pointer follows the active touch point.
3661 // Emit HOVER_MOVE events at the pointer location.
Jeff Brownb6110c22011-04-01 16:15:13 -07003662 LOG_ASSERT(activeTouchId >= 0);
Jeff Brownace13b12011-03-09 17:39:48 -08003663
3664#if DEBUG_GESTURES
3665 LOGD("Gestures: HOVER");
3666#endif
3667
3668 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3669 const PointerData& currentPointer =
3670 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3671 const PointerData& lastPointer =
3672 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3673 float deltaX = (currentPointer.x - lastPointer.x)
3674 * mLocked.pointerGestureXMovementScale;
3675 float deltaY = (currentPointer.y - lastPointer.y)
3676 * mLocked.pointerGestureYMovementScale;
Jeff Brown2352b972011-04-12 22:39:53 -07003677
3678 // Move the pointer using a relative motion.
3679 // When using spots, the hover will occur at the position of the anchor spot.
Jeff Brownace13b12011-03-09 17:39:48 -08003680 mPointerController->move(deltaX, deltaY);
3681 }
3682
3683 *outFinishPreviousGesture = true;
3684 mPointerGesture.activeGestureId = 0;
3685
3686 float x, y;
3687 mPointerController->getPosition(&x, &y);
3688
3689 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
Jeff Brownace13b12011-03-09 17:39:48 -08003690 mPointerGesture.currentGestureIdBits.clear();
3691 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3692 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3693 mPointerGesture.currentGestureCoords[0].clear();
3694 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3695 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3696 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 0.0f);
3697
3698 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
3699 mPointerGesture.tapTime = when;
Jeff Brown2352b972011-04-12 22:39:53 -07003700 mPointerGesture.tapX = x;
3701 mPointerGesture.tapY = y;
3702 }
3703
3704 mPointerController->setButtonState(0);
3705
3706 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3707 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_HOVER;
3708 mPointerGesture.spotIdBits.clear();
3709 mPointerGesture.spotIdBits.markBit(activeTouchId);
3710 mPointerGesture.spotIdToIndex[activeTouchId] = 0;
3711 mPointerGesture.spotCoords[0] = mPointerGesture.currentGestureCoords[0];
3712 moveSpotsLocked();
Jeff Brownace13b12011-03-09 17:39:48 -08003713 }
3714 } else {
Jeff Brown2352b972011-04-12 22:39:53 -07003715 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3716 // We need to provide feedback for each finger that goes down so we cannot wait
3717 // for the fingers to move before deciding what to do.
Jeff Brownace13b12011-03-09 17:39:48 -08003718 //
Jeff Brown2352b972011-04-12 22:39:53 -07003719 // The ambiguous case is deciding what to do when there are two fingers down but they
3720 // have not moved enough to determine whether they are part of a drag or part of a
3721 // freeform gesture, or just a press or long-press at the pointer location.
3722 //
3723 // When there are two fingers we start with the PRESS hypothesis and we generate a
3724 // down at the pointer location.
3725 //
3726 // When the two fingers move enough or when additional fingers are added, we make
3727 // a decision to transition into SWIPE or FREEFORM mode accordingly.
Jeff Brownb6110c22011-04-01 16:15:13 -07003728 LOG_ASSERT(activeTouchId >= 0);
Jeff Brownace13b12011-03-09 17:39:48 -08003729
Jeff Brown2352b972011-04-12 22:39:53 -07003730 bool needReference = false;
3731 bool settled = when >= mPointerGesture.firstTouchTime + MULTITOUCH_SETTLE_INTERVAL;
3732 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
Jeff Brownace13b12011-03-09 17:39:48 -08003733 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
3734 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
Jeff Brownace13b12011-03-09 17:39:48 -08003735 *outFinishPreviousGesture = true;
Jeff Brown2352b972011-04-12 22:39:53 -07003736 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
3737 mPointerGesture.activeGestureId = 0;
Jeff Brownace13b12011-03-09 17:39:48 -08003738
Jeff Brown2352b972011-04-12 22:39:53 -07003739 if (settled && mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
3740 && mLastTouch.idBits.hasBit(mPointerGesture.activeTouchId)) {
3741 // The spot is already visible and has settled, use it as the reference point
3742 // for the gesture. Other spots will be positioned relative to this one.
3743#if DEBUG_GESTURES
3744 LOGD("Gestures: Using active spot as reference for MULTITOUCH, "
3745 "settle time expired %0.3fms ago",
3746 (when - mPointerGesture.firstTouchTime - MULTITOUCH_SETTLE_INTERVAL)
3747 * 0.000001f);
3748#endif
3749 const PointerData& d = mLastTouch.pointers[mLastTouch.idToIndex[
3750 mPointerGesture.activeTouchId]];
3751 mPointerGesture.referenceTouchX = d.x;
3752 mPointerGesture.referenceTouchY = d.y;
3753 const PointerCoords& c = mPointerGesture.spotCoords[mPointerGesture.spotIdToIndex[
3754 mPointerGesture.activeTouchId]];
3755 mPointerGesture.referenceGestureX = c.getAxisValue(AMOTION_EVENT_AXIS_X);
3756 mPointerGesture.referenceGestureY = c.getAxisValue(AMOTION_EVENT_AXIS_Y);
3757 } else {
3758#if DEBUG_GESTURES
3759 LOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3760 "settle time remaining %0.3fms",
3761 (mPointerGesture.firstTouchTime + MULTITOUCH_SETTLE_INTERVAL - when)
3762 * 0.000001f);
3763#endif
3764 needReference = true;
Jeff Brownace13b12011-03-09 17:39:48 -08003765 }
Jeff Brown2352b972011-04-12 22:39:53 -07003766 } else if (!settled && mCurrentTouch.pointerCount > mLastTouch.pointerCount) {
3767 // Additional pointers have gone down but not yet settled.
3768 // Reset the gesture.
3769#if DEBUG_GESTURES
3770 LOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3771 "settle time remaining %0.3fms",
3772 (mPointerGesture.firstTouchTime + MULTITOUCH_SETTLE_INTERVAL - when)
3773 * 0.000001f);
3774#endif
3775 *outCancelPreviousGesture = true;
3776 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
3777 mPointerGesture.activeGestureId = 0;
Jeff Brownace13b12011-03-09 17:39:48 -08003778 } else {
Jeff Brown2352b972011-04-12 22:39:53 -07003779 // Continue previous gesture.
Jeff Brownace13b12011-03-09 17:39:48 -08003780 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3781 }
3782
Jeff Brown2352b972011-04-12 22:39:53 -07003783 if (needReference) {
3784 // Use the centroid and pointer location as the reference points for the gesture.
3785 mCurrentTouch.getCentroid(&mPointerGesture.referenceTouchX,
3786 &mPointerGesture.referenceTouchY);
3787 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3788 &mPointerGesture.referenceGestureY);
3789 }
Jeff Brownace13b12011-03-09 17:39:48 -08003790
Jeff Brown2352b972011-04-12 22:39:53 -07003791 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
3792 float d;
3793 if (mCurrentTouch.pointerCount > 2) {
3794 // There are more than two pointers, switch to FREEFORM.
3795#if DEBUG_GESTURES
3796 LOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3797 mCurrentTouch.pointerCount);
3798#endif
3799 *outCancelPreviousGesture = true;
Jeff Brownace13b12011-03-09 17:39:48 -08003800 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown2352b972011-04-12 22:39:53 -07003801 } else if (((d = distance(
3802 mCurrentTouch.pointers[0].x, mCurrentTouch.pointers[0].y,
3803 mCurrentTouch.pointers[1].x, mCurrentTouch.pointers[1].y))
3804 > mLocked.pointerGestureMaxSwipeWidth)) {
3805 // There are two pointers but they are too far apart, switch to FREEFORM.
3806#if DEBUG_GESTURES
3807 LOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3808 d, mLocked.pointerGestureMaxSwipeWidth);
3809#endif
3810 *outCancelPreviousGesture = true;
3811 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
3812 } else {
3813 // There are two pointers. Wait for both pointers to start moving
3814 // before deciding whether this is a SWIPE or FREEFORM gesture.
3815 uint32_t id1 = mCurrentTouch.pointers[0].id;
3816 uint32_t id2 = mCurrentTouch.pointers[1].id;
Jeff Brownace13b12011-03-09 17:39:48 -08003817
Jeff Brown2352b972011-04-12 22:39:53 -07003818 float vx1, vy1, vx2, vy2;
3819 mPointerGesture.velocityTracker.getVelocity(id1, &vx1, &vy1);
3820 mPointerGesture.velocityTracker.getVelocity(id2, &vx2, &vy2);
Jeff Brownace13b12011-03-09 17:39:48 -08003821
Jeff Brown2352b972011-04-12 22:39:53 -07003822 float speed1 = hypotf(vx1, vy1);
3823 float speed2 = hypotf(vx2, vy2);
3824 if (speed1 >= MULTITOUCH_MIN_SPEED && speed2 >= MULTITOUCH_MIN_SPEED) {
3825 // Calculate the dot product of the velocity vectors.
Jeff Brownace13b12011-03-09 17:39:48 -08003826 // When the vectors are oriented in approximately the same direction,
3827 // the angle betweeen them is near zero and the cosine of the angle
3828 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
Jeff Brown2352b972011-04-12 22:39:53 -07003829 float dot = vx1 * vx2 + vy1 * vy2;
3830 float cosine = dot / (speed1 * speed2); // denominator always > 0
3831 if (cosine >= SWIPE_TRANSITION_ANGLE_COSINE) {
3832 // Pointers are moving in the same direction. Switch to SWIPE.
3833#if DEBUG_GESTURES
3834 LOGD("Gestures: PRESS transitioned to SWIPE, "
3835 "speed1 %0.3f >= %0.3f, speed2 %0.3f >= %0.3f, "
3836 "cosine %0.3f >= %0.3f",
3837 speed1, MULTITOUCH_MIN_SPEED, speed2, MULTITOUCH_MIN_SPEED,
3838 cosine, SWIPE_TRANSITION_ANGLE_COSINE);
3839#endif
Jeff Brownace13b12011-03-09 17:39:48 -08003840 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
Jeff Brown2352b972011-04-12 22:39:53 -07003841 } else {
3842 // Pointers are moving in different directions. Switch to FREEFORM.
3843#if DEBUG_GESTURES
3844 LOGD("Gestures: PRESS transitioned to FREEFORM, "
3845 "speed1 %0.3f >= %0.3f, speed2 %0.3f >= %0.3f, "
3846 "cosine %0.3f < %0.3f",
3847 speed1, MULTITOUCH_MIN_SPEED, speed2, MULTITOUCH_MIN_SPEED,
3848 cosine, SWIPE_TRANSITION_ANGLE_COSINE);
3849#endif
3850 *outCancelPreviousGesture = true;
3851 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brownace13b12011-03-09 17:39:48 -08003852 }
3853 }
Jeff Brownace13b12011-03-09 17:39:48 -08003854 }
3855 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
Jeff Brown2352b972011-04-12 22:39:53 -07003856 // Switch from SWIPE to FREEFORM if additional pointers go down.
3857 // Cancel previous gesture.
3858 if (mCurrentTouch.pointerCount > 2) {
3859#if DEBUG_GESTURES
3860 LOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3861 mCurrentTouch.pointerCount);
3862#endif
Jeff Brownace13b12011-03-09 17:39:48 -08003863 *outCancelPreviousGesture = true;
3864 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003865 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003866 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003867
Jeff Brown2352b972011-04-12 22:39:53 -07003868 // Move the reference points based on the overall group motion of the fingers.
3869 // The objective is to calculate a vector delta that is common to the movement
3870 // of all fingers.
3871 BitSet32 commonIdBits(mLastTouch.idBits.value & mCurrentTouch.idBits.value);
3872 if (!commonIdBits.isEmpty()) {
3873 float commonDeltaX = 0, commonDeltaY = 0;
3874 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
3875 bool first = (idBits == commonIdBits);
3876 uint32_t id = idBits.firstMarkedBit();
3877 idBits.clearBit(id);
3878
3879 const PointerData& cpd = mCurrentTouch.pointers[mCurrentTouch.idToIndex[id]];
3880 const PointerData& lpd = mLastTouch.pointers[mLastTouch.idToIndex[id]];
3881 float deltaX = cpd.x - lpd.x;
3882 float deltaY = cpd.y - lpd.y;
3883
3884 if (first) {
3885 commonDeltaX = deltaX;
3886 commonDeltaY = deltaY;
3887 } else {
3888 commonDeltaX = calculateCommonVector(commonDeltaX, deltaX);
3889 commonDeltaY = calculateCommonVector(commonDeltaY, deltaY);
3890 }
3891 }
3892
3893 mPointerGesture.referenceTouchX += commonDeltaX;
3894 mPointerGesture.referenceTouchY += commonDeltaY;
3895 mPointerGesture.referenceGestureX +=
3896 commonDeltaX * mLocked.pointerGestureXMovementScale;
3897 mPointerGesture.referenceGestureY +=
3898 commonDeltaY * mLocked.pointerGestureYMovementScale;
3899 clampPositionUsingPointerBounds(mPointerController,
3900 &mPointerGesture.referenceGestureX,
3901 &mPointerGesture.referenceGestureY);
3902 }
3903
3904 // Report gestures.
3905 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
3906 // PRESS mode.
Jeff Brownace13b12011-03-09 17:39:48 -08003907#if DEBUG_GESTURES
Jeff Brown2352b972011-04-12 22:39:53 -07003908 LOGD("Gestures: PRESS activeTouchId=%d,"
Jeff Brownace13b12011-03-09 17:39:48 -08003909 "activeGestureId=%d, currentTouchPointerCount=%d",
Jeff Brown2352b972011-04-12 22:39:53 -07003910 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
Jeff Brownace13b12011-03-09 17:39:48 -08003911#endif
Jeff Brownb6110c22011-04-01 16:15:13 -07003912 LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
Jeff Brownace13b12011-03-09 17:39:48 -08003913
Jeff Brownace13b12011-03-09 17:39:48 -08003914 mPointerGesture.currentGestureIdBits.clear();
3915 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3916 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3917 mPointerGesture.currentGestureCoords[0].clear();
Jeff Brown2352b972011-04-12 22:39:53 -07003918 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3919 mPointerGesture.referenceGestureX);
3920 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3921 mPointerGesture.referenceGestureY);
Jeff Brownace13b12011-03-09 17:39:48 -08003922 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown2352b972011-04-12 22:39:53 -07003923
3924 mPointerController->setButtonState(BUTTON_STATE_PRIMARY);
3925
3926 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3927 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_PRESS;
3928 }
3929 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
3930 // SWIPE mode.
3931#if DEBUG_GESTURES
3932 LOGD("Gestures: SWIPE activeTouchId=%d,"
3933 "activeGestureId=%d, currentTouchPointerCount=%d",
3934 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
3935#endif
3936 LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3937
3938 mPointerGesture.currentGestureIdBits.clear();
3939 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3940 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3941 mPointerGesture.currentGestureCoords[0].clear();
3942 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3943 mPointerGesture.referenceGestureX);
3944 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3945 mPointerGesture.referenceGestureY);
3946 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3947
3948 mPointerController->setButtonState(0); // touch is not actually following the pointer
3949
3950 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3951 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_SWIPE;
3952 }
Jeff Brownace13b12011-03-09 17:39:48 -08003953 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
3954 // FREEFORM mode.
3955#if DEBUG_GESTURES
3956 LOGD("Gestures: FREEFORM activeTouchId=%d,"
3957 "activeGestureId=%d, currentTouchPointerCount=%d",
Jeff Brown2352b972011-04-12 22:39:53 -07003958 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
Jeff Brownace13b12011-03-09 17:39:48 -08003959#endif
Jeff Brownb6110c22011-04-01 16:15:13 -07003960 LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
Jeff Brownace13b12011-03-09 17:39:48 -08003961
Jeff Brownace13b12011-03-09 17:39:48 -08003962 mPointerGesture.currentGestureIdBits.clear();
3963
3964 BitSet32 mappedTouchIdBits;
3965 BitSet32 usedGestureIdBits;
3966 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
3967 // Initially, assign the active gesture id to the active touch point
3968 // if there is one. No other touch id bits are mapped yet.
3969 if (!*outCancelPreviousGesture) {
3970 mappedTouchIdBits.markBit(activeTouchId);
3971 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3972 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3973 mPointerGesture.activeGestureId;
3974 } else {
3975 mPointerGesture.activeGestureId = -1;
3976 }
3977 } else {
3978 // Otherwise, assume we mapped all touches from the previous frame.
3979 // Reuse all mappings that are still applicable.
3980 mappedTouchIdBits.value = mLastTouch.idBits.value & mCurrentTouch.idBits.value;
3981 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3982
3983 // Check whether we need to choose a new active gesture id because the
3984 // current went went up.
3985 for (BitSet32 upTouchIdBits(mLastTouch.idBits.value & ~mCurrentTouch.idBits.value);
3986 !upTouchIdBits.isEmpty(); ) {
3987 uint32_t upTouchId = upTouchIdBits.firstMarkedBit();
3988 upTouchIdBits.clearBit(upTouchId);
3989 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3990 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3991 mPointerGesture.activeGestureId = -1;
3992 break;
3993 }
3994 }
3995 }
3996
3997#if DEBUG_GESTURES
3998 LOGD("Gestures: FREEFORM follow up "
3999 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
4000 "activeGestureId=%d",
4001 mappedTouchIdBits.value, usedGestureIdBits.value,
4002 mPointerGesture.activeGestureId);
4003#endif
4004
Jeff Brown2352b972011-04-12 22:39:53 -07004005 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
Jeff Brownace13b12011-03-09 17:39:48 -08004006 uint32_t touchId = mCurrentTouch.pointers[i].id;
4007 uint32_t gestureId;
4008 if (!mappedTouchIdBits.hasBit(touchId)) {
4009 gestureId = usedGestureIdBits.firstUnmarkedBit();
4010 usedGestureIdBits.markBit(gestureId);
4011 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
4012#if DEBUG_GESTURES
4013 LOGD("Gestures: FREEFORM "
4014 "new mapping for touch id %d -> gesture id %d",
4015 touchId, gestureId);
4016#endif
4017 } else {
4018 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
4019#if DEBUG_GESTURES
4020 LOGD("Gestures: FREEFORM "
4021 "existing mapping for touch id %d -> gesture id %d",
4022 touchId, gestureId);
4023#endif
4024 }
4025 mPointerGesture.currentGestureIdBits.markBit(gestureId);
4026 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
4027
Jeff Brown2352b972011-04-12 22:39:53 -07004028 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.referenceTouchX)
4029 * mLocked.pointerGestureXZoomScale + mPointerGesture.referenceGestureX;
4030 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.referenceTouchY)
4031 * mLocked.pointerGestureYZoomScale + mPointerGesture.referenceGestureY;
Jeff Brownace13b12011-03-09 17:39:48 -08004032
4033 mPointerGesture.currentGestureCoords[i].clear();
4034 mPointerGesture.currentGestureCoords[i].setAxisValue(
4035 AMOTION_EVENT_AXIS_X, x);
4036 mPointerGesture.currentGestureCoords[i].setAxisValue(
4037 AMOTION_EVENT_AXIS_Y, y);
4038 mPointerGesture.currentGestureCoords[i].setAxisValue(
4039 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4040 }
4041
4042 if (mPointerGesture.activeGestureId < 0) {
4043 mPointerGesture.activeGestureId =
4044 mPointerGesture.currentGestureIdBits.firstMarkedBit();
4045#if DEBUG_GESTURES
4046 LOGD("Gestures: FREEFORM new "
4047 "activeGestureId=%d", mPointerGesture.activeGestureId);
4048#endif
4049 }
Jeff Brownace13b12011-03-09 17:39:48 -08004050
Jeff Brown2352b972011-04-12 22:39:53 -07004051 mPointerController->setButtonState(0); // touch is not actually following the pointer
4052
4053 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4054 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_FREEFORM;
4055 }
4056 }
4057
4058 // Update spot locations for PRESS, SWIPE and FREEFORM.
4059 // We use the same calculation as we do to calculate the gesture pointers
4060 // for FREEFORM so that the spots smoothly track gestures.
4061 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4062 mPointerGesture.spotIdBits.clear();
4063 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
4064 uint32_t id = mCurrentTouch.pointers[i].id;
4065 mPointerGesture.spotIdBits.markBit(id);
4066 mPointerGesture.spotIdToIndex[id] = i;
4067
4068 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.referenceTouchX)
4069 * mLocked.pointerGestureXZoomScale + mPointerGesture.referenceGestureX;
4070 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.referenceTouchY)
4071 * mLocked.pointerGestureYZoomScale + mPointerGesture.referenceGestureY;
4072
4073 mPointerGesture.spotCoords[i].clear();
4074 mPointerGesture.spotCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4075 mPointerGesture.spotCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4076 mPointerGesture.spotCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4077 }
4078 moveSpotsLocked();
4079 }
Jeff Brownace13b12011-03-09 17:39:48 -08004080 }
4081
4082#if DEBUG_GESTURES
4083 LOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
Jeff Brown2352b972011-04-12 22:39:53 -07004084 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
4085 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
Jeff Brownace13b12011-03-09 17:39:48 -08004086 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
Jeff Brown2352b972011-04-12 22:39:53 -07004087 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
4088 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
Jeff Brownace13b12011-03-09 17:39:48 -08004089 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
4090 uint32_t id = idBits.firstMarkedBit();
4091 idBits.clearBit(id);
4092 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
4093 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
4094 LOGD(" currentGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
4095 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
4096 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
4097 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
4098 }
4099 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
4100 uint32_t id = idBits.firstMarkedBit();
4101 idBits.clearBit(id);
4102 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
4103 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
4104 LOGD(" lastGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
4105 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
4106 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
4107 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
4108 }
4109#endif
4110}
4111
Jeff Brown2352b972011-04-12 22:39:53 -07004112void TouchInputMapper::moveSpotsLocked() {
4113 mPointerController->setSpots(mPointerGesture.spotGesture,
4114 mPointerGesture.spotCoords, mPointerGesture.spotIdToIndex, mPointerGesture.spotIdBits);
4115}
4116
Jeff Brownace13b12011-03-09 17:39:48 -08004117void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
4118 int32_t action, int32_t flags, uint32_t metaState, int32_t edgeFlags,
4119 const PointerCoords* coords, const uint32_t* idToIndex, BitSet32 idBits,
4120 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
4121 PointerCoords pointerCoords[MAX_POINTERS];
4122 int32_t pointerIds[MAX_POINTERS];
4123 uint32_t pointerCount = 0;
4124 while (!idBits.isEmpty()) {
4125 uint32_t id = idBits.firstMarkedBit();
4126 idBits.clearBit(id);
4127 uint32_t index = idToIndex[id];
4128 pointerIds[pointerCount] = id;
4129 pointerCoords[pointerCount].copyFrom(coords[index]);
4130
4131 if (changedId >= 0 && id == uint32_t(changedId)) {
4132 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
4133 }
4134
4135 pointerCount += 1;
4136 }
4137
Jeff Brownb6110c22011-04-01 16:15:13 -07004138 LOG_ASSERT(pointerCount != 0);
Jeff Brownace13b12011-03-09 17:39:48 -08004139
4140 if (changedId >= 0 && pointerCount == 1) {
4141 // Replace initial down and final up action.
4142 // We can compare the action without masking off the changed pointer index
4143 // because we know the index is 0.
4144 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
4145 action = AMOTION_EVENT_ACTION_DOWN;
4146 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
4147 action = AMOTION_EVENT_ACTION_UP;
4148 } else {
4149 // Can't happen.
Jeff Brownb6110c22011-04-01 16:15:13 -07004150 LOG_ASSERT(false);
Jeff Brownace13b12011-03-09 17:39:48 -08004151 }
4152 }
4153
4154 getDispatcher()->notifyMotion(when, getDeviceId(), source, policyFlags,
4155 action, flags, metaState, edgeFlags,
4156 pointerCount, pointerIds, pointerCoords, xPrecision, yPrecision, downTime);
4157}
4158
4159bool TouchInputMapper::updateMovedPointerCoords(
4160 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
4161 PointerCoords* outCoords, const uint32_t* outIdToIndex, BitSet32 idBits) const {
4162 bool changed = false;
4163 while (!idBits.isEmpty()) {
4164 uint32_t id = idBits.firstMarkedBit();
4165 idBits.clearBit(id);
4166
4167 uint32_t inIndex = inIdToIndex[id];
4168 uint32_t outIndex = outIdToIndex[id];
4169 const PointerCoords& curInCoords = inCoords[inIndex];
4170 PointerCoords& curOutCoords = outCoords[outIndex];
4171
4172 if (curInCoords != curOutCoords) {
4173 curOutCoords.copyFrom(curInCoords);
4174 changed = true;
4175 }
4176 }
4177 return changed;
4178}
4179
4180void TouchInputMapper::fadePointer() {
4181 { // acquire lock
4182 AutoMutex _l(mLock);
4183 if (mPointerController != NULL) {
4184 mPointerController->fade();
4185 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004186 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004187}
4188
Jeff Brown6328cdc2010-07-29 18:18:33 -07004189bool TouchInputMapper::isPointInsideSurfaceLocked(int32_t x, int32_t y) {
Jeff Brown9626b142011-03-03 02:09:54 -08004190 return x >= mRawAxes.x.minValue && x <= mRawAxes.x.maxValue
4191 && y >= mRawAxes.y.minValue && y <= mRawAxes.y.maxValue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004192}
4193
Jeff Brown6328cdc2010-07-29 18:18:33 -07004194const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHitLocked(
4195 int32_t x, int32_t y) {
4196 size_t numVirtualKeys = mLocked.virtualKeys.size();
4197 for (size_t i = 0; i < numVirtualKeys; i++) {
4198 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004199
4200#if DEBUG_VIRTUAL_KEYS
4201 LOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
4202 "left=%d, top=%d, right=%d, bottom=%d",
4203 x, y,
4204 virtualKey.keyCode, virtualKey.scanCode,
4205 virtualKey.hitLeft, virtualKey.hitTop,
4206 virtualKey.hitRight, virtualKey.hitBottom);
4207#endif
4208
4209 if (virtualKey.isHit(x, y)) {
4210 return & virtualKey;
4211 }
4212 }
4213
4214 return NULL;
4215}
4216
4217void TouchInputMapper::calculatePointerIds() {
4218 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
4219 uint32_t lastPointerCount = mLastTouch.pointerCount;
4220
4221 if (currentPointerCount == 0) {
4222 // No pointers to assign.
4223 mCurrentTouch.idBits.clear();
4224 } else if (lastPointerCount == 0) {
4225 // All pointers are new.
4226 mCurrentTouch.idBits.clear();
4227 for (uint32_t i = 0; i < currentPointerCount; i++) {
4228 mCurrentTouch.pointers[i].id = i;
4229 mCurrentTouch.idToIndex[i] = i;
4230 mCurrentTouch.idBits.markBit(i);
4231 }
4232 } else if (currentPointerCount == 1 && lastPointerCount == 1) {
4233 // Only one pointer and no change in count so it must have the same id as before.
4234 uint32_t id = mLastTouch.pointers[0].id;
4235 mCurrentTouch.pointers[0].id = id;
4236 mCurrentTouch.idToIndex[id] = 0;
4237 mCurrentTouch.idBits.value = BitSet32::valueForBit(id);
4238 } else {
4239 // General case.
4240 // We build a heap of squared euclidean distances between current and last pointers
4241 // associated with the current and last pointer indices. Then, we find the best
4242 // match (by distance) for each current pointer.
4243 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
4244
4245 uint32_t heapSize = 0;
4246 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
4247 currentPointerIndex++) {
4248 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
4249 lastPointerIndex++) {
4250 int64_t deltaX = mCurrentTouch.pointers[currentPointerIndex].x
4251 - mLastTouch.pointers[lastPointerIndex].x;
4252 int64_t deltaY = mCurrentTouch.pointers[currentPointerIndex].y
4253 - mLastTouch.pointers[lastPointerIndex].y;
4254
4255 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4256
4257 // Insert new element into the heap (sift up).
4258 heap[heapSize].currentPointerIndex = currentPointerIndex;
4259 heap[heapSize].lastPointerIndex = lastPointerIndex;
4260 heap[heapSize].distance = distance;
4261 heapSize += 1;
4262 }
4263 }
4264
4265 // Heapify
4266 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
4267 startIndex -= 1;
4268 for (uint32_t parentIndex = startIndex; ;) {
4269 uint32_t childIndex = parentIndex * 2 + 1;
4270 if (childIndex >= heapSize) {
4271 break;
4272 }
4273
4274 if (childIndex + 1 < heapSize
4275 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4276 childIndex += 1;
4277 }
4278
4279 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4280 break;
4281 }
4282
4283 swap(heap[parentIndex], heap[childIndex]);
4284 parentIndex = childIndex;
4285 }
4286 }
4287
4288#if DEBUG_POINTER_ASSIGNMENT
4289 LOGD("calculatePointerIds - initial distance min-heap: size=%d", heapSize);
4290 for (size_t i = 0; i < heapSize; i++) {
4291 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4292 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4293 heap[i].distance);
4294 }
4295#endif
4296
4297 // Pull matches out by increasing order of distance.
4298 // To avoid reassigning pointers that have already been matched, the loop keeps track
4299 // of which last and current pointers have been matched using the matchedXXXBits variables.
4300 // It also tracks the used pointer id bits.
4301 BitSet32 matchedLastBits(0);
4302 BitSet32 matchedCurrentBits(0);
4303 BitSet32 usedIdBits(0);
4304 bool first = true;
4305 for (uint32_t i = min(currentPointerCount, lastPointerCount); i > 0; i--) {
4306 for (;;) {
4307 if (first) {
4308 // The first time through the loop, we just consume the root element of
4309 // the heap (the one with smallest distance).
4310 first = false;
4311 } else {
4312 // Previous iterations consumed the root element of the heap.
4313 // Pop root element off of the heap (sift down).
4314 heapSize -= 1;
Jeff Brownb6110c22011-04-01 16:15:13 -07004315 LOG_ASSERT(heapSize > 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004316
4317 // Sift down.
4318 heap[0] = heap[heapSize];
4319 for (uint32_t parentIndex = 0; ;) {
4320 uint32_t childIndex = parentIndex * 2 + 1;
4321 if (childIndex >= heapSize) {
4322 break;
4323 }
4324
4325 if (childIndex + 1 < heapSize
4326 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4327 childIndex += 1;
4328 }
4329
4330 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4331 break;
4332 }
4333
4334 swap(heap[parentIndex], heap[childIndex]);
4335 parentIndex = childIndex;
4336 }
4337
4338#if DEBUG_POINTER_ASSIGNMENT
4339 LOGD("calculatePointerIds - reduced distance min-heap: size=%d", heapSize);
4340 for (size_t i = 0; i < heapSize; i++) {
4341 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4342 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4343 heap[i].distance);
4344 }
4345#endif
4346 }
4347
4348 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4349 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4350
4351 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4352 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4353
4354 matchedCurrentBits.markBit(currentPointerIndex);
4355 matchedLastBits.markBit(lastPointerIndex);
4356
4357 uint32_t id = mLastTouch.pointers[lastPointerIndex].id;
4358 mCurrentTouch.pointers[currentPointerIndex].id = id;
4359 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4360 usedIdBits.markBit(id);
4361
4362#if DEBUG_POINTER_ASSIGNMENT
4363 LOGD("calculatePointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
4364 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
4365#endif
4366 break;
4367 }
4368 }
4369
4370 // Assign fresh ids to new pointers.
4371 if (currentPointerCount > lastPointerCount) {
4372 for (uint32_t i = currentPointerCount - lastPointerCount; ;) {
4373 uint32_t currentPointerIndex = matchedCurrentBits.firstUnmarkedBit();
4374 uint32_t id = usedIdBits.firstUnmarkedBit();
4375
4376 mCurrentTouch.pointers[currentPointerIndex].id = id;
4377 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4378 usedIdBits.markBit(id);
4379
4380#if DEBUG_POINTER_ASSIGNMENT
4381 LOGD("calculatePointerIds - assigned: cur=%d, id=%d",
4382 currentPointerIndex, id);
4383#endif
4384
4385 if (--i == 0) break; // done
4386 matchedCurrentBits.markBit(currentPointerIndex);
4387 }
4388 }
4389
4390 // Fix id bits.
4391 mCurrentTouch.idBits = usedIdBits;
4392 }
4393}
4394
4395/* Special hack for devices that have bad screen data: if one of the
4396 * points has moved more than a screen height from the last position,
4397 * then drop it. */
4398bool TouchInputMapper::applyBadTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004399 uint32_t pointerCount = mCurrentTouch.pointerCount;
4400
4401 // Nothing to do if there are no points.
4402 if (pointerCount == 0) {
4403 return false;
4404 }
4405
4406 // Don't do anything if a finger is going down or up. We run
4407 // here before assigning pointer IDs, so there isn't a good
4408 // way to do per-finger matching.
4409 if (pointerCount != mLastTouch.pointerCount) {
4410 return false;
4411 }
4412
4413 // We consider a single movement across more than a 7/16 of
4414 // the long size of the screen to be bad. This was a magic value
4415 // determined by looking at the maximum distance it is feasible
4416 // to actually move in one sample.
Jeff Brown9626b142011-03-03 02:09:54 -08004417 int32_t maxDeltaY = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) * 7 / 16;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004418
4419 // XXX The original code in InputDevice.java included commented out
4420 // code for testing the X axis. Note that when we drop a point
4421 // we don't actually restore the old X either. Strange.
4422 // The old code also tries to track when bad points were previously
4423 // detected but it turns out that due to the placement of a "break"
4424 // at the end of the loop, we never set mDroppedBadPoint to true
4425 // so it is effectively dead code.
4426 // Need to figure out if the old code is busted or just overcomplicated
4427 // but working as intended.
4428
4429 // Look through all new points and see if any are farther than
4430 // acceptable from all previous points.
4431 for (uint32_t i = pointerCount; i-- > 0; ) {
4432 int32_t y = mCurrentTouch.pointers[i].y;
4433 int32_t closestY = INT_MAX;
4434 int32_t closestDeltaY = 0;
4435
4436#if DEBUG_HACKS
4437 LOGD("BadTouchFilter: Looking at next point #%d: y=%d", i, y);
4438#endif
4439
4440 for (uint32_t j = pointerCount; j-- > 0; ) {
4441 int32_t lastY = mLastTouch.pointers[j].y;
4442 int32_t deltaY = abs(y - lastY);
4443
4444#if DEBUG_HACKS
4445 LOGD("BadTouchFilter: Comparing with last point #%d: y=%d deltaY=%d",
4446 j, lastY, deltaY);
4447#endif
4448
4449 if (deltaY < maxDeltaY) {
4450 goto SkipSufficientlyClosePoint;
4451 }
4452 if (deltaY < closestDeltaY) {
4453 closestDeltaY = deltaY;
4454 closestY = lastY;
4455 }
4456 }
4457
4458 // Must not have found a close enough match.
4459#if DEBUG_HACKS
4460 LOGD("BadTouchFilter: Dropping bad point #%d: newY=%d oldY=%d deltaY=%d maxDeltaY=%d",
4461 i, y, closestY, closestDeltaY, maxDeltaY);
4462#endif
4463
4464 mCurrentTouch.pointers[i].y = closestY;
4465 return true; // XXX original code only corrects one point
4466
4467 SkipSufficientlyClosePoint: ;
4468 }
4469
4470 // No change.
4471 return false;
4472}
4473
4474/* Special hack for devices that have bad screen data: drop points where
4475 * the coordinate value for one axis has jumped to the other pointer's location.
4476 */
4477bool TouchInputMapper::applyJumpyTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004478 uint32_t pointerCount = mCurrentTouch.pointerCount;
4479 if (mLastTouch.pointerCount != pointerCount) {
4480#if DEBUG_HACKS
4481 LOGD("JumpyTouchFilter: Different pointer count %d -> %d",
4482 mLastTouch.pointerCount, pointerCount);
4483 for (uint32_t i = 0; i < pointerCount; i++) {
4484 LOGD(" Pointer %d (%d, %d)", i,
4485 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4486 }
4487#endif
4488
4489 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_TRANSITION_DROPS) {
4490 if (mLastTouch.pointerCount == 1 && pointerCount == 2) {
4491 // Just drop the first few events going from 1 to 2 pointers.
4492 // They're bad often enough that they're not worth considering.
4493 mCurrentTouch.pointerCount = 1;
4494 mJumpyTouchFilter.jumpyPointsDropped += 1;
4495
4496#if DEBUG_HACKS
4497 LOGD("JumpyTouchFilter: Pointer 2 dropped");
4498#endif
4499 return true;
4500 } else if (mLastTouch.pointerCount == 2 && pointerCount == 1) {
4501 // The event when we go from 2 -> 1 tends to be messed up too
4502 mCurrentTouch.pointerCount = 2;
4503 mCurrentTouch.pointers[0] = mLastTouch.pointers[0];
4504 mCurrentTouch.pointers[1] = mLastTouch.pointers[1];
4505 mJumpyTouchFilter.jumpyPointsDropped += 1;
4506
4507#if DEBUG_HACKS
4508 for (int32_t i = 0; i < 2; i++) {
4509 LOGD("JumpyTouchFilter: Pointer %d replaced (%d, %d)", i,
4510 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4511 }
4512#endif
4513 return true;
4514 }
4515 }
4516 // Reset jumpy points dropped on other transitions or if limit exceeded.
4517 mJumpyTouchFilter.jumpyPointsDropped = 0;
4518
4519#if DEBUG_HACKS
4520 LOGD("JumpyTouchFilter: Transition - drop limit reset");
4521#endif
4522 return false;
4523 }
4524
4525 // We have the same number of pointers as last time.
4526 // A 'jumpy' point is one where the coordinate value for one axis
4527 // has jumped to the other pointer's location. No need to do anything
4528 // else if we only have one pointer.
4529 if (pointerCount < 2) {
4530 return false;
4531 }
4532
4533 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_DROP_LIMIT) {
Jeff Brown9626b142011-03-03 02:09:54 -08004534 int jumpyEpsilon = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) / JUMPY_EPSILON_DIVISOR;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004535
4536 // We only replace the single worst jumpy point as characterized by pointer distance
4537 // in a single axis.
4538 int32_t badPointerIndex = -1;
4539 int32_t badPointerReplacementIndex = -1;
4540 int32_t badPointerDistance = INT_MIN; // distance to be corrected
4541
4542 for (uint32_t i = pointerCount; i-- > 0; ) {
4543 int32_t x = mCurrentTouch.pointers[i].x;
4544 int32_t y = mCurrentTouch.pointers[i].y;
4545
4546#if DEBUG_HACKS
4547 LOGD("JumpyTouchFilter: Point %d (%d, %d)", i, x, y);
4548#endif
4549
4550 // Check if a touch point is too close to another's coordinates
4551 bool dropX = false, dropY = false;
4552 for (uint32_t j = 0; j < pointerCount; j++) {
4553 if (i == j) {
4554 continue;
4555 }
4556
4557 if (abs(x - mCurrentTouch.pointers[j].x) <= jumpyEpsilon) {
4558 dropX = true;
4559 break;
4560 }
4561
4562 if (abs(y - mCurrentTouch.pointers[j].y) <= jumpyEpsilon) {
4563 dropY = true;
4564 break;
4565 }
4566 }
4567 if (! dropX && ! dropY) {
4568 continue; // not jumpy
4569 }
4570
4571 // Find a replacement candidate by comparing with older points on the
4572 // complementary (non-jumpy) axis.
4573 int32_t distance = INT_MIN; // distance to be corrected
4574 int32_t replacementIndex = -1;
4575
4576 if (dropX) {
4577 // X looks too close. Find an older replacement point with a close Y.
4578 int32_t smallestDeltaY = INT_MAX;
4579 for (uint32_t j = 0; j < pointerCount; j++) {
4580 int32_t deltaY = abs(y - mLastTouch.pointers[j].y);
4581 if (deltaY < smallestDeltaY) {
4582 smallestDeltaY = deltaY;
4583 replacementIndex = j;
4584 }
4585 }
4586 distance = abs(x - mLastTouch.pointers[replacementIndex].x);
4587 } else {
4588 // Y looks too close. Find an older replacement point with a close X.
4589 int32_t smallestDeltaX = INT_MAX;
4590 for (uint32_t j = 0; j < pointerCount; j++) {
4591 int32_t deltaX = abs(x - mLastTouch.pointers[j].x);
4592 if (deltaX < smallestDeltaX) {
4593 smallestDeltaX = deltaX;
4594 replacementIndex = j;
4595 }
4596 }
4597 distance = abs(y - mLastTouch.pointers[replacementIndex].y);
4598 }
4599
4600 // If replacing this pointer would correct a worse error than the previous ones
4601 // considered, then use this replacement instead.
4602 if (distance > badPointerDistance) {
4603 badPointerIndex = i;
4604 badPointerReplacementIndex = replacementIndex;
4605 badPointerDistance = distance;
4606 }
4607 }
4608
4609 // Correct the jumpy pointer if one was found.
4610 if (badPointerIndex >= 0) {
4611#if DEBUG_HACKS
4612 LOGD("JumpyTouchFilter: Replacing bad pointer %d with (%d, %d)",
4613 badPointerIndex,
4614 mLastTouch.pointers[badPointerReplacementIndex].x,
4615 mLastTouch.pointers[badPointerReplacementIndex].y);
4616#endif
4617
4618 mCurrentTouch.pointers[badPointerIndex].x =
4619 mLastTouch.pointers[badPointerReplacementIndex].x;
4620 mCurrentTouch.pointers[badPointerIndex].y =
4621 mLastTouch.pointers[badPointerReplacementIndex].y;
4622 mJumpyTouchFilter.jumpyPointsDropped += 1;
4623 return true;
4624 }
4625 }
4626
4627 mJumpyTouchFilter.jumpyPointsDropped = 0;
4628 return false;
4629}
4630
4631/* Special hack for devices that have bad screen data: aggregate and
4632 * compute averages of the coordinate data, to reduce the amount of
4633 * jitter seen by applications. */
4634void TouchInputMapper::applyAveragingTouchFilter() {
4635 for (uint32_t currentIndex = 0; currentIndex < mCurrentTouch.pointerCount; currentIndex++) {
4636 uint32_t id = mCurrentTouch.pointers[currentIndex].id;
4637 int32_t x = mCurrentTouch.pointers[currentIndex].x;
4638 int32_t y = mCurrentTouch.pointers[currentIndex].y;
Jeff Brown8d608662010-08-30 03:02:23 -07004639 int32_t pressure;
4640 switch (mCalibration.pressureSource) {
4641 case Calibration::PRESSURE_SOURCE_PRESSURE:
4642 pressure = mCurrentTouch.pointers[currentIndex].pressure;
4643 break;
4644 case Calibration::PRESSURE_SOURCE_TOUCH:
4645 pressure = mCurrentTouch.pointers[currentIndex].touchMajor;
4646 break;
4647 default:
4648 pressure = 1;
4649 break;
4650 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004651
4652 if (mLastTouch.idBits.hasBit(id)) {
4653 // Pointer was down before and is still down now.
4654 // Compute average over history trace.
4655 uint32_t start = mAveragingTouchFilter.historyStart[id];
4656 uint32_t end = mAveragingTouchFilter.historyEnd[id];
4657
4658 int64_t deltaX = x - mAveragingTouchFilter.historyData[end].pointers[id].x;
4659 int64_t deltaY = y - mAveragingTouchFilter.historyData[end].pointers[id].y;
4660 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4661
4662#if DEBUG_HACKS
4663 LOGD("AveragingTouchFilter: Pointer id %d - Distance from last sample: %lld",
4664 id, distance);
4665#endif
4666
4667 if (distance < AVERAGING_DISTANCE_LIMIT) {
4668 // Increment end index in preparation for recording new historical data.
4669 end += 1;
4670 if (end > AVERAGING_HISTORY_SIZE) {
4671 end = 0;
4672 }
4673
4674 // If the end index has looped back to the start index then we have filled
4675 // the historical trace up to the desired size so we drop the historical
4676 // data at the start of the trace.
4677 if (end == start) {
4678 start += 1;
4679 if (start > AVERAGING_HISTORY_SIZE) {
4680 start = 0;
4681 }
4682 }
4683
4684 // Add the raw data to the historical trace.
4685 mAveragingTouchFilter.historyStart[id] = start;
4686 mAveragingTouchFilter.historyEnd[id] = end;
4687 mAveragingTouchFilter.historyData[end].pointers[id].x = x;
4688 mAveragingTouchFilter.historyData[end].pointers[id].y = y;
4689 mAveragingTouchFilter.historyData[end].pointers[id].pressure = pressure;
4690
4691 // Average over all historical positions in the trace by total pressure.
4692 int32_t averagedX = 0;
4693 int32_t averagedY = 0;
4694 int32_t totalPressure = 0;
4695 for (;;) {
4696 int32_t historicalX = mAveragingTouchFilter.historyData[start].pointers[id].x;
4697 int32_t historicalY = mAveragingTouchFilter.historyData[start].pointers[id].y;
4698 int32_t historicalPressure = mAveragingTouchFilter.historyData[start]
4699 .pointers[id].pressure;
4700
4701 averagedX += historicalX * historicalPressure;
4702 averagedY += historicalY * historicalPressure;
4703 totalPressure += historicalPressure;
4704
4705 if (start == end) {
4706 break;
4707 }
4708
4709 start += 1;
4710 if (start > AVERAGING_HISTORY_SIZE) {
4711 start = 0;
4712 }
4713 }
4714
Jeff Brown8d608662010-08-30 03:02:23 -07004715 if (totalPressure != 0) {
4716 averagedX /= totalPressure;
4717 averagedY /= totalPressure;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004718
4719#if DEBUG_HACKS
Jeff Brown8d608662010-08-30 03:02:23 -07004720 LOGD("AveragingTouchFilter: Pointer id %d - "
4721 "totalPressure=%d, averagedX=%d, averagedY=%d", id, totalPressure,
4722 averagedX, averagedY);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004723#endif
4724
Jeff Brown8d608662010-08-30 03:02:23 -07004725 mCurrentTouch.pointers[currentIndex].x = averagedX;
4726 mCurrentTouch.pointers[currentIndex].y = averagedY;
4727 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004728 } else {
4729#if DEBUG_HACKS
4730 LOGD("AveragingTouchFilter: Pointer id %d - Exceeded max distance", id);
4731#endif
4732 }
4733 } else {
4734#if DEBUG_HACKS
4735 LOGD("AveragingTouchFilter: Pointer id %d - Pointer went up", id);
4736#endif
4737 }
4738
4739 // Reset pointer history.
4740 mAveragingTouchFilter.historyStart[id] = 0;
4741 mAveragingTouchFilter.historyEnd[id] = 0;
4742 mAveragingTouchFilter.historyData[0].pointers[id].x = x;
4743 mAveragingTouchFilter.historyData[0].pointers[id].y = y;
4744 mAveragingTouchFilter.historyData[0].pointers[id].pressure = pressure;
4745 }
4746}
4747
4748int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004749 { // acquire lock
4750 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004751
Jeff Brown6328cdc2010-07-29 18:18:33 -07004752 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.keyCode == keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004753 return AKEY_STATE_VIRTUAL;
4754 }
4755
Jeff Brown6328cdc2010-07-29 18:18:33 -07004756 size_t numVirtualKeys = mLocked.virtualKeys.size();
4757 for (size_t i = 0; i < numVirtualKeys; i++) {
4758 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004759 if (virtualKey.keyCode == keyCode) {
4760 return AKEY_STATE_UP;
4761 }
4762 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004763 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004764
4765 return AKEY_STATE_UNKNOWN;
4766}
4767
4768int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004769 { // acquire lock
4770 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004771
Jeff Brown6328cdc2010-07-29 18:18:33 -07004772 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004773 return AKEY_STATE_VIRTUAL;
4774 }
4775
Jeff Brown6328cdc2010-07-29 18:18:33 -07004776 size_t numVirtualKeys = mLocked.virtualKeys.size();
4777 for (size_t i = 0; i < numVirtualKeys; i++) {
4778 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004779 if (virtualKey.scanCode == scanCode) {
4780 return AKEY_STATE_UP;
4781 }
4782 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004783 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004784
4785 return AKEY_STATE_UNKNOWN;
4786}
4787
4788bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4789 const int32_t* keyCodes, uint8_t* outFlags) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004790 { // acquire lock
4791 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004792
Jeff Brown6328cdc2010-07-29 18:18:33 -07004793 size_t numVirtualKeys = mLocked.virtualKeys.size();
4794 for (size_t i = 0; i < numVirtualKeys; i++) {
4795 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004796
4797 for (size_t i = 0; i < numCodes; i++) {
4798 if (virtualKey.keyCode == keyCodes[i]) {
4799 outFlags[i] = 1;
4800 }
4801 }
4802 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004803 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004804
4805 return true;
4806}
4807
4808
4809// --- SingleTouchInputMapper ---
4810
Jeff Brown47e6b1b2010-11-29 17:37:49 -08004811SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
4812 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004813 initialize();
4814}
4815
4816SingleTouchInputMapper::~SingleTouchInputMapper() {
4817}
4818
4819void SingleTouchInputMapper::initialize() {
4820 mAccumulator.clear();
4821
4822 mDown = false;
4823 mX = 0;
4824 mY = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07004825 mPressure = 0; // default to 0 for devices that don't report pressure
4826 mToolWidth = 0; // default to 0 for devices that don't report tool width
Jeff Brownace13b12011-03-09 17:39:48 -08004827 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004828}
4829
4830void SingleTouchInputMapper::reset() {
4831 TouchInputMapper::reset();
4832
Jeff Brown6d0fec22010-07-23 21:28:06 -07004833 initialize();
4834 }
4835
4836void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
4837 switch (rawEvent->type) {
4838 case EV_KEY:
4839 switch (rawEvent->scanCode) {
4840 case BTN_TOUCH:
4841 mAccumulator.fields |= Accumulator::FIELD_BTN_TOUCH;
4842 mAccumulator.btnTouch = rawEvent->value != 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004843 // Don't sync immediately. Wait until the next SYN_REPORT since we might
4844 // not have received valid position information yet. This logic assumes that
4845 // BTN_TOUCH is always followed by SYN_REPORT as part of a complete packet.
Jeff Brown6d0fec22010-07-23 21:28:06 -07004846 break;
Jeff Brownace13b12011-03-09 17:39:48 -08004847 default:
4848 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
4849 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
4850 if (buttonState) {
4851 if (rawEvent->value) {
4852 mAccumulator.buttonDown |= buttonState;
4853 } else {
4854 mAccumulator.buttonUp |= buttonState;
4855 }
4856 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
4857 }
4858 }
4859 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004860 }
4861 break;
4862
4863 case EV_ABS:
4864 switch (rawEvent->scanCode) {
4865 case ABS_X:
4866 mAccumulator.fields |= Accumulator::FIELD_ABS_X;
4867 mAccumulator.absX = rawEvent->value;
4868 break;
4869 case ABS_Y:
4870 mAccumulator.fields |= Accumulator::FIELD_ABS_Y;
4871 mAccumulator.absY = rawEvent->value;
4872 break;
4873 case ABS_PRESSURE:
4874 mAccumulator.fields |= Accumulator::FIELD_ABS_PRESSURE;
4875 mAccumulator.absPressure = rawEvent->value;
4876 break;
4877 case ABS_TOOL_WIDTH:
4878 mAccumulator.fields |= Accumulator::FIELD_ABS_TOOL_WIDTH;
4879 mAccumulator.absToolWidth = rawEvent->value;
4880 break;
4881 }
4882 break;
4883
4884 case EV_SYN:
4885 switch (rawEvent->scanCode) {
4886 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004887 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004888 break;
4889 }
4890 break;
4891 }
4892}
4893
4894void SingleTouchInputMapper::sync(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004895 uint32_t fields = mAccumulator.fields;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004896 if (fields == 0) {
4897 return; // no new state changes, so nothing to do
4898 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004899
4900 if (fields & Accumulator::FIELD_BTN_TOUCH) {
4901 mDown = mAccumulator.btnTouch;
4902 }
4903
4904 if (fields & Accumulator::FIELD_ABS_X) {
4905 mX = mAccumulator.absX;
4906 }
4907
4908 if (fields & Accumulator::FIELD_ABS_Y) {
4909 mY = mAccumulator.absY;
4910 }
4911
4912 if (fields & Accumulator::FIELD_ABS_PRESSURE) {
4913 mPressure = mAccumulator.absPressure;
4914 }
4915
4916 if (fields & Accumulator::FIELD_ABS_TOOL_WIDTH) {
Jeff Brown8d608662010-08-30 03:02:23 -07004917 mToolWidth = mAccumulator.absToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004918 }
4919
Jeff Brownace13b12011-03-09 17:39:48 -08004920 if (fields & Accumulator::FIELD_BUTTONS) {
4921 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
4922 }
4923
Jeff Brown6d0fec22010-07-23 21:28:06 -07004924 mCurrentTouch.clear();
4925
4926 if (mDown) {
4927 mCurrentTouch.pointerCount = 1;
4928 mCurrentTouch.pointers[0].id = 0;
4929 mCurrentTouch.pointers[0].x = mX;
4930 mCurrentTouch.pointers[0].y = mY;
4931 mCurrentTouch.pointers[0].pressure = mPressure;
Jeff Brown8d608662010-08-30 03:02:23 -07004932 mCurrentTouch.pointers[0].touchMajor = 0;
4933 mCurrentTouch.pointers[0].touchMinor = 0;
4934 mCurrentTouch.pointers[0].toolMajor = mToolWidth;
4935 mCurrentTouch.pointers[0].toolMinor = mToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004936 mCurrentTouch.pointers[0].orientation = 0;
4937 mCurrentTouch.idToIndex[0] = 0;
4938 mCurrentTouch.idBits.markBit(0);
Jeff Brownace13b12011-03-09 17:39:48 -08004939 mCurrentTouch.buttonState = mButtonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004940 }
4941
4942 syncTouch(when, true);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004943
4944 mAccumulator.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07004945}
4946
Jeff Brown8d608662010-08-30 03:02:23 -07004947void SingleTouchInputMapper::configureRawAxes() {
4948 TouchInputMapper::configureRawAxes();
Jeff Brown6d0fec22010-07-23 21:28:06 -07004949
Jeff Brown8d608662010-08-30 03:02:23 -07004950 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_X, & mRawAxes.x);
4951 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_Y, & mRawAxes.y);
4952 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_PRESSURE, & mRawAxes.pressure);
4953 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_TOOL_WIDTH, & mRawAxes.toolMajor);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004954}
4955
4956
4957// --- MultiTouchInputMapper ---
4958
Jeff Brown47e6b1b2010-11-29 17:37:49 -08004959MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
4960 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004961 initialize();
4962}
4963
4964MultiTouchInputMapper::~MultiTouchInputMapper() {
4965}
4966
4967void MultiTouchInputMapper::initialize() {
4968 mAccumulator.clear();
Jeff Brownace13b12011-03-09 17:39:48 -08004969 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004970}
4971
4972void MultiTouchInputMapper::reset() {
4973 TouchInputMapper::reset();
4974
Jeff Brown6d0fec22010-07-23 21:28:06 -07004975 initialize();
4976}
4977
4978void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
4979 switch (rawEvent->type) {
Jeff Brownace13b12011-03-09 17:39:48 -08004980 case EV_KEY: {
4981 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
4982 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
4983 if (buttonState) {
4984 if (rawEvent->value) {
4985 mAccumulator.buttonDown |= buttonState;
4986 } else {
4987 mAccumulator.buttonUp |= buttonState;
4988 }
4989 }
4990 }
4991 break;
4992 }
4993
Jeff Brown6d0fec22010-07-23 21:28:06 -07004994 case EV_ABS: {
4995 uint32_t pointerIndex = mAccumulator.pointerCount;
4996 Accumulator::Pointer* pointer = & mAccumulator.pointers[pointerIndex];
4997
4998 switch (rawEvent->scanCode) {
4999 case ABS_MT_POSITION_X:
5000 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_X;
5001 pointer->absMTPositionX = rawEvent->value;
5002 break;
5003 case ABS_MT_POSITION_Y:
5004 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_Y;
5005 pointer->absMTPositionY = rawEvent->value;
5006 break;
5007 case ABS_MT_TOUCH_MAJOR:
5008 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MAJOR;
5009 pointer->absMTTouchMajor = rawEvent->value;
5010 break;
5011 case ABS_MT_TOUCH_MINOR:
5012 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MINOR;
5013 pointer->absMTTouchMinor = rawEvent->value;
5014 break;
5015 case ABS_MT_WIDTH_MAJOR:
5016 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MAJOR;
5017 pointer->absMTWidthMajor = rawEvent->value;
5018 break;
5019 case ABS_MT_WIDTH_MINOR:
5020 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MINOR;
5021 pointer->absMTWidthMinor = rawEvent->value;
5022 break;
5023 case ABS_MT_ORIENTATION:
5024 pointer->fields |= Accumulator::FIELD_ABS_MT_ORIENTATION;
5025 pointer->absMTOrientation = rawEvent->value;
5026 break;
5027 case ABS_MT_TRACKING_ID:
5028 pointer->fields |= Accumulator::FIELD_ABS_MT_TRACKING_ID;
5029 pointer->absMTTrackingId = rawEvent->value;
5030 break;
Jeff Brown8d608662010-08-30 03:02:23 -07005031 case ABS_MT_PRESSURE:
5032 pointer->fields |= Accumulator::FIELD_ABS_MT_PRESSURE;
5033 pointer->absMTPressure = rawEvent->value;
5034 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005035 }
5036 break;
5037 }
5038
5039 case EV_SYN:
5040 switch (rawEvent->scanCode) {
5041 case SYN_MT_REPORT: {
5042 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
5043 uint32_t pointerIndex = mAccumulator.pointerCount;
5044
5045 if (mAccumulator.pointers[pointerIndex].fields) {
5046 if (pointerIndex == MAX_POINTERS) {
5047 LOGW("MultiTouch device driver returned more than maximum of %d pointers.",
5048 MAX_POINTERS);
5049 } else {
5050 pointerIndex += 1;
5051 mAccumulator.pointerCount = pointerIndex;
5052 }
5053 }
5054
5055 mAccumulator.pointers[pointerIndex].clear();
5056 break;
5057 }
5058
5059 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005060 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005061 break;
5062 }
5063 break;
5064 }
5065}
5066
5067void MultiTouchInputMapper::sync(nsecs_t when) {
5068 static const uint32_t REQUIRED_FIELDS =
Jeff Brown8d608662010-08-30 03:02:23 -07005069 Accumulator::FIELD_ABS_MT_POSITION_X | Accumulator::FIELD_ABS_MT_POSITION_Y;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005070
Jeff Brown6d0fec22010-07-23 21:28:06 -07005071 uint32_t inCount = mAccumulator.pointerCount;
5072 uint32_t outCount = 0;
5073 bool havePointerIds = true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005074
Jeff Brown6d0fec22010-07-23 21:28:06 -07005075 mCurrentTouch.clear();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005076
Jeff Brown6d0fec22010-07-23 21:28:06 -07005077 for (uint32_t inIndex = 0; inIndex < inCount; inIndex++) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005078 const Accumulator::Pointer& inPointer = mAccumulator.pointers[inIndex];
5079 uint32_t fields = inPointer.fields;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005080
Jeff Brown6d0fec22010-07-23 21:28:06 -07005081 if ((fields & REQUIRED_FIELDS) != REQUIRED_FIELDS) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005082 // Some drivers send empty MT sync packets without X / Y to indicate a pointer up.
5083 // Drop this finger.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005084 continue;
5085 }
5086
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005087 PointerData& outPointer = mCurrentTouch.pointers[outCount];
5088 outPointer.x = inPointer.absMTPositionX;
5089 outPointer.y = inPointer.absMTPositionY;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005090
Jeff Brown8d608662010-08-30 03:02:23 -07005091 if (fields & Accumulator::FIELD_ABS_MT_PRESSURE) {
5092 if (inPointer.absMTPressure <= 0) {
Jeff Brownc3db8582010-10-20 15:33:38 -07005093 // Some devices send sync packets with X / Y but with a 0 pressure to indicate
5094 // a pointer going up. Drop this finger.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005095 continue;
5096 }
Jeff Brown8d608662010-08-30 03:02:23 -07005097 outPointer.pressure = inPointer.absMTPressure;
5098 } else {
5099 // Default pressure to 0 if absent.
5100 outPointer.pressure = 0;
5101 }
5102
5103 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MAJOR) {
5104 if (inPointer.absMTTouchMajor <= 0) {
5105 // Some devices send sync packets with X / Y but with a 0 touch major to indicate
5106 // a pointer going up. Drop this finger.
5107 continue;
5108 }
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005109 outPointer.touchMajor = inPointer.absMTTouchMajor;
5110 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005111 // Default touch area to 0 if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005112 outPointer.touchMajor = 0;
5113 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005114
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005115 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MINOR) {
5116 outPointer.touchMinor = inPointer.absMTTouchMinor;
5117 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005118 // Assume touch area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005119 outPointer.touchMinor = outPointer.touchMajor;
5120 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005121
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005122 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MAJOR) {
5123 outPointer.toolMajor = inPointer.absMTWidthMajor;
5124 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005125 // Default tool area to 0 if absent.
5126 outPointer.toolMajor = 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005127 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005128
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005129 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MINOR) {
5130 outPointer.toolMinor = inPointer.absMTWidthMinor;
5131 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005132 // Assume tool area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005133 outPointer.toolMinor = outPointer.toolMajor;
5134 }
5135
5136 if (fields & Accumulator::FIELD_ABS_MT_ORIENTATION) {
5137 outPointer.orientation = inPointer.absMTOrientation;
5138 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005139 // Default orientation to vertical if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005140 outPointer.orientation = 0;
5141 }
5142
Jeff Brown8d608662010-08-30 03:02:23 -07005143 // Assign pointer id using tracking id if available.
Jeff Brown6d0fec22010-07-23 21:28:06 -07005144 if (havePointerIds) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005145 if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) {
5146 uint32_t id = uint32_t(inPointer.absMTTrackingId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005147
Jeff Brown6d0fec22010-07-23 21:28:06 -07005148 if (id > MAX_POINTER_ID) {
5149#if DEBUG_POINTERS
5150 LOGD("Pointers: Ignoring driver provided pointer id %d because "
Jeff Brown01ce2e92010-09-26 22:20:12 -07005151 "it is larger than max supported id %d",
Jeff Brown6d0fec22010-07-23 21:28:06 -07005152 id, MAX_POINTER_ID);
5153#endif
5154 havePointerIds = false;
5155 }
5156 else {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005157 outPointer.id = id;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005158 mCurrentTouch.idToIndex[id] = outCount;
5159 mCurrentTouch.idBits.markBit(id);
5160 }
5161 } else {
5162 havePointerIds = false;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005163 }
5164 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005165
Jeff Brown6d0fec22010-07-23 21:28:06 -07005166 outCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005167 }
5168
Jeff Brown6d0fec22010-07-23 21:28:06 -07005169 mCurrentTouch.pointerCount = outCount;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005170
Jeff Brownace13b12011-03-09 17:39:48 -08005171 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
5172 mCurrentTouch.buttonState = mButtonState;
5173
Jeff Brown6d0fec22010-07-23 21:28:06 -07005174 syncTouch(when, havePointerIds);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005175
5176 mAccumulator.clear();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005177}
5178
Jeff Brown8d608662010-08-30 03:02:23 -07005179void MultiTouchInputMapper::configureRawAxes() {
5180 TouchInputMapper::configureRawAxes();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005181
Jeff Brown8d608662010-08-30 03:02:23 -07005182 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_X, & mRawAxes.x);
5183 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_Y, & mRawAxes.y);
5184 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MAJOR, & mRawAxes.touchMajor);
5185 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MINOR, & mRawAxes.touchMinor);
5186 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MAJOR, & mRawAxes.toolMajor);
5187 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MINOR, & mRawAxes.toolMinor);
5188 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_ORIENTATION, & mRawAxes.orientation);
5189 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_PRESSURE, & mRawAxes.pressure);
Jeff Brown9c3cda02010-06-15 01:31:58 -07005190}
5191
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005192
Jeff Browncb1404e2011-01-15 18:14:15 -08005193// --- JoystickInputMapper ---
5194
5195JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
5196 InputMapper(device) {
Jeff Browncb1404e2011-01-15 18:14:15 -08005197}
5198
5199JoystickInputMapper::~JoystickInputMapper() {
5200}
5201
5202uint32_t JoystickInputMapper::getSources() {
5203 return AINPUT_SOURCE_JOYSTICK;
5204}
5205
5206void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
5207 InputMapper::populateDeviceInfo(info);
5208
Jeff Brown6f2fba42011-02-19 01:08:02 -08005209 for (size_t i = 0; i < mAxes.size(); i++) {
5210 const Axis& axis = mAxes.valueAt(i);
Jeff Brownefd32662011-03-08 15:13:06 -08005211 info->addMotionRange(axis.axisInfo.axis, AINPUT_SOURCE_JOYSTICK,
5212 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08005213 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
Jeff Brownefd32662011-03-08 15:13:06 -08005214 info->addMotionRange(axis.axisInfo.highAxis, AINPUT_SOURCE_JOYSTICK,
5215 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08005216 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005217 }
5218}
5219
5220void JoystickInputMapper::dump(String8& dump) {
5221 dump.append(INDENT2 "Joystick Input Mapper:\n");
5222
Jeff Brown6f2fba42011-02-19 01:08:02 -08005223 dump.append(INDENT3 "Axes:\n");
5224 size_t numAxes = mAxes.size();
5225 for (size_t i = 0; i < numAxes; i++) {
5226 const Axis& axis = mAxes.valueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005227 const char* label = getAxisLabel(axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005228 if (label) {
Jeff Brown85297452011-03-04 13:07:49 -08005229 dump.appendFormat(INDENT4 "%s", label);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005230 } else {
Jeff Brown85297452011-03-04 13:07:49 -08005231 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005232 }
Jeff Brown85297452011-03-04 13:07:49 -08005233 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5234 label = getAxisLabel(axis.axisInfo.highAxis);
5235 if (label) {
5236 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
5237 } else {
5238 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
5239 axis.axisInfo.splitValue);
5240 }
5241 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
5242 dump.append(" (invert)");
5243 }
5244
5245 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f\n",
5246 axis.min, axis.max, axis.flat, axis.fuzz);
5247 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
5248 "highScale=%0.5f, highOffset=%0.5f\n",
5249 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005250 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, rawFlat=%d, rawFuzz=%d\n",
5251 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
5252 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz);
Jeff Browncb1404e2011-01-15 18:14:15 -08005253 }
5254}
5255
5256void JoystickInputMapper::configure() {
5257 InputMapper::configure();
5258
Jeff Brown6f2fba42011-02-19 01:08:02 -08005259 // Collect all axes.
5260 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
5261 RawAbsoluteAxisInfo rawAxisInfo;
5262 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), abs, &rawAxisInfo);
5263 if (rawAxisInfo.valid) {
Jeff Brown85297452011-03-04 13:07:49 -08005264 // Map axis.
5265 AxisInfo axisInfo;
5266 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005267 if (!explicitlyMapped) {
5268 // Axis is not explicitly mapped, will choose a generic axis later.
Jeff Brown85297452011-03-04 13:07:49 -08005269 axisInfo.mode = AxisInfo::MODE_NORMAL;
5270 axisInfo.axis = -1;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005271 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005272
Jeff Brown85297452011-03-04 13:07:49 -08005273 // Apply flat override.
5274 int32_t rawFlat = axisInfo.flatOverride < 0
5275 ? rawAxisInfo.flat : axisInfo.flatOverride;
5276
5277 // Calculate scaling factors and limits.
Jeff Brown6f2fba42011-02-19 01:08:02 -08005278 Axis axis;
Jeff Brown85297452011-03-04 13:07:49 -08005279 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
5280 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
5281 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
5282 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5283 scale, 0.0f, highScale, 0.0f,
5284 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
5285 } else if (isCenteredAxis(axisInfo.axis)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005286 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
5287 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
Jeff Brown85297452011-03-04 13:07:49 -08005288 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5289 scale, offset, scale, offset,
5290 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005291 } else {
5292 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
Jeff Brown85297452011-03-04 13:07:49 -08005293 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5294 scale, 0.0f, scale, 0.0f,
5295 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005296 }
5297
5298 // To eliminate noise while the joystick is at rest, filter out small variations
5299 // in axis values up front.
5300 axis.filter = axis.flat * 0.25f;
5301
5302 mAxes.add(abs, axis);
5303 }
5304 }
5305
5306 // If there are too many axes, start dropping them.
5307 // Prefer to keep explicitly mapped axes.
5308 if (mAxes.size() > PointerCoords::MAX_AXES) {
5309 LOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.",
5310 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
5311 pruneAxes(true);
5312 pruneAxes(false);
5313 }
5314
5315 // Assign generic axis ids to remaining axes.
5316 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
5317 size_t numAxes = mAxes.size();
5318 for (size_t i = 0; i < numAxes; i++) {
5319 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005320 if (axis.axisInfo.axis < 0) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005321 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
5322 && haveAxis(nextGenericAxisId)) {
5323 nextGenericAxisId += 1;
5324 }
5325
5326 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
Jeff Brown85297452011-03-04 13:07:49 -08005327 axis.axisInfo.axis = nextGenericAxisId;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005328 nextGenericAxisId += 1;
5329 } else {
5330 LOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
5331 "have already been assigned to other axes.",
5332 getDeviceName().string(), mAxes.keyAt(i));
5333 mAxes.removeItemsAt(i--);
5334 numAxes -= 1;
5335 }
5336 }
5337 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005338}
5339
Jeff Brown85297452011-03-04 13:07:49 -08005340bool JoystickInputMapper::haveAxis(int32_t axisId) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005341 size_t numAxes = mAxes.size();
5342 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005343 const Axis& axis = mAxes.valueAt(i);
5344 if (axis.axisInfo.axis == axisId
5345 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
5346 && axis.axisInfo.highAxis == axisId)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005347 return true;
5348 }
5349 }
5350 return false;
5351}
Jeff Browncb1404e2011-01-15 18:14:15 -08005352
Jeff Brown6f2fba42011-02-19 01:08:02 -08005353void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
5354 size_t i = mAxes.size();
5355 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
5356 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
5357 continue;
5358 }
5359 LOGI("Discarding joystick '%s' axis %d because there are too many axes.",
5360 getDeviceName().string(), mAxes.keyAt(i));
5361 mAxes.removeItemsAt(i);
5362 }
5363}
5364
5365bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
5366 switch (axis) {
5367 case AMOTION_EVENT_AXIS_X:
5368 case AMOTION_EVENT_AXIS_Y:
5369 case AMOTION_EVENT_AXIS_Z:
5370 case AMOTION_EVENT_AXIS_RX:
5371 case AMOTION_EVENT_AXIS_RY:
5372 case AMOTION_EVENT_AXIS_RZ:
5373 case AMOTION_EVENT_AXIS_HAT_X:
5374 case AMOTION_EVENT_AXIS_HAT_Y:
5375 case AMOTION_EVENT_AXIS_ORIENTATION:
Jeff Brown85297452011-03-04 13:07:49 -08005376 case AMOTION_EVENT_AXIS_RUDDER:
5377 case AMOTION_EVENT_AXIS_WHEEL:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005378 return true;
5379 default:
5380 return false;
5381 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005382}
5383
5384void JoystickInputMapper::reset() {
5385 // Recenter all axes.
5386 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Browncb1404e2011-01-15 18:14:15 -08005387
Jeff Brown6f2fba42011-02-19 01:08:02 -08005388 size_t numAxes = mAxes.size();
5389 for (size_t i = 0; i < numAxes; i++) {
5390 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005391 axis.resetValue();
Jeff Brown6f2fba42011-02-19 01:08:02 -08005392 }
5393
5394 sync(when, true /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005395
5396 InputMapper::reset();
5397}
5398
5399void JoystickInputMapper::process(const RawEvent* rawEvent) {
5400 switch (rawEvent->type) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005401 case EV_ABS: {
5402 ssize_t index = mAxes.indexOfKey(rawEvent->scanCode);
5403 if (index >= 0) {
5404 Axis& axis = mAxes.editValueAt(index);
Jeff Brown85297452011-03-04 13:07:49 -08005405 float newValue, highNewValue;
5406 switch (axis.axisInfo.mode) {
5407 case AxisInfo::MODE_INVERT:
5408 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
5409 * axis.scale + axis.offset;
5410 highNewValue = 0.0f;
5411 break;
5412 case AxisInfo::MODE_SPLIT:
5413 if (rawEvent->value < axis.axisInfo.splitValue) {
5414 newValue = (axis.axisInfo.splitValue - rawEvent->value)
5415 * axis.scale + axis.offset;
5416 highNewValue = 0.0f;
5417 } else if (rawEvent->value > axis.axisInfo.splitValue) {
5418 newValue = 0.0f;
5419 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
5420 * axis.highScale + axis.highOffset;
5421 } else {
5422 newValue = 0.0f;
5423 highNewValue = 0.0f;
5424 }
5425 break;
5426 default:
5427 newValue = rawEvent->value * axis.scale + axis.offset;
5428 highNewValue = 0.0f;
5429 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005430 }
Jeff Brown85297452011-03-04 13:07:49 -08005431 axis.newValue = newValue;
5432 axis.highNewValue = highNewValue;
Jeff Browncb1404e2011-01-15 18:14:15 -08005433 }
5434 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005435 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005436
5437 case EV_SYN:
5438 switch (rawEvent->scanCode) {
5439 case SYN_REPORT:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005440 sync(rawEvent->when, false /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005441 break;
5442 }
5443 break;
5444 }
5445}
5446
Jeff Brown6f2fba42011-02-19 01:08:02 -08005447void JoystickInputMapper::sync(nsecs_t when, bool force) {
Jeff Brown85297452011-03-04 13:07:49 -08005448 if (!filterAxes(force)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005449 return;
Jeff Browncb1404e2011-01-15 18:14:15 -08005450 }
5451
5452 int32_t metaState = mContext->getGlobalMetaState();
5453
Jeff Brown6f2fba42011-02-19 01:08:02 -08005454 PointerCoords pointerCoords;
5455 pointerCoords.clear();
5456
5457 size_t numAxes = mAxes.size();
5458 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005459 const Axis& axis = mAxes.valueAt(i);
5460 pointerCoords.setAxisValue(axis.axisInfo.axis, axis.currentValue);
5461 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5462 pointerCoords.setAxisValue(axis.axisInfo.highAxis, axis.highCurrentValue);
5463 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005464 }
5465
Jeff Brown56194eb2011-03-02 19:23:13 -08005466 // Moving a joystick axis should not wake the devide because joysticks can
5467 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
5468 // button will likely wake the device.
5469 // TODO: Use the input device configuration to control this behavior more finely.
5470 uint32_t policyFlags = 0;
5471
Jeff Brown6f2fba42011-02-19 01:08:02 -08005472 int32_t pointerId = 0;
Jeff Brown56194eb2011-03-02 19:23:13 -08005473 getDispatcher()->notifyMotion(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Jeff Brown6f2fba42011-02-19 01:08:02 -08005474 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
5475 1, &pointerId, &pointerCoords, 0, 0, 0);
Jeff Browncb1404e2011-01-15 18:14:15 -08005476}
5477
Jeff Brown85297452011-03-04 13:07:49 -08005478bool JoystickInputMapper::filterAxes(bool force) {
5479 bool atLeastOneSignificantChange = force;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005480 size_t numAxes = mAxes.size();
5481 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005482 Axis& axis = mAxes.editValueAt(i);
5483 if (force || hasValueChangedSignificantly(axis.filter,
5484 axis.newValue, axis.currentValue, axis.min, axis.max)) {
5485 axis.currentValue = axis.newValue;
5486 atLeastOneSignificantChange = true;
5487 }
5488 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5489 if (force || hasValueChangedSignificantly(axis.filter,
5490 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
5491 axis.highCurrentValue = axis.highNewValue;
5492 atLeastOneSignificantChange = true;
5493 }
5494 }
5495 }
5496 return atLeastOneSignificantChange;
5497}
5498
5499bool JoystickInputMapper::hasValueChangedSignificantly(
5500 float filter, float newValue, float currentValue, float min, float max) {
5501 if (newValue != currentValue) {
5502 // Filter out small changes in value unless the value is converging on the axis
5503 // bounds or center point. This is intended to reduce the amount of information
5504 // sent to applications by particularly noisy joysticks (such as PS3).
5505 if (fabs(newValue - currentValue) > filter
5506 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
5507 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
5508 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
5509 return true;
5510 }
5511 }
5512 return false;
5513}
5514
5515bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
5516 float filter, float newValue, float currentValue, float thresholdValue) {
5517 float newDistance = fabs(newValue - thresholdValue);
5518 if (newDistance < filter) {
5519 float oldDistance = fabs(currentValue - thresholdValue);
5520 if (newDistance < oldDistance) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005521 return true;
5522 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005523 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08005524 return false;
Jeff Browncb1404e2011-01-15 18:14:15 -08005525}
5526
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005527} // namespace android