blob: 59943809e9f2ce9074df865e47fd960bbcced429 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac02010-04-22 18:58:52 -070017#define LOG_TAG "InputReader"
18
19//#define LOG_NDEBUG 0
20
21// Log debug messages for each raw event received from the EventHub.
22#define DEBUG_RAW_EVENTS 0
23
24// Log debug messages about touch screen filtering hacks.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_HACKS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070026
27// Log debug messages about virtual key processing.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_VIRTUAL_KEYS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070029
30// Log debug messages about pointers.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_POINTERS 0
Jeff Brown46b9ac02010-04-22 18:58:52 -070032
Jeff Brown5c225b12010-06-16 01:53:36 -070033// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
Jeff Brown96ad3972011-03-09 17:39:48 -080036// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
Jeff Brownb4ff35d2011-01-02 16:37:43 -080039#include "InputReader.h"
40
Jeff Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -070044
45#include <stddef.h>
Jeff Brown8d608662010-08-30 03:02:23 -070046#include <stdlib.h>
Jeff Brown46b9ac02010-04-22 18:58:52 -070047#include <unistd.h>
Jeff Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -070057namespace android {
58
Jeff Brown96ad3972011-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 Brown86ea1f52011-04-12 22:39:53 -070073static const nsecs_t TAP_INTERVAL = 150 * 1000000; // 150 ms
Jeff Brown96ad3972011-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 Brown86ea1f52011-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 Brown96ad3972011-03-09 17:39:48 -080083
Jeff Brown86ea1f52011-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 Brown96ad3972011-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 Brown86ea1f52011-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 Brown96ad3972011-03-09 17:39:48 -0800114
Jeff Brown46b9ac02010-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 Brown86ea1f52011-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 Brown96ad3972011-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 Brown46b9ac02010-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 Brownfd035822010-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 Brown46b9ac02010-04-22 18:58:52 -0700169};
Jeff Brown9626b142011-03-03 02:09:54 -0800170static const size_t keyCodeRotationMapSize =
Jeff Brown46b9ac02010-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 Brown46b9ac02010-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 Brown86ea1f52011-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 Brown46b9ac02010-04-22 18:58:52 -0700271
Jeff Brown46b9ac02010-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 Brown46b9ac02010-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 Brown68d60752011-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 Brown46b9ac02010-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 Brown68d60752011-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 Browndbf8d272011-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 Brown68d60752011-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 Brown46b9ac02010-04-22 18:58:52 -0700309}
310
Jeff Browndbf8d272011-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:
340 assert(false); // can't happen
341 break;
342 }
343 }
344 count -= batchSize;
345 rawEvent += batchSize;
Jeff Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -0700377 return;
378 }
Jeff Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Browndbf8d272011-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 Browndbf8d272011-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 Brown68d60752011-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 Brown46b9ac02010-04-22 18:58:52 -0700571 }
572 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700573 } // release device registry reader lock
Jeff Brown46b9ac02010-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 Brown68d60752011-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brownf2f48712010-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 Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -0700844
Jeff Browndbf8d272011-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 Browndbf8d272011-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 Brown46b9ac02010-04-22 18:58:52 -0700866
Jeff Brown68d60752011-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 Brown68d60752011-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 Brownfd035822010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown51e7fe72010-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 Brown51e7fe72010-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 Brown51e7fe72010-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:
1425 assert(false);
1426 }
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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -07001482 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001483 break;
Jeff Brownefd32662011-03-08 15:13:06 -08001484 }
Jeff Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -07001504 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001505 break;
Jeff Brown46b9ac02010-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 Brown46b9ac02010-04-22 18:58:52 -07001512 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001513 break;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001514 }
Jeff Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown46b9ac02010-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 Brown86ea1f52011-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 Brown86ea1f52011-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
1660 mAccumulator.clear();
Jeff Brown33bbfd22011-02-24 20:55:35 -08001661
1662 if (vscroll != 0 || hscroll != 0) {
1663 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
1664 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
1665
Jeff Brownefd32662011-03-08 15:13:06 -08001666 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brown33bbfd22011-02-24 20:55:35 -08001667 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
1668 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1669 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001670}
1671
Jeff Brown83c09682010-12-23 17:50:18 -08001672int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brownc3fc2d02010-08-10 15:47:53 -07001673 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
1674 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1675 } else {
1676 return AKEY_STATE_UNKNOWN;
1677 }
1678}
1679
Jeff Brown05dc66a2011-03-02 14:41:58 -08001680void CursorInputMapper::fadePointer() {
1681 { // acquire lock
1682 AutoMutex _l(mLock);
Jeff Brownefd32662011-03-08 15:13:06 -08001683 if (mPointerController != NULL) {
1684 mPointerController->fade();
1685 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001686 } // release lock
1687}
1688
Jeff Brown6d0fec22010-07-23 21:28:06 -07001689
1690// --- TouchInputMapper ---
1691
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001692TouchInputMapper::TouchInputMapper(InputDevice* device) :
1693 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001694 mLocked.surfaceOrientation = -1;
1695 mLocked.surfaceWidth = -1;
1696 mLocked.surfaceHeight = -1;
1697
1698 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001699}
1700
1701TouchInputMapper::~TouchInputMapper() {
1702}
1703
1704uint32_t TouchInputMapper::getSources() {
Jeff Brown96ad3972011-03-09 17:39:48 -08001705 return mTouchSource | mPointerSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001706}
1707
1708void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1709 InputMapper::populateDeviceInfo(info);
1710
Jeff Brown6328cdc2010-07-29 18:18:33 -07001711 { // acquire lock
1712 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001713
Jeff Brown6328cdc2010-07-29 18:18:33 -07001714 // Ensure surface information is up to date so that orientation changes are
1715 // noticed immediately.
Jeff Brownefd32662011-03-08 15:13:06 -08001716 if (!configureSurfaceLocked()) {
1717 return;
1718 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001719
Jeff Brownefd32662011-03-08 15:13:06 -08001720 info->addMotionRange(mLocked.orientedRanges.x);
1721 info->addMotionRange(mLocked.orientedRanges.y);
Jeff Brown8d608662010-08-30 03:02:23 -07001722
1723 if (mLocked.orientedRanges.havePressure) {
Jeff Brownefd32662011-03-08 15:13:06 -08001724 info->addMotionRange(mLocked.orientedRanges.pressure);
Jeff Brown8d608662010-08-30 03:02:23 -07001725 }
1726
1727 if (mLocked.orientedRanges.haveSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001728 info->addMotionRange(mLocked.orientedRanges.size);
Jeff Brown8d608662010-08-30 03:02:23 -07001729 }
1730
Jeff Brownc6d282b2010-10-14 21:42:15 -07001731 if (mLocked.orientedRanges.haveTouchSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001732 info->addMotionRange(mLocked.orientedRanges.touchMajor);
1733 info->addMotionRange(mLocked.orientedRanges.touchMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001734 }
1735
Jeff Brownc6d282b2010-10-14 21:42:15 -07001736 if (mLocked.orientedRanges.haveToolSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001737 info->addMotionRange(mLocked.orientedRanges.toolMajor);
1738 info->addMotionRange(mLocked.orientedRanges.toolMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001739 }
1740
1741 if (mLocked.orientedRanges.haveOrientation) {
Jeff Brownefd32662011-03-08 15:13:06 -08001742 info->addMotionRange(mLocked.orientedRanges.orientation);
Jeff Brown8d608662010-08-30 03:02:23 -07001743 }
Jeff Brown96ad3972011-03-09 17:39:48 -08001744
1745 if (mPointerController != NULL) {
1746 float minX, minY, maxX, maxY;
1747 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
1748 info->addMotionRange(AMOTION_EVENT_AXIS_X, mPointerSource,
1749 minX, maxX, 0.0f, 0.0f);
1750 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mPointerSource,
1751 minY, maxY, 0.0f, 0.0f);
1752 }
1753 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mPointerSource,
1754 0.0f, 1.0f, 0.0f, 0.0f);
1755 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001756 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001757}
1758
Jeff Brownef3d7e82010-09-30 14:33:04 -07001759void TouchInputMapper::dump(String8& dump) {
1760 { // acquire lock
1761 AutoMutex _l(mLock);
1762 dump.append(INDENT2 "Touch Input Mapper:\n");
Jeff Brownef3d7e82010-09-30 14:33:04 -07001763 dumpParameters(dump);
1764 dumpVirtualKeysLocked(dump);
1765 dumpRawAxes(dump);
1766 dumpCalibration(dump);
1767 dumpSurfaceLocked(dump);
Jeff Brownefd32662011-03-08 15:13:06 -08001768
Jeff Brown511ee5f2010-10-18 13:32:20 -07001769 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
Jeff Brownc6d282b2010-10-14 21:42:15 -07001770 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mLocked.xScale);
1771 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mLocked.yScale);
1772 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mLocked.xPrecision);
1773 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mLocked.yPrecision);
1774 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mLocked.geometricScale);
1775 dump.appendFormat(INDENT4 "ToolSizeLinearScale: %0.3f\n", mLocked.toolSizeLinearScale);
1776 dump.appendFormat(INDENT4 "ToolSizeLinearBias: %0.3f\n", mLocked.toolSizeLinearBias);
1777 dump.appendFormat(INDENT4 "ToolSizeAreaScale: %0.3f\n", mLocked.toolSizeAreaScale);
1778 dump.appendFormat(INDENT4 "ToolSizeAreaBias: %0.3f\n", mLocked.toolSizeAreaBias);
1779 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mLocked.pressureScale);
1780 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mLocked.sizeScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001781 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mLocked.orientationScale);
1782
1783 dump.appendFormat(INDENT3 "Last Touch:\n");
1784 dump.appendFormat(INDENT4 "Pointer Count: %d\n", mLastTouch.pointerCount);
Jeff Brown96ad3972011-03-09 17:39:48 -08001785 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", mLastTouch.buttonState);
1786
1787 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
1788 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
1789 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
1790 mLocked.pointerGestureXMovementScale);
1791 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
1792 mLocked.pointerGestureYMovementScale);
1793 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
1794 mLocked.pointerGestureXZoomScale);
1795 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
1796 mLocked.pointerGestureYZoomScale);
Jeff Brown86ea1f52011-04-12 22:39:53 -07001797 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
1798 mLocked.pointerGestureMaxSwipeWidth);
Jeff Brown96ad3972011-03-09 17:39:48 -08001799 }
Jeff Brownef3d7e82010-09-30 14:33:04 -07001800 } // release lock
1801}
1802
Jeff Brown6328cdc2010-07-29 18:18:33 -07001803void TouchInputMapper::initializeLocked() {
1804 mCurrentTouch.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001805 mLastTouch.clear();
1806 mDownTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001807
1808 for (uint32_t i = 0; i < MAX_POINTERS; i++) {
1809 mAveragingTouchFilter.historyStart[i] = 0;
1810 mAveragingTouchFilter.historyEnd[i] = 0;
1811 }
1812
1813 mJumpyTouchFilter.jumpyPointsDropped = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001814
1815 mLocked.currentVirtualKey.down = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001816
1817 mLocked.orientedRanges.havePressure = false;
1818 mLocked.orientedRanges.haveSize = false;
Jeff Brownc6d282b2010-10-14 21:42:15 -07001819 mLocked.orientedRanges.haveTouchSize = false;
1820 mLocked.orientedRanges.haveToolSize = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001821 mLocked.orientedRanges.haveOrientation = false;
Jeff Brown96ad3972011-03-09 17:39:48 -08001822
1823 mPointerGesture.reset();
Jeff Brown8d608662010-08-30 03:02:23 -07001824}
1825
Jeff Brown6d0fec22010-07-23 21:28:06 -07001826void TouchInputMapper::configure() {
1827 InputMapper::configure();
1828
1829 // Configure basic parameters.
Jeff Brown8d608662010-08-30 03:02:23 -07001830 configureParameters();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001831
Jeff Brown83c09682010-12-23 17:50:18 -08001832 // Configure sources.
1833 switch (mParameters.deviceType) {
1834 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Jeff Brownefd32662011-03-08 15:13:06 -08001835 mTouchSource = AINPUT_SOURCE_TOUCHSCREEN;
Jeff Brown96ad3972011-03-09 17:39:48 -08001836 mPointerSource = 0;
Jeff Brown83c09682010-12-23 17:50:18 -08001837 break;
1838 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Jeff Brownefd32662011-03-08 15:13:06 -08001839 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
Jeff Brown96ad3972011-03-09 17:39:48 -08001840 mPointerSource = 0;
1841 break;
1842 case Parameters::DEVICE_TYPE_POINTER:
1843 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
1844 mPointerSource = AINPUT_SOURCE_MOUSE;
Jeff Brown83c09682010-12-23 17:50:18 -08001845 break;
1846 default:
1847 assert(false);
1848 }
1849
Jeff Brown6d0fec22010-07-23 21:28:06 -07001850 // Configure absolute axis information.
Jeff Brown8d608662010-08-30 03:02:23 -07001851 configureRawAxes();
Jeff Brown8d608662010-08-30 03:02:23 -07001852
1853 // Prepare input device calibration.
1854 parseCalibration();
1855 resolveCalibration();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001856
Jeff Brown6328cdc2010-07-29 18:18:33 -07001857 { // acquire lock
1858 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001859
Jeff Brown8d608662010-08-30 03:02:23 -07001860 // Configure surface dimensions and orientation.
Jeff Brown6328cdc2010-07-29 18:18:33 -07001861 configureSurfaceLocked();
1862 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001863}
1864
Jeff Brown8d608662010-08-30 03:02:23 -07001865void TouchInputMapper::configureParameters() {
1866 mParameters.useBadTouchFilter = getPolicy()->filterTouchEvents();
1867 mParameters.useAveragingTouchFilter = getPolicy()->filterTouchEvents();
1868 mParameters.useJumpyTouchFilter = getPolicy()->filterJumpyTouchEvents();
Jeff Brownfe508922011-01-18 15:10:10 -08001869 mParameters.virtualKeyQuietTime = getPolicy()->getVirtualKeyQuietTime();
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001870
Jeff Brown86ea1f52011-04-12 22:39:53 -07001871 // TODO: Make this configurable.
1872 //mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER;
1873 mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
1874
Jeff Brown96ad3972011-03-09 17:39:48 -08001875 if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
1876 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
1877 // The device is a cursor device with a touch pad attached.
1878 // By default don't use the touch pad to move the pointer.
1879 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
1880 } else {
1881 // The device is just a touch pad.
1882 // By default use the touch pad to move the pointer and to perform related gestures.
1883 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
1884 }
1885
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001886 String8 deviceTypeString;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001887 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
1888 deviceTypeString)) {
Jeff Brown58a2da82011-01-25 16:02:22 -08001889 if (deviceTypeString == "touchScreen") {
1890 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brownefd32662011-03-08 15:13:06 -08001891 } else if (deviceTypeString == "touchPad") {
1892 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
Jeff Brown96ad3972011-03-09 17:39:48 -08001893 } else if (deviceTypeString == "pointer") {
1894 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
Jeff Brownefd32662011-03-08 15:13:06 -08001895 } else {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001896 LOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
1897 }
1898 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001899
Jeff Brownefd32662011-03-08 15:13:06 -08001900 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001901 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
1902 mParameters.orientationAware);
1903
Jeff Brownefd32662011-03-08 15:13:06 -08001904 mParameters.associatedDisplayId = mParameters.orientationAware
1905 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
Jeff Brown96ad3972011-03-09 17:39:48 -08001906 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
Jeff Brownefd32662011-03-08 15:13:06 -08001907 ? 0 : -1;
Jeff Brown8d608662010-08-30 03:02:23 -07001908}
1909
Jeff Brownef3d7e82010-09-30 14:33:04 -07001910void TouchInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001911 dump.append(INDENT3 "Parameters:\n");
1912
1913 switch (mParameters.deviceType) {
1914 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
1915 dump.append(INDENT4 "DeviceType: touchScreen\n");
1916 break;
1917 case Parameters::DEVICE_TYPE_TOUCH_PAD:
1918 dump.append(INDENT4 "DeviceType: touchPad\n");
1919 break;
Jeff Brown96ad3972011-03-09 17:39:48 -08001920 case Parameters::DEVICE_TYPE_POINTER:
1921 dump.append(INDENT4 "DeviceType: pointer\n");
1922 break;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001923 default:
1924 assert(false);
1925 }
1926
1927 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1928 mParameters.associatedDisplayId);
1929 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1930 toString(mParameters.orientationAware));
1931
1932 dump.appendFormat(INDENT4 "UseBadTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001933 toString(mParameters.useBadTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001934 dump.appendFormat(INDENT4 "UseAveragingTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001935 toString(mParameters.useAveragingTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001936 dump.appendFormat(INDENT4 "UseJumpyTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001937 toString(mParameters.useJumpyTouchFilter));
Jeff Brownb88102f2010-09-08 11:49:43 -07001938}
1939
Jeff Brown8d608662010-08-30 03:02:23 -07001940void TouchInputMapper::configureRawAxes() {
1941 mRawAxes.x.clear();
1942 mRawAxes.y.clear();
1943 mRawAxes.pressure.clear();
1944 mRawAxes.touchMajor.clear();
1945 mRawAxes.touchMinor.clear();
1946 mRawAxes.toolMajor.clear();
1947 mRawAxes.toolMinor.clear();
1948 mRawAxes.orientation.clear();
1949}
1950
Jeff Brownef3d7e82010-09-30 14:33:04 -07001951void TouchInputMapper::dumpRawAxes(String8& dump) {
1952 dump.append(INDENT3 "Raw Axes:\n");
Jeff Browncb1404e2011-01-15 18:14:15 -08001953 dumpRawAbsoluteAxisInfo(dump, mRawAxes.x, "X");
1954 dumpRawAbsoluteAxisInfo(dump, mRawAxes.y, "Y");
1955 dumpRawAbsoluteAxisInfo(dump, mRawAxes.pressure, "Pressure");
1956 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMajor, "TouchMajor");
1957 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMinor, "TouchMinor");
1958 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMajor, "ToolMajor");
1959 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMinor, "ToolMinor");
1960 dumpRawAbsoluteAxisInfo(dump, mRawAxes.orientation, "Orientation");
Jeff Brown6d0fec22010-07-23 21:28:06 -07001961}
1962
Jeff Brown6328cdc2010-07-29 18:18:33 -07001963bool TouchInputMapper::configureSurfaceLocked() {
Jeff Brown9626b142011-03-03 02:09:54 -08001964 // Ensure we have valid X and Y axes.
1965 if (!mRawAxes.x.valid || !mRawAxes.y.valid) {
1966 LOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
1967 "The device will be inoperable.", getDeviceName().string());
1968 return false;
1969 }
1970
Jeff Brown6d0fec22010-07-23 21:28:06 -07001971 // Update orientation and dimensions if needed.
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001972 int32_t orientation = DISPLAY_ORIENTATION_0;
Jeff Brown9626b142011-03-03 02:09:54 -08001973 int32_t width = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
1974 int32_t height = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001975
1976 if (mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001977 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001978 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
Jeff Brownefd32662011-03-08 15:13:06 -08001979 &mLocked.associatedDisplayWidth, &mLocked.associatedDisplayHeight,
1980 &mLocked.associatedDisplayOrientation)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001981 return false;
1982 }
Jeff Brownefd32662011-03-08 15:13:06 -08001983
1984 // A touch screen inherits the dimensions of the display.
1985 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
1986 width = mLocked.associatedDisplayWidth;
1987 height = mLocked.associatedDisplayHeight;
1988 }
1989
1990 // The device inherits the orientation of the display if it is orientation aware.
1991 if (mParameters.orientationAware) {
1992 orientation = mLocked.associatedDisplayOrientation;
1993 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001994 }
1995
Jeff Brown96ad3972011-03-09 17:39:48 -08001996 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
1997 && mPointerController == NULL) {
1998 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
1999 }
2000
Jeff Brown6328cdc2010-07-29 18:18:33 -07002001 bool orientationChanged = mLocked.surfaceOrientation != orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002002 if (orientationChanged) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002003 mLocked.surfaceOrientation = orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002004 }
2005
Jeff Brown6328cdc2010-07-29 18:18:33 -07002006 bool sizeChanged = mLocked.surfaceWidth != width || mLocked.surfaceHeight != height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002007 if (sizeChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08002008 LOGI("Device reconfigured: id=%d, name='%s', surface size is now %dx%d",
Jeff Brownef3d7e82010-09-30 14:33:04 -07002009 getDeviceId(), getDeviceName().string(), width, height);
Jeff Brown8d608662010-08-30 03:02:23 -07002010
Jeff Brown6328cdc2010-07-29 18:18:33 -07002011 mLocked.surfaceWidth = width;
2012 mLocked.surfaceHeight = height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002013
Jeff Brown8d608662010-08-30 03:02:23 -07002014 // Configure X and Y factors.
Jeff Brown9626b142011-03-03 02:09:54 -08002015 mLocked.xScale = float(width) / (mRawAxes.x.maxValue - mRawAxes.x.minValue + 1);
2016 mLocked.yScale = float(height) / (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1);
2017 mLocked.xPrecision = 1.0f / mLocked.xScale;
2018 mLocked.yPrecision = 1.0f / mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002019
Jeff Brownefd32662011-03-08 15:13:06 -08002020 mLocked.orientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
2021 mLocked.orientedRanges.x.source = mTouchSource;
2022 mLocked.orientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
2023 mLocked.orientedRanges.y.source = mTouchSource;
2024
Jeff Brown9626b142011-03-03 02:09:54 -08002025 configureVirtualKeysLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002026
Jeff Brown8d608662010-08-30 03:02:23 -07002027 // Scale factor for terms that are not oriented in a particular axis.
2028 // If the pixels are square then xScale == yScale otherwise we fake it
2029 // by choosing an average.
2030 mLocked.geometricScale = avg(mLocked.xScale, mLocked.yScale);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002031
Jeff Brown8d608662010-08-30 03:02:23 -07002032 // Size of diagonal axis.
Jeff Brown86ea1f52011-04-12 22:39:53 -07002033 float diagonalSize = hypotf(width, height);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002034
Jeff Brown8d608662010-08-30 03:02:23 -07002035 // TouchMajor and TouchMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002036 if (mCalibration.touchSizeCalibration != Calibration::TOUCH_SIZE_CALIBRATION_NONE) {
2037 mLocked.orientedRanges.haveTouchSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002038
2039 mLocked.orientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
2040 mLocked.orientedRanges.touchMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002041 mLocked.orientedRanges.touchMajor.min = 0;
2042 mLocked.orientedRanges.touchMajor.max = diagonalSize;
2043 mLocked.orientedRanges.touchMajor.flat = 0;
2044 mLocked.orientedRanges.touchMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08002045
Jeff Brown8d608662010-08-30 03:02:23 -07002046 mLocked.orientedRanges.touchMinor = mLocked.orientedRanges.touchMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08002047 mLocked.orientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002048 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002049
Jeff Brown8d608662010-08-30 03:02:23 -07002050 // ToolMajor and ToolMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002051 mLocked.toolSizeLinearScale = 0;
2052 mLocked.toolSizeLinearBias = 0;
2053 mLocked.toolSizeAreaScale = 0;
2054 mLocked.toolSizeAreaBias = 0;
2055 if (mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2056 if (mCalibration.toolSizeCalibration == Calibration::TOOL_SIZE_CALIBRATION_LINEAR) {
2057 if (mCalibration.haveToolSizeLinearScale) {
2058 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
Jeff Brown8d608662010-08-30 03:02:23 -07002059 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002060 mLocked.toolSizeLinearScale = float(min(width, height))
Jeff Brown8d608662010-08-30 03:02:23 -07002061 / mRawAxes.toolMajor.maxValue;
2062 }
2063
Jeff Brownc6d282b2010-10-14 21:42:15 -07002064 if (mCalibration.haveToolSizeLinearBias) {
2065 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2066 }
2067 } else if (mCalibration.toolSizeCalibration ==
2068 Calibration::TOOL_SIZE_CALIBRATION_AREA) {
2069 if (mCalibration.haveToolSizeLinearScale) {
2070 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
2071 } else {
2072 mLocked.toolSizeLinearScale = min(width, height);
2073 }
2074
2075 if (mCalibration.haveToolSizeLinearBias) {
2076 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2077 }
2078
2079 if (mCalibration.haveToolSizeAreaScale) {
2080 mLocked.toolSizeAreaScale = mCalibration.toolSizeAreaScale;
2081 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2082 mLocked.toolSizeAreaScale = 1.0f / mRawAxes.toolMajor.maxValue;
2083 }
2084
2085 if (mCalibration.haveToolSizeAreaBias) {
2086 mLocked.toolSizeAreaBias = mCalibration.toolSizeAreaBias;
Jeff Brown8d608662010-08-30 03:02:23 -07002087 }
2088 }
2089
Jeff Brownc6d282b2010-10-14 21:42:15 -07002090 mLocked.orientedRanges.haveToolSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002091
2092 mLocked.orientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
2093 mLocked.orientedRanges.toolMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002094 mLocked.orientedRanges.toolMajor.min = 0;
2095 mLocked.orientedRanges.toolMajor.max = diagonalSize;
2096 mLocked.orientedRanges.toolMajor.flat = 0;
2097 mLocked.orientedRanges.toolMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08002098
Jeff Brown8d608662010-08-30 03:02:23 -07002099 mLocked.orientedRanges.toolMinor = mLocked.orientedRanges.toolMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08002100 mLocked.orientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002101 }
2102
2103 // Pressure factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002104 mLocked.pressureScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002105 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE) {
2106 RawAbsoluteAxisInfo rawPressureAxis;
2107 switch (mCalibration.pressureSource) {
2108 case Calibration::PRESSURE_SOURCE_PRESSURE:
2109 rawPressureAxis = mRawAxes.pressure;
2110 break;
2111 case Calibration::PRESSURE_SOURCE_TOUCH:
2112 rawPressureAxis = mRawAxes.touchMajor;
2113 break;
2114 default:
2115 rawPressureAxis.clear();
2116 }
2117
Jeff Brown8d608662010-08-30 03:02:23 -07002118 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
2119 || mCalibration.pressureCalibration
2120 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
2121 if (mCalibration.havePressureScale) {
2122 mLocked.pressureScale = mCalibration.pressureScale;
2123 } else if (rawPressureAxis.valid && rawPressureAxis.maxValue != 0) {
2124 mLocked.pressureScale = 1.0f / rawPressureAxis.maxValue;
2125 }
2126 }
2127
2128 mLocked.orientedRanges.havePressure = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002129
2130 mLocked.orientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
2131 mLocked.orientedRanges.pressure.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002132 mLocked.orientedRanges.pressure.min = 0;
2133 mLocked.orientedRanges.pressure.max = 1.0;
2134 mLocked.orientedRanges.pressure.flat = 0;
2135 mLocked.orientedRanges.pressure.fuzz = 0;
2136 }
2137
2138 // Size factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002139 mLocked.sizeScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002140 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002141 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_NORMALIZED) {
2142 if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2143 mLocked.sizeScale = 1.0f / mRawAxes.toolMajor.maxValue;
2144 }
2145 }
2146
2147 mLocked.orientedRanges.haveSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002148
2149 mLocked.orientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
2150 mLocked.orientedRanges.size.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002151 mLocked.orientedRanges.size.min = 0;
2152 mLocked.orientedRanges.size.max = 1.0;
2153 mLocked.orientedRanges.size.flat = 0;
2154 mLocked.orientedRanges.size.fuzz = 0;
2155 }
2156
2157 // Orientation
Jeff Brownc6d282b2010-10-14 21:42:15 -07002158 mLocked.orientationScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002159 if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002160 if (mCalibration.orientationCalibration
2161 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
2162 if (mRawAxes.orientation.valid && mRawAxes.orientation.maxValue != 0) {
2163 mLocked.orientationScale = float(M_PI_2) / mRawAxes.orientation.maxValue;
2164 }
2165 }
2166
Jeff Brownefd32662011-03-08 15:13:06 -08002167 mLocked.orientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
2168 mLocked.orientedRanges.orientation.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002169 mLocked.orientedRanges.orientation.min = - M_PI_2;
2170 mLocked.orientedRanges.orientation.max = M_PI_2;
2171 mLocked.orientedRanges.orientation.flat = 0;
2172 mLocked.orientedRanges.orientation.fuzz = 0;
2173 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002174 }
2175
2176 if (orientationChanged || sizeChanged) {
Jeff Brown9626b142011-03-03 02:09:54 -08002177 // Compute oriented surface dimensions, precision, scales and ranges.
2178 // Note that the maximum value reported is an inclusive maximum value so it is one
2179 // unit less than the total width or height of surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002180 switch (mLocked.surfaceOrientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08002181 case DISPLAY_ORIENTATION_90:
2182 case DISPLAY_ORIENTATION_270:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002183 mLocked.orientedSurfaceWidth = mLocked.surfaceHeight;
2184 mLocked.orientedSurfaceHeight = mLocked.surfaceWidth;
Jeff Brown9626b142011-03-03 02:09:54 -08002185
Jeff Brown6328cdc2010-07-29 18:18:33 -07002186 mLocked.orientedXPrecision = mLocked.yPrecision;
2187 mLocked.orientedYPrecision = mLocked.xPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002188
2189 mLocked.orientedRanges.x.min = 0;
2190 mLocked.orientedRanges.x.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2191 * mLocked.yScale;
2192 mLocked.orientedRanges.x.flat = 0;
2193 mLocked.orientedRanges.x.fuzz = mLocked.yScale;
2194
2195 mLocked.orientedRanges.y.min = 0;
2196 mLocked.orientedRanges.y.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2197 * mLocked.xScale;
2198 mLocked.orientedRanges.y.flat = 0;
2199 mLocked.orientedRanges.y.fuzz = mLocked.xScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002200 break;
Jeff Brown9626b142011-03-03 02:09:54 -08002201
Jeff Brown6d0fec22010-07-23 21:28:06 -07002202 default:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002203 mLocked.orientedSurfaceWidth = mLocked.surfaceWidth;
2204 mLocked.orientedSurfaceHeight = mLocked.surfaceHeight;
Jeff Brown9626b142011-03-03 02:09:54 -08002205
Jeff Brown6328cdc2010-07-29 18:18:33 -07002206 mLocked.orientedXPrecision = mLocked.xPrecision;
2207 mLocked.orientedYPrecision = mLocked.yPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002208
2209 mLocked.orientedRanges.x.min = 0;
2210 mLocked.orientedRanges.x.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2211 * mLocked.xScale;
2212 mLocked.orientedRanges.x.flat = 0;
2213 mLocked.orientedRanges.x.fuzz = mLocked.xScale;
2214
2215 mLocked.orientedRanges.y.min = 0;
2216 mLocked.orientedRanges.y.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2217 * mLocked.yScale;
2218 mLocked.orientedRanges.y.flat = 0;
2219 mLocked.orientedRanges.y.fuzz = mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002220 break;
2221 }
Jeff Brown96ad3972011-03-09 17:39:48 -08002222
2223 // Compute pointer gesture detection parameters.
2224 // TODO: These factors should not be hardcoded.
2225 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
2226 int32_t rawWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2227 int32_t rawHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown86ea1f52011-04-12 22:39:53 -07002228 float rawDiagonal = hypotf(rawWidth, rawHeight);
2229 float displayDiagonal = hypotf(mLocked.associatedDisplayWidth,
2230 mLocked.associatedDisplayHeight);
Jeff Brown96ad3972011-03-09 17:39:48 -08002231
Jeff Brown86ea1f52011-04-12 22:39:53 -07002232 // Scale movements such that one whole swipe of the touch pad covers a
2233 // given area relative to the diagonal size of the display.
Jeff Brown96ad3972011-03-09 17:39:48 -08002234 // Assume that the touch pad has a square aspect ratio such that movements in
2235 // X and Y of the same number of raw units cover the same physical distance.
2236 const float scaleFactor = 0.8f;
2237
Jeff Brown86ea1f52011-04-12 22:39:53 -07002238 mLocked.pointerGestureXMovementScale = GESTURE_MOVEMENT_SPEED_RATIO
2239 * displayDiagonal / rawDiagonal;
Jeff Brown96ad3972011-03-09 17:39:48 -08002240 mLocked.pointerGestureYMovementScale = mLocked.pointerGestureXMovementScale;
2241
2242 // Scale zooms to cover a smaller range of the display than movements do.
2243 // This value determines the area around the pointer that is affected by freeform
2244 // pointer gestures.
Jeff Brown86ea1f52011-04-12 22:39:53 -07002245 mLocked.pointerGestureXZoomScale = GESTURE_ZOOM_SPEED_RATIO
2246 * displayDiagonal / rawDiagonal;
2247 mLocked.pointerGestureYZoomScale = mLocked.pointerGestureXZoomScale;
Jeff Brown96ad3972011-03-09 17:39:48 -08002248
Jeff Brown86ea1f52011-04-12 22:39:53 -07002249 // Max width between pointers to detect a swipe gesture is more than some fraction
2250 // of the diagonal axis of the touch pad. Touches that are wider than this are
2251 // translated into freeform gestures.
2252 mLocked.pointerGestureMaxSwipeWidth = SWIPE_MAX_WIDTH_RATIO * rawDiagonal;
2253
2254 // Reset the current pointer gesture.
2255 mPointerGesture.reset();
2256
2257 // Remove any current spots.
2258 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
2259 mPointerController->clearSpots();
2260 }
Jeff Brown96ad3972011-03-09 17:39:48 -08002261 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002262 }
2263
2264 return true;
2265}
2266
Jeff Brownef3d7e82010-09-30 14:33:04 -07002267void TouchInputMapper::dumpSurfaceLocked(String8& dump) {
2268 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mLocked.surfaceWidth);
2269 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mLocked.surfaceHeight);
2270 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mLocked.surfaceOrientation);
Jeff Brownb88102f2010-09-08 11:49:43 -07002271}
2272
Jeff Brown6328cdc2010-07-29 18:18:33 -07002273void TouchInputMapper::configureVirtualKeysLocked() {
Jeff Brown8d608662010-08-30 03:02:23 -07002274 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
Jeff Brown90655042010-12-02 13:50:46 -08002275 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002276
Jeff Brown6328cdc2010-07-29 18:18:33 -07002277 mLocked.virtualKeys.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002278
Jeff Brown6328cdc2010-07-29 18:18:33 -07002279 if (virtualKeyDefinitions.size() == 0) {
2280 return;
2281 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002282
Jeff Brown6328cdc2010-07-29 18:18:33 -07002283 mLocked.virtualKeys.setCapacity(virtualKeyDefinitions.size());
2284
Jeff Brown8d608662010-08-30 03:02:23 -07002285 int32_t touchScreenLeft = mRawAxes.x.minValue;
2286 int32_t touchScreenTop = mRawAxes.y.minValue;
Jeff Brown9626b142011-03-03 02:09:54 -08002287 int32_t touchScreenWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2288 int32_t touchScreenHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002289
2290 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002291 const VirtualKeyDefinition& virtualKeyDefinition =
Jeff Brown6328cdc2010-07-29 18:18:33 -07002292 virtualKeyDefinitions[i];
2293
2294 mLocked.virtualKeys.add();
2295 VirtualKey& virtualKey = mLocked.virtualKeys.editTop();
2296
2297 virtualKey.scanCode = virtualKeyDefinition.scanCode;
2298 int32_t keyCode;
2299 uint32_t flags;
Jeff Brown6f2fba42011-02-19 01:08:02 -08002300 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode,
Jeff Brown6328cdc2010-07-29 18:18:33 -07002301 & keyCode, & flags)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002302 LOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
2303 virtualKey.scanCode);
Jeff Brown6328cdc2010-07-29 18:18:33 -07002304 mLocked.virtualKeys.pop(); // drop the key
2305 continue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002306 }
2307
Jeff Brown6328cdc2010-07-29 18:18:33 -07002308 virtualKey.keyCode = keyCode;
2309 virtualKey.flags = flags;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002310
Jeff Brown6328cdc2010-07-29 18:18:33 -07002311 // convert the key definition's display coordinates into touch coordinates for a hit box
2312 int32_t halfWidth = virtualKeyDefinition.width / 2;
2313 int32_t halfHeight = virtualKeyDefinition.height / 2;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002314
Jeff Brown6328cdc2010-07-29 18:18:33 -07002315 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
2316 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2317 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
2318 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2319 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
2320 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
2321 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
2322 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
Jeff Brownef3d7e82010-09-30 14:33:04 -07002323 }
2324}
2325
2326void TouchInputMapper::dumpVirtualKeysLocked(String8& dump) {
2327 if (!mLocked.virtualKeys.isEmpty()) {
2328 dump.append(INDENT3 "Virtual Keys:\n");
2329
2330 for (size_t i = 0; i < mLocked.virtualKeys.size(); i++) {
2331 const VirtualKey& virtualKey = mLocked.virtualKeys.itemAt(i);
2332 dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, "
2333 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
2334 i, virtualKey.scanCode, virtualKey.keyCode,
2335 virtualKey.hitLeft, virtualKey.hitRight,
2336 virtualKey.hitTop, virtualKey.hitBottom);
2337 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002338 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002339}
2340
Jeff Brown8d608662010-08-30 03:02:23 -07002341void TouchInputMapper::parseCalibration() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002342 const PropertyMap& in = getDevice()->getConfiguration();
Jeff Brown8d608662010-08-30 03:02:23 -07002343 Calibration& out = mCalibration;
2344
Jeff Brownc6d282b2010-10-14 21:42:15 -07002345 // Touch Size
2346 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT;
2347 String8 touchSizeCalibrationString;
2348 if (in.tryGetProperty(String8("touch.touchSize.calibration"), touchSizeCalibrationString)) {
2349 if (touchSizeCalibrationString == "none") {
2350 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
2351 } else if (touchSizeCalibrationString == "geometric") {
2352 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC;
2353 } else if (touchSizeCalibrationString == "pressure") {
2354 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
2355 } else if (touchSizeCalibrationString != "default") {
2356 LOGW("Invalid value for touch.touchSize.calibration: '%s'",
2357 touchSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002358 }
2359 }
2360
Jeff Brownc6d282b2010-10-14 21:42:15 -07002361 // Tool Size
2362 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_DEFAULT;
2363 String8 toolSizeCalibrationString;
2364 if (in.tryGetProperty(String8("touch.toolSize.calibration"), toolSizeCalibrationString)) {
2365 if (toolSizeCalibrationString == "none") {
2366 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
2367 } else if (toolSizeCalibrationString == "geometric") {
2368 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC;
2369 } else if (toolSizeCalibrationString == "linear") {
2370 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
2371 } else if (toolSizeCalibrationString == "area") {
2372 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_AREA;
2373 } else if (toolSizeCalibrationString != "default") {
2374 LOGW("Invalid value for touch.toolSize.calibration: '%s'",
2375 toolSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002376 }
2377 }
2378
Jeff Brownc6d282b2010-10-14 21:42:15 -07002379 out.haveToolSizeLinearScale = in.tryGetProperty(String8("touch.toolSize.linearScale"),
2380 out.toolSizeLinearScale);
2381 out.haveToolSizeLinearBias = in.tryGetProperty(String8("touch.toolSize.linearBias"),
2382 out.toolSizeLinearBias);
2383 out.haveToolSizeAreaScale = in.tryGetProperty(String8("touch.toolSize.areaScale"),
2384 out.toolSizeAreaScale);
2385 out.haveToolSizeAreaBias = in.tryGetProperty(String8("touch.toolSize.areaBias"),
2386 out.toolSizeAreaBias);
2387 out.haveToolSizeIsSummed = in.tryGetProperty(String8("touch.toolSize.isSummed"),
2388 out.toolSizeIsSummed);
Jeff Brown8d608662010-08-30 03:02:23 -07002389
2390 // Pressure
2391 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
2392 String8 pressureCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002393 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002394 if (pressureCalibrationString == "none") {
2395 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2396 } else if (pressureCalibrationString == "physical") {
2397 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
2398 } else if (pressureCalibrationString == "amplitude") {
2399 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2400 } else if (pressureCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002401 LOGW("Invalid value for touch.pressure.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002402 pressureCalibrationString.string());
2403 }
2404 }
2405
2406 out.pressureSource = Calibration::PRESSURE_SOURCE_DEFAULT;
2407 String8 pressureSourceString;
2408 if (in.tryGetProperty(String8("touch.pressure.source"), pressureSourceString)) {
2409 if (pressureSourceString == "pressure") {
2410 out.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2411 } else if (pressureSourceString == "touch") {
2412 out.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2413 } else if (pressureSourceString != "default") {
2414 LOGW("Invalid value for touch.pressure.source: '%s'",
2415 pressureSourceString.string());
2416 }
2417 }
2418
2419 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
2420 out.pressureScale);
2421
2422 // Size
2423 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
2424 String8 sizeCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002425 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002426 if (sizeCalibrationString == "none") {
2427 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2428 } else if (sizeCalibrationString == "normalized") {
2429 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2430 } else if (sizeCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002431 LOGW("Invalid value for touch.size.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002432 sizeCalibrationString.string());
2433 }
2434 }
2435
2436 // Orientation
2437 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
2438 String8 orientationCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002439 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002440 if (orientationCalibrationString == "none") {
2441 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2442 } else if (orientationCalibrationString == "interpolated") {
2443 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002444 } else if (orientationCalibrationString == "vector") {
2445 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002446 } else if (orientationCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002447 LOGW("Invalid value for touch.orientation.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002448 orientationCalibrationString.string());
2449 }
2450 }
2451}
2452
2453void TouchInputMapper::resolveCalibration() {
2454 // Pressure
2455 switch (mCalibration.pressureSource) {
2456 case Calibration::PRESSURE_SOURCE_DEFAULT:
2457 if (mRawAxes.pressure.valid) {
2458 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2459 } else if (mRawAxes.touchMajor.valid) {
2460 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2461 }
2462 break;
2463
2464 case Calibration::PRESSURE_SOURCE_PRESSURE:
2465 if (! mRawAxes.pressure.valid) {
2466 LOGW("Calibration property touch.pressure.source is 'pressure' but "
2467 "the pressure axis is not available.");
2468 }
2469 break;
2470
2471 case Calibration::PRESSURE_SOURCE_TOUCH:
2472 if (! mRawAxes.touchMajor.valid) {
2473 LOGW("Calibration property touch.pressure.source is 'touch' but "
2474 "the touchMajor axis is not available.");
2475 }
2476 break;
2477
2478 default:
2479 break;
2480 }
2481
2482 switch (mCalibration.pressureCalibration) {
2483 case Calibration::PRESSURE_CALIBRATION_DEFAULT:
2484 if (mCalibration.pressureSource != Calibration::PRESSURE_SOURCE_DEFAULT) {
2485 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2486 } else {
2487 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2488 }
2489 break;
2490
2491 default:
2492 break;
2493 }
2494
Jeff Brownc6d282b2010-10-14 21:42:15 -07002495 // Tool Size
2496 switch (mCalibration.toolSizeCalibration) {
2497 case Calibration::TOOL_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002498 if (mRawAxes.toolMajor.valid) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002499 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
Jeff Brown8d608662010-08-30 03:02:23 -07002500 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002501 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002502 }
2503 break;
2504
2505 default:
2506 break;
2507 }
2508
Jeff Brownc6d282b2010-10-14 21:42:15 -07002509 // Touch Size
2510 switch (mCalibration.touchSizeCalibration) {
2511 case Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002512 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE
Jeff Brownc6d282b2010-10-14 21:42:15 -07002513 && mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2514 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
Jeff Brown8d608662010-08-30 03:02:23 -07002515 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002516 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002517 }
2518 break;
2519
2520 default:
2521 break;
2522 }
2523
2524 // Size
2525 switch (mCalibration.sizeCalibration) {
2526 case Calibration::SIZE_CALIBRATION_DEFAULT:
2527 if (mRawAxes.toolMajor.valid) {
2528 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2529 } else {
2530 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2531 }
2532 break;
2533
2534 default:
2535 break;
2536 }
2537
2538 // Orientation
2539 switch (mCalibration.orientationCalibration) {
2540 case Calibration::ORIENTATION_CALIBRATION_DEFAULT:
2541 if (mRawAxes.orientation.valid) {
2542 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
2543 } else {
2544 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2545 }
2546 break;
2547
2548 default:
2549 break;
2550 }
2551}
2552
Jeff Brownef3d7e82010-09-30 14:33:04 -07002553void TouchInputMapper::dumpCalibration(String8& dump) {
2554 dump.append(INDENT3 "Calibration:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002555
Jeff Brownc6d282b2010-10-14 21:42:15 -07002556 // Touch Size
2557 switch (mCalibration.touchSizeCalibration) {
2558 case Calibration::TOUCH_SIZE_CALIBRATION_NONE:
2559 dump.append(INDENT4 "touch.touchSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002560 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002561 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
2562 dump.append(INDENT4 "touch.touchSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002563 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002564 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
2565 dump.append(INDENT4 "touch.touchSize.calibration: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002566 break;
2567 default:
2568 assert(false);
2569 }
2570
Jeff Brownc6d282b2010-10-14 21:42:15 -07002571 // Tool Size
2572 switch (mCalibration.toolSizeCalibration) {
2573 case Calibration::TOOL_SIZE_CALIBRATION_NONE:
2574 dump.append(INDENT4 "touch.toolSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002575 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002576 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
2577 dump.append(INDENT4 "touch.toolSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002578 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002579 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
2580 dump.append(INDENT4 "touch.toolSize.calibration: linear\n");
2581 break;
2582 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
2583 dump.append(INDENT4 "touch.toolSize.calibration: area\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002584 break;
2585 default:
2586 assert(false);
2587 }
2588
Jeff Brownc6d282b2010-10-14 21:42:15 -07002589 if (mCalibration.haveToolSizeLinearScale) {
2590 dump.appendFormat(INDENT4 "touch.toolSize.linearScale: %0.3f\n",
2591 mCalibration.toolSizeLinearScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002592 }
2593
Jeff Brownc6d282b2010-10-14 21:42:15 -07002594 if (mCalibration.haveToolSizeLinearBias) {
2595 dump.appendFormat(INDENT4 "touch.toolSize.linearBias: %0.3f\n",
2596 mCalibration.toolSizeLinearBias);
Jeff Brown8d608662010-08-30 03:02:23 -07002597 }
2598
Jeff Brownc6d282b2010-10-14 21:42:15 -07002599 if (mCalibration.haveToolSizeAreaScale) {
2600 dump.appendFormat(INDENT4 "touch.toolSize.areaScale: %0.3f\n",
2601 mCalibration.toolSizeAreaScale);
2602 }
2603
2604 if (mCalibration.haveToolSizeAreaBias) {
2605 dump.appendFormat(INDENT4 "touch.toolSize.areaBias: %0.3f\n",
2606 mCalibration.toolSizeAreaBias);
2607 }
2608
2609 if (mCalibration.haveToolSizeIsSummed) {
Jeff Brown1f245102010-11-18 20:53:46 -08002610 dump.appendFormat(INDENT4 "touch.toolSize.isSummed: %s\n",
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002611 toString(mCalibration.toolSizeIsSummed));
Jeff Brown8d608662010-08-30 03:02:23 -07002612 }
2613
2614 // Pressure
2615 switch (mCalibration.pressureCalibration) {
2616 case Calibration::PRESSURE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002617 dump.append(INDENT4 "touch.pressure.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002618 break;
2619 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002620 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002621 break;
2622 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002623 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002624 break;
2625 default:
2626 assert(false);
2627 }
2628
2629 switch (mCalibration.pressureSource) {
2630 case Calibration::PRESSURE_SOURCE_PRESSURE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002631 dump.append(INDENT4 "touch.pressure.source: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002632 break;
2633 case Calibration::PRESSURE_SOURCE_TOUCH:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002634 dump.append(INDENT4 "touch.pressure.source: touch\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002635 break;
2636 case Calibration::PRESSURE_SOURCE_DEFAULT:
2637 break;
2638 default:
2639 assert(false);
2640 }
2641
2642 if (mCalibration.havePressureScale) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07002643 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
2644 mCalibration.pressureScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002645 }
2646
2647 // Size
2648 switch (mCalibration.sizeCalibration) {
2649 case Calibration::SIZE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002650 dump.append(INDENT4 "touch.size.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002651 break;
2652 case Calibration::SIZE_CALIBRATION_NORMALIZED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002653 dump.append(INDENT4 "touch.size.calibration: normalized\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002654 break;
2655 default:
2656 assert(false);
2657 }
2658
2659 // Orientation
2660 switch (mCalibration.orientationCalibration) {
2661 case Calibration::ORIENTATION_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002662 dump.append(INDENT4 "touch.orientation.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002663 break;
2664 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002665 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002666 break;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002667 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
2668 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
2669 break;
Jeff Brown8d608662010-08-30 03:02:23 -07002670 default:
2671 assert(false);
2672 }
2673}
2674
Jeff Brown6d0fec22010-07-23 21:28:06 -07002675void TouchInputMapper::reset() {
2676 // Synthesize touch up event if touch is currently down.
2677 // This will also take care of finishing virtual key processing if needed.
2678 if (mLastTouch.pointerCount != 0) {
2679 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
2680 mCurrentTouch.clear();
2681 syncTouch(when, true);
2682 }
2683
Jeff Brown6328cdc2010-07-29 18:18:33 -07002684 { // acquire lock
2685 AutoMutex _l(mLock);
2686 initializeLocked();
Jeff Brown86ea1f52011-04-12 22:39:53 -07002687
2688 if (mPointerController != NULL
2689 && mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
2690 mPointerController->clearSpots();
2691 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002692 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002693
Jeff Brown6328cdc2010-07-29 18:18:33 -07002694 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002695}
2696
2697void TouchInputMapper::syncTouch(nsecs_t when, bool havePointerIds) {
Jeff Brown68d60752011-03-17 01:34:19 -07002698#if DEBUG_RAW_EVENTS
2699 if (!havePointerIds) {
2700 LOGD("syncTouch: pointerCount=%d, no pointer ids", mCurrentTouch.pointerCount);
2701 } else {
2702 LOGD("syncTouch: pointerCount=%d, up=0x%08x, down=0x%08x, move=0x%08x, "
2703 "last=0x%08x, current=0x%08x", mCurrentTouch.pointerCount,
2704 mLastTouch.idBits.value & ~mCurrentTouch.idBits.value,
2705 mCurrentTouch.idBits.value & ~mLastTouch.idBits.value,
2706 mLastTouch.idBits.value & mCurrentTouch.idBits.value,
2707 mLastTouch.idBits.value, mCurrentTouch.idBits.value);
2708 }
2709#endif
2710
Jeff Brown6328cdc2010-07-29 18:18:33 -07002711 // Preprocess pointer data.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002712 if (mParameters.useBadTouchFilter) {
2713 if (applyBadTouchFilter()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002714 havePointerIds = false;
2715 }
2716 }
2717
Jeff Brown6d0fec22010-07-23 21:28:06 -07002718 if (mParameters.useJumpyTouchFilter) {
2719 if (applyJumpyTouchFilter()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002720 havePointerIds = false;
2721 }
2722 }
2723
Jeff Brown68d60752011-03-17 01:34:19 -07002724 if (!havePointerIds) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002725 calculatePointerIds();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002726 }
2727
Jeff Brown6d0fec22010-07-23 21:28:06 -07002728 TouchData temp;
2729 TouchData* savedTouch;
2730 if (mParameters.useAveragingTouchFilter) {
2731 temp.copyFrom(mCurrentTouch);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002732 savedTouch = & temp;
2733
Jeff Brown6d0fec22010-07-23 21:28:06 -07002734 applyAveragingTouchFilter();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002735 } else {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002736 savedTouch = & mCurrentTouch;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002737 }
2738
Jeff Brown56194eb2011-03-02 19:23:13 -08002739 uint32_t policyFlags = 0;
Jeff Brown05dc66a2011-03-02 14:41:58 -08002740 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
Jeff Brownefd32662011-03-08 15:13:06 -08002741 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
2742 // If this is a touch screen, hide the pointer on an initial down.
2743 getContext()->fadePointer();
2744 }
Jeff Brown56194eb2011-03-02 19:23:13 -08002745
2746 // Initial downs on external touch devices should wake the device.
2747 // We don't do this for internal touch screens to prevent them from waking
2748 // up in your pocket.
2749 // TODO: Use the input device configuration to control this behavior more finely.
2750 if (getDevice()->isExternal()) {
2751 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
2752 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08002753 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002754
Jeff Brown05dc66a2011-03-02 14:41:58 -08002755 // Process touches and virtual keys.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002756 TouchResult touchResult = consumeOffScreenTouches(when, policyFlags);
2757 if (touchResult == DISPATCH_TOUCH) {
Jeff Brownefd32662011-03-08 15:13:06 -08002758 suppressSwipeOntoVirtualKeys(when);
Jeff Brown96ad3972011-03-09 17:39:48 -08002759 if (mPointerController != NULL) {
2760 dispatchPointerGestures(when, policyFlags);
2761 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002762 dispatchTouches(when, policyFlags);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002763 }
2764
Jeff Brown6328cdc2010-07-29 18:18:33 -07002765 // Copy current touch to last touch in preparation for the next cycle.
Jeff Brown96ad3972011-03-09 17:39:48 -08002766 // Keep the button state so we can track edge-triggered button state changes.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002767 if (touchResult == DROP_STROKE) {
2768 mLastTouch.clear();
Jeff Brown96ad3972011-03-09 17:39:48 -08002769 mLastTouch.buttonState = savedTouch->buttonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002770 } else {
2771 mLastTouch.copyFrom(*savedTouch);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002772 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002773}
2774
Jeff Brown6d0fec22010-07-23 21:28:06 -07002775TouchInputMapper::TouchResult TouchInputMapper::consumeOffScreenTouches(
2776 nsecs_t when, uint32_t policyFlags) {
2777 int32_t keyEventAction, keyEventFlags;
2778 int32_t keyCode, scanCode, downTime;
2779 TouchResult touchResult;
Jeff Brown349703e2010-06-22 01:27:15 -07002780
Jeff Brown6328cdc2010-07-29 18:18:33 -07002781 { // acquire lock
2782 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002783
Jeff Brown6328cdc2010-07-29 18:18:33 -07002784 // Update surface size and orientation, including virtual key positions.
2785 if (! configureSurfaceLocked()) {
2786 return DROP_STROKE;
2787 }
2788
2789 // Check for virtual key press.
2790 if (mLocked.currentVirtualKey.down) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002791 if (mCurrentTouch.pointerCount == 0) {
2792 // Pointer went up while virtual key was down.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002793 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002794#if DEBUG_VIRTUAL_KEYS
2795 LOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002796 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002797#endif
2798 keyEventAction = AKEY_EVENT_ACTION_UP;
2799 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2800 touchResult = SKIP_TOUCH;
2801 goto DispatchVirtualKey;
2802 }
2803
2804 if (mCurrentTouch.pointerCount == 1) {
2805 int32_t x = mCurrentTouch.pointers[0].x;
2806 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002807 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
2808 if (virtualKey && virtualKey->keyCode == mLocked.currentVirtualKey.keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002809 // Pointer is still within the space of the virtual key.
2810 return SKIP_TOUCH;
2811 }
2812 }
2813
2814 // Pointer left virtual key area or another pointer also went down.
2815 // Send key cancellation and drop the stroke so subsequent motions will be
2816 // considered fresh downs. This is useful when the user swipes away from the
2817 // virtual key area into the main display surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002818 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002819#if DEBUG_VIRTUAL_KEYS
2820 LOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002821 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002822#endif
2823 keyEventAction = AKEY_EVENT_ACTION_UP;
2824 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
2825 | AKEY_EVENT_FLAG_CANCELED;
Jeff Brownc3db8582010-10-20 15:33:38 -07002826
2827 // Check whether the pointer moved inside the display area where we should
2828 // start a new stroke.
2829 int32_t x = mCurrentTouch.pointers[0].x;
2830 int32_t y = mCurrentTouch.pointers[0].y;
2831 if (isPointInsideSurfaceLocked(x, y)) {
2832 mLastTouch.clear();
2833 touchResult = DISPATCH_TOUCH;
2834 } else {
2835 touchResult = DROP_STROKE;
2836 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002837 } else {
2838 if (mCurrentTouch.pointerCount >= 1 && mLastTouch.pointerCount == 0) {
2839 // Pointer just went down. Handle off-screen touches, if needed.
2840 int32_t x = mCurrentTouch.pointers[0].x;
2841 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002842 if (! isPointInsideSurfaceLocked(x, y)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002843 // If exactly one pointer went down, check for virtual key hit.
2844 // Otherwise we will drop the entire stroke.
2845 if (mCurrentTouch.pointerCount == 1) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002846 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002847 if (virtualKey) {
Jeff Brownfe508922011-01-18 15:10:10 -08002848 if (mContext->shouldDropVirtualKey(when, getDevice(),
2849 virtualKey->keyCode, virtualKey->scanCode)) {
2850 return DROP_STROKE;
2851 }
2852
Jeff Brown6328cdc2010-07-29 18:18:33 -07002853 mLocked.currentVirtualKey.down = true;
2854 mLocked.currentVirtualKey.downTime = when;
2855 mLocked.currentVirtualKey.keyCode = virtualKey->keyCode;
2856 mLocked.currentVirtualKey.scanCode = virtualKey->scanCode;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002857#if DEBUG_VIRTUAL_KEYS
2858 LOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002859 mLocked.currentVirtualKey.keyCode,
2860 mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002861#endif
2862 keyEventAction = AKEY_EVENT_ACTION_DOWN;
2863 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM
2864 | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2865 touchResult = SKIP_TOUCH;
2866 goto DispatchVirtualKey;
2867 }
2868 }
2869 return DROP_STROKE;
2870 }
2871 }
2872 return DISPATCH_TOUCH;
2873 }
2874
2875 DispatchVirtualKey:
2876 // Collect remaining state needed to dispatch virtual key.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002877 keyCode = mLocked.currentVirtualKey.keyCode;
2878 scanCode = mLocked.currentVirtualKey.scanCode;
2879 downTime = mLocked.currentVirtualKey.downTime;
2880 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002881
2882 // Dispatch virtual key.
2883 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown0eaf3932010-10-01 14:55:30 -07002884 policyFlags |= POLICY_FLAG_VIRTUAL;
Jeff Brownb6997262010-10-08 22:31:17 -07002885 getDispatcher()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
2886 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
2887 return touchResult;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002888}
2889
Jeff Brownefd32662011-03-08 15:13:06 -08002890void TouchInputMapper::suppressSwipeOntoVirtualKeys(nsecs_t when) {
Jeff Brownfe508922011-01-18 15:10:10 -08002891 // Disable all virtual key touches that happen within a short time interval of the
2892 // most recent touch. The idea is to filter out stray virtual key presses when
2893 // interacting with the touch screen.
2894 //
2895 // Problems we're trying to solve:
2896 //
2897 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
2898 // virtual key area that is implemented by a separate touch panel and accidentally
2899 // triggers a virtual key.
2900 //
2901 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
2902 // area and accidentally triggers a virtual key. This often happens when virtual keys
2903 // are layed out below the screen near to where the on screen keyboard's space bar
2904 // is displayed.
2905 if (mParameters.virtualKeyQuietTime > 0 && mCurrentTouch.pointerCount != 0) {
2906 mContext->disableVirtualKeysUntil(when + mParameters.virtualKeyQuietTime);
2907 }
2908}
2909
Jeff Brown6d0fec22010-07-23 21:28:06 -07002910void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
2911 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
2912 uint32_t lastPointerCount = mLastTouch.pointerCount;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002913 if (currentPointerCount == 0 && lastPointerCount == 0) {
2914 return; // nothing to do!
2915 }
2916
Jeff Brown96ad3972011-03-09 17:39:48 -08002917 // Update current touch coordinates.
2918 int32_t edgeFlags;
2919 float xPrecision, yPrecision;
2920 prepareTouches(&edgeFlags, &xPrecision, &yPrecision);
2921
2922 // Dispatch motions.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002923 BitSet32 currentIdBits = mCurrentTouch.idBits;
2924 BitSet32 lastIdBits = mLastTouch.idBits;
Jeff Brown96ad3972011-03-09 17:39:48 -08002925 uint32_t metaState = getContext()->getGlobalMetaState();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002926
2927 if (currentIdBits == lastIdBits) {
2928 // No pointer id changes so this is a move event.
2929 // The dispatcher takes care of batching moves so we don't have to deal with that here.
Jeff Brown96ad3972011-03-09 17:39:48 -08002930 dispatchMotion(when, policyFlags, mTouchSource,
2931 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
2932 mCurrentTouchCoords, mCurrentTouch.idToIndex, currentIdBits, -1,
2933 xPrecision, yPrecision, mDownTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002934 } else {
Jeff Brownc3db8582010-10-20 15:33:38 -07002935 // There may be pointers going up and pointers going down and pointers moving
2936 // all at the same time.
Jeff Brown96ad3972011-03-09 17:39:48 -08002937 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2938 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002939 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
Jeff Brown96ad3972011-03-09 17:39:48 -08002940 BitSet32 dispatchedIdBits(lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002941
Jeff Brown96ad3972011-03-09 17:39:48 -08002942 // Update last coordinates of pointers that have moved so that we observe the new
2943 // pointer positions at the same time as other pointers that have just gone up.
2944 bool moveNeeded = updateMovedPointerCoords(
2945 mCurrentTouchCoords, mCurrentTouch.idToIndex,
2946 mLastTouchCoords, mLastTouch.idToIndex,
2947 moveIdBits);
Jeff Brownc3db8582010-10-20 15:33:38 -07002948
Jeff Brown96ad3972011-03-09 17:39:48 -08002949 // Dispatch pointer up events.
Jeff Brownc3db8582010-10-20 15:33:38 -07002950 while (!upIdBits.isEmpty()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002951 uint32_t upId = upIdBits.firstMarkedBit();
2952 upIdBits.clearBit(upId);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002953
Jeff Brown96ad3972011-03-09 17:39:48 -08002954 dispatchMotion(when, policyFlags, mTouchSource,
2955 AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, 0,
2956 mLastTouchCoords, mLastTouch.idToIndex, dispatchedIdBits, upId,
2957 xPrecision, yPrecision, mDownTime);
2958 dispatchedIdBits.clearBit(upId);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002959 }
2960
Jeff Brownc3db8582010-10-20 15:33:38 -07002961 // Dispatch move events if any of the remaining pointers moved from their old locations.
2962 // Although applications receive new locations as part of individual pointer up
2963 // events, they do not generally handle them except when presented in a move event.
2964 if (moveNeeded) {
Jeff Brown96ad3972011-03-09 17:39:48 -08002965 assert(moveIdBits.value == dispatchedIdBits.value);
2966 dispatchMotion(when, policyFlags, mTouchSource,
2967 AMOTION_EVENT_ACTION_MOVE, 0, metaState, 0,
2968 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, -1,
2969 xPrecision, yPrecision, mDownTime);
Jeff Brownc3db8582010-10-20 15:33:38 -07002970 }
2971
2972 // Dispatch pointer down events using the new pointer locations.
2973 while (!downIdBits.isEmpty()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002974 uint32_t downId = downIdBits.firstMarkedBit();
2975 downIdBits.clearBit(downId);
Jeff Brown96ad3972011-03-09 17:39:48 -08002976 dispatchedIdBits.markBit(downId);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002977
Jeff Brown96ad3972011-03-09 17:39:48 -08002978 if (dispatchedIdBits.count() == 1) {
2979 // First pointer is going down. Set down time.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002980 mDownTime = when;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002981 } else {
Jeff Brown96ad3972011-03-09 17:39:48 -08002982 // Only send edge flags with first pointer down.
2983 edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002984 }
2985
Jeff Brown96ad3972011-03-09 17:39:48 -08002986 dispatchMotion(when, policyFlags, mTouchSource,
2987 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
2988 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, downId,
2989 xPrecision, yPrecision, mDownTime);
2990 }
2991 }
2992
2993 // Update state for next time.
2994 for (uint32_t i = 0; i < currentPointerCount; i++) {
2995 mLastTouchCoords[i].copyFrom(mCurrentTouchCoords[i]);
2996 }
2997}
2998
2999void TouchInputMapper::prepareTouches(int32_t* outEdgeFlags,
3000 float* outXPrecision, float* outYPrecision) {
3001 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
3002 uint32_t lastPointerCount = mLastTouch.pointerCount;
3003
3004 AutoMutex _l(mLock);
3005
3006 // Walk through the the active pointers and map touch screen coordinates (TouchData) into
3007 // display or surface coordinates (PointerCoords) and adjust for display orientation.
3008 for (uint32_t i = 0; i < currentPointerCount; i++) {
3009 const PointerData& in = mCurrentTouch.pointers[i];
3010
3011 // ToolMajor and ToolMinor
3012 float toolMajor, toolMinor;
3013 switch (mCalibration.toolSizeCalibration) {
3014 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
3015 toolMajor = in.toolMajor * mLocked.geometricScale;
3016 if (mRawAxes.toolMinor.valid) {
3017 toolMinor = in.toolMinor * mLocked.geometricScale;
3018 } else {
3019 toolMinor = toolMajor;
3020 }
3021 break;
3022 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
3023 toolMajor = in.toolMajor != 0
3024 ? in.toolMajor * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias
3025 : 0;
3026 if (mRawAxes.toolMinor.valid) {
3027 toolMinor = in.toolMinor != 0
3028 ? in.toolMinor * mLocked.toolSizeLinearScale
3029 + mLocked.toolSizeLinearBias
3030 : 0;
3031 } else {
3032 toolMinor = toolMajor;
3033 }
3034 break;
3035 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
3036 if (in.toolMajor != 0) {
3037 float diameter = sqrtf(in.toolMajor
3038 * mLocked.toolSizeAreaScale + mLocked.toolSizeAreaBias);
3039 toolMajor = diameter * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias;
3040 } else {
3041 toolMajor = 0;
3042 }
3043 toolMinor = toolMajor;
3044 break;
3045 default:
3046 toolMajor = 0;
3047 toolMinor = 0;
3048 break;
3049 }
3050
3051 if (mCalibration.haveToolSizeIsSummed && mCalibration.toolSizeIsSummed) {
3052 toolMajor /= currentPointerCount;
3053 toolMinor /= currentPointerCount;
3054 }
3055
3056 // Pressure
3057 float rawPressure;
3058 switch (mCalibration.pressureSource) {
3059 case Calibration::PRESSURE_SOURCE_PRESSURE:
3060 rawPressure = in.pressure;
3061 break;
3062 case Calibration::PRESSURE_SOURCE_TOUCH:
3063 rawPressure = in.touchMajor;
3064 break;
3065 default:
3066 rawPressure = 0;
3067 }
3068
3069 float pressure;
3070 switch (mCalibration.pressureCalibration) {
3071 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3072 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3073 pressure = rawPressure * mLocked.pressureScale;
3074 break;
3075 default:
3076 pressure = 1;
3077 break;
3078 }
3079
3080 // TouchMajor and TouchMinor
3081 float touchMajor, touchMinor;
3082 switch (mCalibration.touchSizeCalibration) {
3083 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
3084 touchMajor = in.touchMajor * mLocked.geometricScale;
3085 if (mRawAxes.touchMinor.valid) {
3086 touchMinor = in.touchMinor * mLocked.geometricScale;
3087 } else {
3088 touchMinor = touchMajor;
3089 }
3090 break;
3091 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
3092 touchMajor = toolMajor * pressure;
3093 touchMinor = toolMinor * pressure;
3094 break;
3095 default:
3096 touchMajor = 0;
3097 touchMinor = 0;
3098 break;
3099 }
3100
3101 if (touchMajor > toolMajor) {
3102 touchMajor = toolMajor;
3103 }
3104 if (touchMinor > toolMinor) {
3105 touchMinor = toolMinor;
3106 }
3107
3108 // Size
3109 float size;
3110 switch (mCalibration.sizeCalibration) {
3111 case Calibration::SIZE_CALIBRATION_NORMALIZED: {
3112 float rawSize = mRawAxes.toolMinor.valid
3113 ? avg(in.toolMajor, in.toolMinor)
3114 : in.toolMajor;
3115 size = rawSize * mLocked.sizeScale;
3116 break;
3117 }
3118 default:
3119 size = 0;
3120 break;
3121 }
3122
3123 // Orientation
3124 float orientation;
3125 switch (mCalibration.orientationCalibration) {
3126 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3127 orientation = in.orientation * mLocked.orientationScale;
3128 break;
3129 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
3130 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
3131 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
3132 if (c1 != 0 || c2 != 0) {
3133 orientation = atan2f(c1, c2) * 0.5f;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003134 float scale = 1.0f + hypotf(c1, c2) / 16.0f;
Jeff Brown96ad3972011-03-09 17:39:48 -08003135 touchMajor *= scale;
3136 touchMinor /= scale;
3137 toolMajor *= scale;
3138 toolMinor /= scale;
3139 } else {
3140 orientation = 0;
3141 }
3142 break;
3143 }
3144 default:
3145 orientation = 0;
3146 }
3147
3148 // X and Y
3149 // Adjust coords for surface orientation.
3150 float x, y;
3151 switch (mLocked.surfaceOrientation) {
3152 case DISPLAY_ORIENTATION_90:
3153 x = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3154 y = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3155 orientation -= M_PI_2;
3156 if (orientation < - M_PI_2) {
3157 orientation += M_PI;
3158 }
3159 break;
3160 case DISPLAY_ORIENTATION_180:
3161 x = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3162 y = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3163 break;
3164 case DISPLAY_ORIENTATION_270:
3165 x = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3166 y = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3167 orientation += M_PI_2;
3168 if (orientation > M_PI_2) {
3169 orientation -= M_PI;
3170 }
3171 break;
3172 default:
3173 x = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3174 y = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3175 break;
3176 }
3177
3178 // Write output coords.
3179 PointerCoords& out = mCurrentTouchCoords[i];
3180 out.clear();
3181 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3182 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3183 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
3184 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
3185 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
3186 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
3187 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
3188 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
3189 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
3190 }
3191
3192 // Check edge flags by looking only at the first pointer since the flags are
3193 // global to the event.
3194 *outEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3195 if (lastPointerCount == 0 && currentPointerCount > 0) {
3196 const PointerData& in = mCurrentTouch.pointers[0];
3197
3198 if (in.x <= mRawAxes.x.minValue) {
3199 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_LEFT,
3200 mLocked.surfaceOrientation);
3201 } else if (in.x >= mRawAxes.x.maxValue) {
3202 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_RIGHT,
3203 mLocked.surfaceOrientation);
3204 }
3205 if (in.y <= mRawAxes.y.minValue) {
3206 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_TOP,
3207 mLocked.surfaceOrientation);
3208 } else if (in.y >= mRawAxes.y.maxValue) {
3209 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_BOTTOM,
3210 mLocked.surfaceOrientation);
3211 }
3212 }
3213
3214 *outXPrecision = mLocked.orientedXPrecision;
3215 *outYPrecision = mLocked.orientedYPrecision;
3216}
3217
3218void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags) {
Jeff Brown86ea1f52011-04-12 22:39:53 -07003219 // Switch pointer presentation.
3220 mPointerController->setPresentation(
3221 mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
3222 ? PointerControllerInterface::PRESENTATION_SPOT
3223 : PointerControllerInterface::PRESENTATION_POINTER);
3224
Jeff Brown96ad3972011-03-09 17:39:48 -08003225 // Update current gesture coordinates.
3226 bool cancelPreviousGesture, finishPreviousGesture;
3227 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture);
3228
Jeff Brown86ea1f52011-04-12 22:39:53 -07003229 // Show the pointer if needed.
3230 if (mPointerGesture.currentGestureMode != PointerGesture::NEUTRAL
3231 && mPointerGesture.currentGestureMode != PointerGesture::QUIET) {
3232 mPointerController->unfade();
3233 }
3234
Jeff Brown96ad3972011-03-09 17:39:48 -08003235 // Send events!
3236 uint32_t metaState = getContext()->getGlobalMetaState();
3237
3238 // Update last coordinates of pointers that have moved so that we observe the new
3239 // pointer positions at the same time as other pointers that have just gone up.
3240 bool down = mPointerGesture.currentGestureMode == PointerGesture::CLICK_OR_DRAG
Jeff Brown86ea1f52011-04-12 22:39:53 -07003241 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
Jeff Brown96ad3972011-03-09 17:39:48 -08003242 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
3243 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
3244 bool moveNeeded = false;
3245 if (down && !cancelPreviousGesture && !finishPreviousGesture
Jeff Brown86ea1f52011-04-12 22:39:53 -07003246 && !mPointerGesture.lastGestureIdBits.isEmpty()
3247 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003248 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
3249 & mPointerGesture.lastGestureIdBits.value);
3250 moveNeeded = updateMovedPointerCoords(
3251 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3252 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3253 movedGestureIdBits);
3254 }
3255
3256 // Send motion events for all pointers that went up or were canceled.
3257 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
3258 if (!dispatchedGestureIdBits.isEmpty()) {
3259 if (cancelPreviousGesture) {
3260 dispatchMotion(when, policyFlags, mPointerSource,
3261 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3262 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3263 dispatchedGestureIdBits, -1,
3264 0, 0, mPointerGesture.downTime);
3265
3266 dispatchedGestureIdBits.clear();
3267 } else {
3268 BitSet32 upGestureIdBits;
3269 if (finishPreviousGesture) {
3270 upGestureIdBits = dispatchedGestureIdBits;
3271 } else {
3272 upGestureIdBits.value = dispatchedGestureIdBits.value
3273 & ~mPointerGesture.currentGestureIdBits.value;
3274 }
3275 while (!upGestureIdBits.isEmpty()) {
3276 uint32_t id = upGestureIdBits.firstMarkedBit();
3277 upGestureIdBits.clearBit(id);
3278
3279 dispatchMotion(when, policyFlags, mPointerSource,
3280 AMOTION_EVENT_ACTION_POINTER_UP, 0,
3281 metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3282 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3283 dispatchedGestureIdBits, id,
3284 0, 0, mPointerGesture.downTime);
3285
3286 dispatchedGestureIdBits.clearBit(id);
3287 }
3288 }
3289 }
3290
3291 // Send motion events for all pointers that moved.
3292 if (moveNeeded) {
3293 dispatchMotion(when, policyFlags, mPointerSource,
3294 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3295 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3296 dispatchedGestureIdBits, -1,
3297 0, 0, mPointerGesture.downTime);
3298 }
3299
3300 // Send motion events for all pointers that went down.
3301 if (down) {
3302 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
3303 & ~dispatchedGestureIdBits.value);
3304 while (!downGestureIdBits.isEmpty()) {
3305 uint32_t id = downGestureIdBits.firstMarkedBit();
3306 downGestureIdBits.clearBit(id);
3307 dispatchedGestureIdBits.markBit(id);
3308
3309 int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3310 if (dispatchedGestureIdBits.count() == 1) {
3311 // First pointer is going down. Calculate edge flags and set down time.
3312 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3313 const PointerCoords& downCoords = mPointerGesture.currentGestureCoords[index];
3314 edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3315 downCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
3316 downCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3317 mPointerGesture.downTime = when;
3318 }
3319
3320 dispatchMotion(when, policyFlags, mPointerSource,
3321 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
3322 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3323 dispatchedGestureIdBits, id,
3324 0, 0, mPointerGesture.downTime);
3325 }
3326 }
3327
3328 // Send down and up for a tap.
3329 if (mPointerGesture.currentGestureMode == PointerGesture::TAP) {
3330 const PointerCoords& coords = mPointerGesture.currentGestureCoords[0];
3331 int32_t edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3332 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3333 coords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3334 nsecs_t downTime = mPointerGesture.downTime = mPointerGesture.tapTime;
3335 mPointerGesture.resetTapTime();
3336
3337 dispatchMotion(downTime, policyFlags, mPointerSource,
3338 AMOTION_EVENT_ACTION_DOWN, 0, metaState, edgeFlags,
3339 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3340 mPointerGesture.currentGestureIdBits, -1,
3341 0, 0, downTime);
3342 dispatchMotion(when, policyFlags, mPointerSource,
3343 AMOTION_EVENT_ACTION_UP, 0, metaState, edgeFlags,
3344 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3345 mPointerGesture.currentGestureIdBits, -1,
3346 0, 0, downTime);
3347 }
3348
3349 // Send motion events for hover.
3350 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
3351 dispatchMotion(when, policyFlags, mPointerSource,
3352 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3353 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3354 mPointerGesture.currentGestureIdBits, -1,
3355 0, 0, mPointerGesture.downTime);
3356 }
3357
3358 // Update state.
3359 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
3360 if (!down) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003361 mPointerGesture.lastGestureIdBits.clear();
3362 } else {
Jeff Brown96ad3972011-03-09 17:39:48 -08003363 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
3364 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
3365 uint32_t id = idBits.firstMarkedBit();
3366 idBits.clearBit(id);
3367 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3368 mPointerGesture.lastGestureCoords[index].copyFrom(
3369 mPointerGesture.currentGestureCoords[index]);
3370 mPointerGesture.lastGestureIdToIndex[id] = index;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003371 }
3372 }
3373}
3374
Jeff Brown96ad3972011-03-09 17:39:48 -08003375void TouchInputMapper::preparePointerGestures(nsecs_t when,
3376 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture) {
3377 *outCancelPreviousGesture = false;
3378 *outFinishPreviousGesture = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003379
Jeff Brown96ad3972011-03-09 17:39:48 -08003380 AutoMutex _l(mLock);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003381
Jeff Brown96ad3972011-03-09 17:39:48 -08003382 // Update the velocity tracker.
3383 {
3384 VelocityTracker::Position positions[MAX_POINTERS];
3385 uint32_t count = 0;
3386 for (BitSet32 idBits(mCurrentTouch.idBits); !idBits.isEmpty(); count++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07003387 uint32_t id = idBits.firstMarkedBit();
3388 idBits.clearBit(id);
Jeff Brown96ad3972011-03-09 17:39:48 -08003389 uint32_t index = mCurrentTouch.idToIndex[id];
3390 positions[count].x = mCurrentTouch.pointers[index].x
3391 * mLocked.pointerGestureXMovementScale;
3392 positions[count].y = mCurrentTouch.pointers[index].y
3393 * mLocked.pointerGestureYMovementScale;
3394 }
3395 mPointerGesture.velocityTracker.addMovement(when, mCurrentTouch.idBits, positions);
3396 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003397
Jeff Brown96ad3972011-03-09 17:39:48 -08003398 // Pick a new active touch id if needed.
3399 // Choose an arbitrary pointer that just went down, if there is one.
3400 // Otherwise choose an arbitrary remaining pointer.
3401 // This guarantees we always have an active touch id when there is at least one pointer.
Jeff Brown86ea1f52011-04-12 22:39:53 -07003402 // We keep the same active touch id for as long as possible.
3403 bool activeTouchChanged = false;
3404 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
3405 int32_t activeTouchId = lastActiveTouchId;
3406 if (activeTouchId < 0) {
3407 if (!mCurrentTouch.idBits.isEmpty()) {
3408 activeTouchChanged = true;
3409 activeTouchId = mPointerGesture.activeTouchId = mCurrentTouch.idBits.firstMarkedBit();
3410 mPointerGesture.firstTouchTime = when;
Jeff Brown96ad3972011-03-09 17:39:48 -08003411 }
Jeff Brown86ea1f52011-04-12 22:39:53 -07003412 } else if (!mCurrentTouch.idBits.hasBit(activeTouchId)) {
3413 activeTouchChanged = true;
3414 if (!mCurrentTouch.idBits.isEmpty()) {
3415 activeTouchId = mPointerGesture.activeTouchId = mCurrentTouch.idBits.firstMarkedBit();
3416 } else {
3417 activeTouchId = mPointerGesture.activeTouchId = -1;
Jeff Brown96ad3972011-03-09 17:39:48 -08003418 }
3419 }
3420
3421 // Determine whether we are in quiet time.
Jeff Brown86ea1f52011-04-12 22:39:53 -07003422 bool isQuietTime = false;
3423 if (activeTouchId < 0) {
3424 mPointerGesture.resetQuietTime();
3425 } else {
3426 isQuietTime = when < mPointerGesture.quietTime + QUIET_INTERVAL;
3427 if (!isQuietTime) {
3428 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
3429 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
3430 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
3431 && mCurrentTouch.pointerCount < 2) {
3432 // Enter quiet time when exiting swipe or freeform state.
3433 // This is to prevent accidentally entering the hover state and flinging the
3434 // pointer when finishing a swipe and there is still one pointer left onscreen.
3435 isQuietTime = true;
3436 } else if (mPointerGesture.lastGestureMode == PointerGesture::CLICK_OR_DRAG
3437 && mCurrentTouch.pointerCount >= 2
3438 && !isPointerDown(mCurrentTouch.buttonState)) {
3439 // Enter quiet time when releasing the button and there are still two or more
3440 // fingers down. This may indicate that one finger was used to press the button
3441 // but it has not gone up yet.
3442 isQuietTime = true;
3443 }
3444 if (isQuietTime) {
3445 mPointerGesture.quietTime = when;
3446 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003447 }
3448 }
3449
3450 // Switch states based on button and pointer state.
3451 if (isQuietTime) {
3452 // Case 1: Quiet time. (QUIET)
3453#if DEBUG_GESTURES
3454 LOGD("Gestures: QUIET for next %0.3fms",
3455 (mPointerGesture.quietTime + QUIET_INTERVAL - when) * 0.000001f);
3456#endif
3457 *outFinishPreviousGesture = true;
3458
3459 mPointerGesture.activeGestureId = -1;
3460 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
Jeff Brown96ad3972011-03-09 17:39:48 -08003461 mPointerGesture.currentGestureIdBits.clear();
Jeff Brown86ea1f52011-04-12 22:39:53 -07003462
3463 mPointerController->setButtonState(0);
3464
3465 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3466 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_NEUTRAL;
3467 mPointerGesture.spotIdBits.clear();
3468 moveSpotsLocked();
3469 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003470 } else if (isPointerDown(mCurrentTouch.buttonState)) {
Jeff Brown86ea1f52011-04-12 22:39:53 -07003471 // Case 2: Button is pressed. (CLICK_OR_DRAG)
Jeff Brown96ad3972011-03-09 17:39:48 -08003472 // The pointer follows the active touch point.
3473 // Emit DOWN, MOVE, UP events at the pointer location.
3474 //
3475 // Only the active touch matters; other fingers are ignored. This policy helps
3476 // to handle the case where the user places a second finger on the touch pad
3477 // to apply the necessary force to depress an integrated button below the surface.
3478 // We don't want the second finger to be delivered to applications.
3479 //
3480 // For this to work well, we need to make sure to track the pointer that is really
3481 // active. If the user first puts one finger down to click then adds another
3482 // finger to drag then the active pointer should switch to the finger that is
3483 // being dragged.
3484#if DEBUG_GESTURES
3485 LOGD("Gestures: CLICK_OR_DRAG activeTouchId=%d, "
3486 "currentTouchPointerCount=%d", activeTouchId, mCurrentTouch.pointerCount);
3487#endif
3488 // Reset state when just starting.
3489 if (mPointerGesture.lastGestureMode != PointerGesture::CLICK_OR_DRAG) {
3490 *outFinishPreviousGesture = true;
3491 mPointerGesture.activeGestureId = 0;
3492 }
3493
3494 // Switch pointers if needed.
3495 // Find the fastest pointer and follow it.
3496 if (activeTouchId >= 0) {
3497 if (mCurrentTouch.pointerCount > 1) {
3498 int32_t bestId = -1;
3499 float bestSpeed = DRAG_MIN_SWITCH_SPEED;
3500 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3501 uint32_t id = mCurrentTouch.pointers[i].id;
3502 float vx, vy;
3503 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
Jeff Brown86ea1f52011-04-12 22:39:53 -07003504 float speed = hypotf(vx, vy);
Jeff Brown96ad3972011-03-09 17:39:48 -08003505 if (speed > bestSpeed) {
3506 bestId = id;
3507 bestSpeed = speed;
3508 }
3509 }
Jeff Brown8d608662010-08-30 03:02:23 -07003510 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003511 if (bestId >= 0 && bestId != activeTouchId) {
3512 mPointerGesture.activeTouchId = activeTouchId = bestId;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003513 activeTouchChanged = true;
Jeff Brown96ad3972011-03-09 17:39:48 -08003514#if DEBUG_GESTURES
3515 LOGD("Gestures: CLICK_OR_DRAG switched pointers, "
3516 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
3517#endif
Jeff Brown8d608662010-08-30 03:02:23 -07003518 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003519 }
3520
Jeff Brown96ad3972011-03-09 17:39:48 -08003521 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3522 const PointerData& currentPointer =
3523 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3524 const PointerData& lastPointer =
3525 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3526 float deltaX = (currentPointer.x - lastPointer.x)
3527 * mLocked.pointerGestureXMovementScale;
3528 float deltaY = (currentPointer.y - lastPointer.y)
3529 * mLocked.pointerGestureYMovementScale;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003530
3531 // Move the pointer using a relative motion.
3532 // When using spots, the click will occur at the position of the anchor
3533 // spot and all other spots will move there.
Jeff Brown96ad3972011-03-09 17:39:48 -08003534 mPointerController->move(deltaX, deltaY);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003535 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003536 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003537
Jeff Brown96ad3972011-03-09 17:39:48 -08003538 float x, y;
3539 mPointerController->getPosition(&x, &y);
Jeff Brown91c69ab2011-02-14 17:03:18 -08003540
Jeff Brown96ad3972011-03-09 17:39:48 -08003541 mPointerGesture.currentGestureMode = PointerGesture::CLICK_OR_DRAG;
Jeff Brown96ad3972011-03-09 17:39:48 -08003542 mPointerGesture.currentGestureIdBits.clear();
3543 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3544 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3545 mPointerGesture.currentGestureCoords[0].clear();
3546 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3547 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3548 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown86ea1f52011-04-12 22:39:53 -07003549
3550 mPointerController->setButtonState(BUTTON_STATE_PRIMARY);
3551
3552 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3553 if (activeTouchId >= 0) {
3554 // Collapse all spots into one point at the pointer location.
3555 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_BUTTON_DRAG;
3556 mPointerGesture.spotIdBits.clear();
3557 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3558 uint32_t id = mCurrentTouch.pointers[i].id;
3559 mPointerGesture.spotIdBits.markBit(id);
3560 mPointerGesture.spotIdToIndex[id] = i;
3561 mPointerGesture.spotCoords[i] = mPointerGesture.currentGestureCoords[0];
3562 }
3563 } else {
3564 // No fingers. Generate a spot at the pointer location so the
3565 // anchor appears to be pressed.
3566 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_BUTTON_CLICK;
3567 mPointerGesture.spotIdBits.clear();
3568 mPointerGesture.spotIdBits.markBit(0);
3569 mPointerGesture.spotIdToIndex[0] = 0;
3570 mPointerGesture.spotCoords[0] = mPointerGesture.currentGestureCoords[0];
3571 }
3572 moveSpotsLocked();
3573 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003574 } else if (mCurrentTouch.pointerCount == 0) {
3575 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
3576 *outFinishPreviousGesture = true;
3577
Jeff Brown86ea1f52011-04-12 22:39:53 -07003578 // Watch for taps coming out of HOVER mode.
Jeff Brown96ad3972011-03-09 17:39:48 -08003579 bool tapped = false;
3580 if (mPointerGesture.lastGestureMode == PointerGesture::HOVER
Jeff Brown86ea1f52011-04-12 22:39:53 -07003581 && mLastTouch.pointerCount == 1) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003582 if (when <= mPointerGesture.tapTime + TAP_INTERVAL) {
3583 float x, y;
3584 mPointerController->getPosition(&x, &y);
Jeff Brown86ea1f52011-04-12 22:39:53 -07003585 if (fabs(x - mPointerGesture.tapX) <= TAP_SLOP
3586 && fabs(y - mPointerGesture.tapY) <= TAP_SLOP) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003587#if DEBUG_GESTURES
3588 LOGD("Gestures: TAP");
3589#endif
3590 mPointerGesture.activeGestureId = 0;
3591 mPointerGesture.currentGestureMode = PointerGesture::TAP;
Jeff Brown96ad3972011-03-09 17:39:48 -08003592 mPointerGesture.currentGestureIdBits.clear();
3593 mPointerGesture.currentGestureIdBits.markBit(
3594 mPointerGesture.activeGestureId);
3595 mPointerGesture.currentGestureIdToIndex[
3596 mPointerGesture.activeGestureId] = 0;
3597 mPointerGesture.currentGestureCoords[0].clear();
3598 mPointerGesture.currentGestureCoords[0].setAxisValue(
Jeff Brown86ea1f52011-04-12 22:39:53 -07003599 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
Jeff Brown96ad3972011-03-09 17:39:48 -08003600 mPointerGesture.currentGestureCoords[0].setAxisValue(
Jeff Brown86ea1f52011-04-12 22:39:53 -07003601 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
Jeff Brown96ad3972011-03-09 17:39:48 -08003602 mPointerGesture.currentGestureCoords[0].setAxisValue(
3603 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown86ea1f52011-04-12 22:39:53 -07003604
3605 mPointerController->setButtonState(BUTTON_STATE_PRIMARY);
3606 mPointerController->setButtonState(0);
3607
3608 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3609 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_TAP;
3610 mPointerGesture.spotIdBits.clear();
3611 mPointerGesture.spotIdBits.markBit(lastActiveTouchId);
3612 mPointerGesture.spotIdToIndex[lastActiveTouchId] = 0;
3613 mPointerGesture.spotCoords[0] = mPointerGesture.currentGestureCoords[0];
3614 moveSpotsLocked();
3615 }
3616
Jeff Brown96ad3972011-03-09 17:39:48 -08003617 tapped = true;
3618 } else {
3619#if DEBUG_GESTURES
3620 LOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
Jeff Brown86ea1f52011-04-12 22:39:53 -07003621 x - mPointerGesture.tapX,
3622 y - mPointerGesture.tapY);
Jeff Brown96ad3972011-03-09 17:39:48 -08003623#endif
3624 }
3625 } else {
3626#if DEBUG_GESTURES
3627 LOGD("Gestures: Not a TAP, delay=%lld",
3628 when - mPointerGesture.tapTime);
3629#endif
Jeff Brown6328cdc2010-07-29 18:18:33 -07003630 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003631 }
Jeff Brown86ea1f52011-04-12 22:39:53 -07003632
Jeff Brown96ad3972011-03-09 17:39:48 -08003633 if (!tapped) {
3634#if DEBUG_GESTURES
3635 LOGD("Gestures: NEUTRAL");
3636#endif
3637 mPointerGesture.activeGestureId = -1;
3638 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
Jeff Brown96ad3972011-03-09 17:39:48 -08003639 mPointerGesture.currentGestureIdBits.clear();
Jeff Brown86ea1f52011-04-12 22:39:53 -07003640
3641 mPointerController->setButtonState(0);
3642
3643 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3644 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_NEUTRAL;
3645 mPointerGesture.spotIdBits.clear();
3646 moveSpotsLocked();
3647 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003648 }
3649 } else if (mCurrentTouch.pointerCount == 1) {
3650 // Case 4. Exactly one finger down, button is not pressed. (HOVER)
3651 // The pointer follows the active touch point.
3652 // Emit HOVER_MOVE events at the pointer location.
3653 assert(activeTouchId >= 0);
3654
3655#if DEBUG_GESTURES
3656 LOGD("Gestures: HOVER");
3657#endif
3658
3659 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3660 const PointerData& currentPointer =
3661 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3662 const PointerData& lastPointer =
3663 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3664 float deltaX = (currentPointer.x - lastPointer.x)
3665 * mLocked.pointerGestureXMovementScale;
3666 float deltaY = (currentPointer.y - lastPointer.y)
3667 * mLocked.pointerGestureYMovementScale;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003668
3669 // Move the pointer using a relative motion.
3670 // When using spots, the hover will occur at the position of the anchor spot.
Jeff Brown96ad3972011-03-09 17:39:48 -08003671 mPointerController->move(deltaX, deltaY);
3672 }
3673
3674 *outFinishPreviousGesture = true;
3675 mPointerGesture.activeGestureId = 0;
3676
3677 float x, y;
3678 mPointerController->getPosition(&x, &y);
3679
3680 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
Jeff Brown96ad3972011-03-09 17:39:48 -08003681 mPointerGesture.currentGestureIdBits.clear();
3682 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3683 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3684 mPointerGesture.currentGestureCoords[0].clear();
3685 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3686 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3687 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 0.0f);
3688
3689 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
3690 mPointerGesture.tapTime = when;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003691 mPointerGesture.tapX = x;
3692 mPointerGesture.tapY = y;
3693 }
3694
3695 mPointerController->setButtonState(0);
3696
3697 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3698 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_HOVER;
3699 mPointerGesture.spotIdBits.clear();
3700 mPointerGesture.spotIdBits.markBit(activeTouchId);
3701 mPointerGesture.spotIdToIndex[activeTouchId] = 0;
3702 mPointerGesture.spotCoords[0] = mPointerGesture.currentGestureCoords[0];
3703 moveSpotsLocked();
Jeff Brown96ad3972011-03-09 17:39:48 -08003704 }
3705 } else {
Jeff Brown86ea1f52011-04-12 22:39:53 -07003706 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3707 // We need to provide feedback for each finger that goes down so we cannot wait
3708 // for the fingers to move before deciding what to do.
Jeff Brown96ad3972011-03-09 17:39:48 -08003709 //
Jeff Brown86ea1f52011-04-12 22:39:53 -07003710 // The ambiguous case is deciding what to do when there are two fingers down but they
3711 // have not moved enough to determine whether they are part of a drag or part of a
3712 // freeform gesture, or just a press or long-press at the pointer location.
3713 //
3714 // When there are two fingers we start with the PRESS hypothesis and we generate a
3715 // down at the pointer location.
3716 //
3717 // When the two fingers move enough or when additional fingers are added, we make
3718 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3719 LOG_ASSERT(activeTouchId >= 0);
Jeff Brown96ad3972011-03-09 17:39:48 -08003720
Jeff Brown86ea1f52011-04-12 22:39:53 -07003721 bool needReference = false;
3722 bool settled = when >= mPointerGesture.firstTouchTime + MULTITOUCH_SETTLE_INTERVAL;
3723 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
Jeff Brown96ad3972011-03-09 17:39:48 -08003724 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
3725 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003726 *outFinishPreviousGesture = true;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003727 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
3728 mPointerGesture.activeGestureId = 0;
Jeff Brown96ad3972011-03-09 17:39:48 -08003729
Jeff Brown86ea1f52011-04-12 22:39:53 -07003730 if (settled && mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
3731 && mLastTouch.idBits.hasBit(mPointerGesture.activeTouchId)) {
3732 // The spot is already visible and has settled, use it as the reference point
3733 // for the gesture. Other spots will be positioned relative to this one.
3734#if DEBUG_GESTURES
3735 LOGD("Gestures: Using active spot as reference for MULTITOUCH, "
3736 "settle time expired %0.3fms ago",
3737 (when - mPointerGesture.firstTouchTime - MULTITOUCH_SETTLE_INTERVAL)
3738 * 0.000001f);
3739#endif
3740 const PointerData& d = mLastTouch.pointers[mLastTouch.idToIndex[
3741 mPointerGesture.activeTouchId]];
3742 mPointerGesture.referenceTouchX = d.x;
3743 mPointerGesture.referenceTouchY = d.y;
3744 const PointerCoords& c = mPointerGesture.spotCoords[mPointerGesture.spotIdToIndex[
3745 mPointerGesture.activeTouchId]];
3746 mPointerGesture.referenceGestureX = c.getAxisValue(AMOTION_EVENT_AXIS_X);
3747 mPointerGesture.referenceGestureY = c.getAxisValue(AMOTION_EVENT_AXIS_Y);
3748 } else {
3749#if DEBUG_GESTURES
3750 LOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3751 "settle time remaining %0.3fms",
3752 (mPointerGesture.firstTouchTime + MULTITOUCH_SETTLE_INTERVAL - when)
3753 * 0.000001f);
3754#endif
3755 needReference = true;
Jeff Brown96ad3972011-03-09 17:39:48 -08003756 }
Jeff Brown86ea1f52011-04-12 22:39:53 -07003757 } else if (!settled && mCurrentTouch.pointerCount > mLastTouch.pointerCount) {
3758 // Additional pointers have gone down but not yet settled.
3759 // Reset the gesture.
3760#if DEBUG_GESTURES
3761 LOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3762 "settle time remaining %0.3fms",
3763 (mPointerGesture.firstTouchTime + MULTITOUCH_SETTLE_INTERVAL - when)
3764 * 0.000001f);
3765#endif
3766 *outCancelPreviousGesture = true;
3767 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
3768 mPointerGesture.activeGestureId = 0;
Jeff Brown96ad3972011-03-09 17:39:48 -08003769 } else {
Jeff Brown86ea1f52011-04-12 22:39:53 -07003770 // Continue previous gesture.
Jeff Brown96ad3972011-03-09 17:39:48 -08003771 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3772 }
3773
Jeff Brown86ea1f52011-04-12 22:39:53 -07003774 if (needReference) {
3775 // Use the centroid and pointer location as the reference points for the gesture.
3776 mCurrentTouch.getCentroid(&mPointerGesture.referenceTouchX,
3777 &mPointerGesture.referenceTouchY);
3778 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3779 &mPointerGesture.referenceGestureY);
3780 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003781
Jeff Brown86ea1f52011-04-12 22:39:53 -07003782 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
3783 float d;
3784 if (mCurrentTouch.pointerCount > 2) {
3785 // There are more than two pointers, switch to FREEFORM.
3786#if DEBUG_GESTURES
3787 LOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3788 mCurrentTouch.pointerCount);
3789#endif
3790 *outCancelPreviousGesture = true;
Jeff Brown96ad3972011-03-09 17:39:48 -08003791 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003792 } else if (((d = distance(
3793 mCurrentTouch.pointers[0].x, mCurrentTouch.pointers[0].y,
3794 mCurrentTouch.pointers[1].x, mCurrentTouch.pointers[1].y))
3795 > mLocked.pointerGestureMaxSwipeWidth)) {
3796 // There are two pointers but they are too far apart, switch to FREEFORM.
3797#if DEBUG_GESTURES
3798 LOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3799 d, mLocked.pointerGestureMaxSwipeWidth);
3800#endif
3801 *outCancelPreviousGesture = true;
3802 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
3803 } else {
3804 // There are two pointers. Wait for both pointers to start moving
3805 // before deciding whether this is a SWIPE or FREEFORM gesture.
3806 uint32_t id1 = mCurrentTouch.pointers[0].id;
3807 uint32_t id2 = mCurrentTouch.pointers[1].id;
Jeff Brown96ad3972011-03-09 17:39:48 -08003808
Jeff Brown86ea1f52011-04-12 22:39:53 -07003809 float vx1, vy1, vx2, vy2;
3810 mPointerGesture.velocityTracker.getVelocity(id1, &vx1, &vy1);
3811 mPointerGesture.velocityTracker.getVelocity(id2, &vx2, &vy2);
Jeff Brown96ad3972011-03-09 17:39:48 -08003812
Jeff Brown86ea1f52011-04-12 22:39:53 -07003813 float speed1 = hypotf(vx1, vy1);
3814 float speed2 = hypotf(vx2, vy2);
3815 if (speed1 >= MULTITOUCH_MIN_SPEED && speed2 >= MULTITOUCH_MIN_SPEED) {
3816 // Calculate the dot product of the velocity vectors.
Jeff Brown96ad3972011-03-09 17:39:48 -08003817 // When the vectors are oriented in approximately the same direction,
3818 // the angle betweeen them is near zero and the cosine of the angle
3819 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
Jeff Brown86ea1f52011-04-12 22:39:53 -07003820 float dot = vx1 * vx2 + vy1 * vy2;
3821 float cosine = dot / (speed1 * speed2); // denominator always > 0
3822 if (cosine >= SWIPE_TRANSITION_ANGLE_COSINE) {
3823 // Pointers are moving in the same direction. Switch to SWIPE.
3824#if DEBUG_GESTURES
3825 LOGD("Gestures: PRESS transitioned to SWIPE, "
3826 "speed1 %0.3f >= %0.3f, speed2 %0.3f >= %0.3f, "
3827 "cosine %0.3f >= %0.3f",
3828 speed1, MULTITOUCH_MIN_SPEED, speed2, MULTITOUCH_MIN_SPEED,
3829 cosine, SWIPE_TRANSITION_ANGLE_COSINE);
3830#endif
Jeff Brown96ad3972011-03-09 17:39:48 -08003831 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003832 } else {
3833 // Pointers are moving in different directions. Switch to FREEFORM.
3834#if DEBUG_GESTURES
3835 LOGD("Gestures: PRESS transitioned to FREEFORM, "
3836 "speed1 %0.3f >= %0.3f, speed2 %0.3f >= %0.3f, "
3837 "cosine %0.3f < %0.3f",
3838 speed1, MULTITOUCH_MIN_SPEED, speed2, MULTITOUCH_MIN_SPEED,
3839 cosine, SWIPE_TRANSITION_ANGLE_COSINE);
3840#endif
3841 *outCancelPreviousGesture = true;
3842 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown96ad3972011-03-09 17:39:48 -08003843 }
3844 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003845 }
3846 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
Jeff Brown86ea1f52011-04-12 22:39:53 -07003847 // Switch from SWIPE to FREEFORM if additional pointers go down.
3848 // Cancel previous gesture.
3849 if (mCurrentTouch.pointerCount > 2) {
3850#if DEBUG_GESTURES
3851 LOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3852 mCurrentTouch.pointerCount);
3853#endif
Jeff Brown96ad3972011-03-09 17:39:48 -08003854 *outCancelPreviousGesture = true;
3855 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003856 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003857 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003858
Jeff Brown86ea1f52011-04-12 22:39:53 -07003859 // Move the reference points based on the overall group motion of the fingers.
3860 // The objective is to calculate a vector delta that is common to the movement
3861 // of all fingers.
3862 BitSet32 commonIdBits(mLastTouch.idBits.value & mCurrentTouch.idBits.value);
3863 if (!commonIdBits.isEmpty()) {
3864 float commonDeltaX = 0, commonDeltaY = 0;
3865 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
3866 bool first = (idBits == commonIdBits);
3867 uint32_t id = idBits.firstMarkedBit();
3868 idBits.clearBit(id);
3869
3870 const PointerData& cpd = mCurrentTouch.pointers[mCurrentTouch.idToIndex[id]];
3871 const PointerData& lpd = mLastTouch.pointers[mLastTouch.idToIndex[id]];
3872 float deltaX = cpd.x - lpd.x;
3873 float deltaY = cpd.y - lpd.y;
3874
3875 if (first) {
3876 commonDeltaX = deltaX;
3877 commonDeltaY = deltaY;
3878 } else {
3879 commonDeltaX = calculateCommonVector(commonDeltaX, deltaX);
3880 commonDeltaY = calculateCommonVector(commonDeltaY, deltaY);
3881 }
3882 }
3883
3884 mPointerGesture.referenceTouchX += commonDeltaX;
3885 mPointerGesture.referenceTouchY += commonDeltaY;
3886 mPointerGesture.referenceGestureX +=
3887 commonDeltaX * mLocked.pointerGestureXMovementScale;
3888 mPointerGesture.referenceGestureY +=
3889 commonDeltaY * mLocked.pointerGestureYMovementScale;
3890 clampPositionUsingPointerBounds(mPointerController,
3891 &mPointerGesture.referenceGestureX,
3892 &mPointerGesture.referenceGestureY);
3893 }
3894
3895 // Report gestures.
3896 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
3897 // PRESS mode.
Jeff Brown96ad3972011-03-09 17:39:48 -08003898#if DEBUG_GESTURES
Jeff Brown86ea1f52011-04-12 22:39:53 -07003899 LOGD("Gestures: PRESS activeTouchId=%d,"
Jeff Brown96ad3972011-03-09 17:39:48 -08003900 "activeGestureId=%d, currentTouchPointerCount=%d",
Jeff Brown86ea1f52011-04-12 22:39:53 -07003901 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
Jeff Brown96ad3972011-03-09 17:39:48 -08003902#endif
Jeff Brown86ea1f52011-04-12 22:39:53 -07003903 LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
Jeff Brown96ad3972011-03-09 17:39:48 -08003904
Jeff Brown96ad3972011-03-09 17:39:48 -08003905 mPointerGesture.currentGestureIdBits.clear();
3906 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3907 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3908 mPointerGesture.currentGestureCoords[0].clear();
Jeff Brown86ea1f52011-04-12 22:39:53 -07003909 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3910 mPointerGesture.referenceGestureX);
3911 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3912 mPointerGesture.referenceGestureY);
Jeff Brown96ad3972011-03-09 17:39:48 -08003913 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown86ea1f52011-04-12 22:39:53 -07003914
3915 mPointerController->setButtonState(BUTTON_STATE_PRIMARY);
3916
3917 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3918 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_PRESS;
3919 }
3920 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
3921 // SWIPE mode.
3922#if DEBUG_GESTURES
3923 LOGD("Gestures: SWIPE activeTouchId=%d,"
3924 "activeGestureId=%d, currentTouchPointerCount=%d",
3925 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
3926#endif
3927 assert(mPointerGesture.activeGestureId >= 0);
3928
3929 mPointerGesture.currentGestureIdBits.clear();
3930 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3931 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3932 mPointerGesture.currentGestureCoords[0].clear();
3933 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3934 mPointerGesture.referenceGestureX);
3935 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3936 mPointerGesture.referenceGestureY);
3937 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3938
3939 mPointerController->setButtonState(0); // touch is not actually following the pointer
3940
3941 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3942 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_SWIPE;
3943 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003944 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
3945 // FREEFORM mode.
3946#if DEBUG_GESTURES
3947 LOGD("Gestures: FREEFORM activeTouchId=%d,"
3948 "activeGestureId=%d, currentTouchPointerCount=%d",
Jeff Brown86ea1f52011-04-12 22:39:53 -07003949 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
Jeff Brown96ad3972011-03-09 17:39:48 -08003950#endif
3951 assert(mPointerGesture.activeGestureId >= 0);
3952
Jeff Brown96ad3972011-03-09 17:39:48 -08003953 mPointerGesture.currentGestureIdBits.clear();
3954
3955 BitSet32 mappedTouchIdBits;
3956 BitSet32 usedGestureIdBits;
3957 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
3958 // Initially, assign the active gesture id to the active touch point
3959 // if there is one. No other touch id bits are mapped yet.
3960 if (!*outCancelPreviousGesture) {
3961 mappedTouchIdBits.markBit(activeTouchId);
3962 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3963 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3964 mPointerGesture.activeGestureId;
3965 } else {
3966 mPointerGesture.activeGestureId = -1;
3967 }
3968 } else {
3969 // Otherwise, assume we mapped all touches from the previous frame.
3970 // Reuse all mappings that are still applicable.
3971 mappedTouchIdBits.value = mLastTouch.idBits.value & mCurrentTouch.idBits.value;
3972 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3973
3974 // Check whether we need to choose a new active gesture id because the
3975 // current went went up.
3976 for (BitSet32 upTouchIdBits(mLastTouch.idBits.value & ~mCurrentTouch.idBits.value);
3977 !upTouchIdBits.isEmpty(); ) {
3978 uint32_t upTouchId = upTouchIdBits.firstMarkedBit();
3979 upTouchIdBits.clearBit(upTouchId);
3980 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3981 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3982 mPointerGesture.activeGestureId = -1;
3983 break;
3984 }
3985 }
3986 }
3987
3988#if DEBUG_GESTURES
3989 LOGD("Gestures: FREEFORM follow up "
3990 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3991 "activeGestureId=%d",
3992 mappedTouchIdBits.value, usedGestureIdBits.value,
3993 mPointerGesture.activeGestureId);
3994#endif
3995
Jeff Brown86ea1f52011-04-12 22:39:53 -07003996 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003997 uint32_t touchId = mCurrentTouch.pointers[i].id;
3998 uint32_t gestureId;
3999 if (!mappedTouchIdBits.hasBit(touchId)) {
4000 gestureId = usedGestureIdBits.firstUnmarkedBit();
4001 usedGestureIdBits.markBit(gestureId);
4002 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
4003#if DEBUG_GESTURES
4004 LOGD("Gestures: FREEFORM "
4005 "new mapping for touch id %d -> gesture id %d",
4006 touchId, gestureId);
4007#endif
4008 } else {
4009 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
4010#if DEBUG_GESTURES
4011 LOGD("Gestures: FREEFORM "
4012 "existing mapping for touch id %d -> gesture id %d",
4013 touchId, gestureId);
4014#endif
4015 }
4016 mPointerGesture.currentGestureIdBits.markBit(gestureId);
4017 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
4018
Jeff Brown86ea1f52011-04-12 22:39:53 -07004019 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.referenceTouchX)
4020 * mLocked.pointerGestureXZoomScale + mPointerGesture.referenceGestureX;
4021 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.referenceTouchY)
4022 * mLocked.pointerGestureYZoomScale + mPointerGesture.referenceGestureY;
Jeff Brown96ad3972011-03-09 17:39:48 -08004023
4024 mPointerGesture.currentGestureCoords[i].clear();
4025 mPointerGesture.currentGestureCoords[i].setAxisValue(
4026 AMOTION_EVENT_AXIS_X, x);
4027 mPointerGesture.currentGestureCoords[i].setAxisValue(
4028 AMOTION_EVENT_AXIS_Y, y);
4029 mPointerGesture.currentGestureCoords[i].setAxisValue(
4030 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4031 }
4032
4033 if (mPointerGesture.activeGestureId < 0) {
4034 mPointerGesture.activeGestureId =
4035 mPointerGesture.currentGestureIdBits.firstMarkedBit();
4036#if DEBUG_GESTURES
4037 LOGD("Gestures: FREEFORM new "
4038 "activeGestureId=%d", mPointerGesture.activeGestureId);
4039#endif
4040 }
Jeff Brown96ad3972011-03-09 17:39:48 -08004041
Jeff Brown86ea1f52011-04-12 22:39:53 -07004042 mPointerController->setButtonState(0); // touch is not actually following the pointer
4043
4044 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4045 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_FREEFORM;
4046 }
4047 }
4048
4049 // Update spot locations for PRESS, SWIPE and FREEFORM.
4050 // We use the same calculation as we do to calculate the gesture pointers
4051 // for FREEFORM so that the spots smoothly track gestures.
4052 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4053 mPointerGesture.spotIdBits.clear();
4054 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
4055 uint32_t id = mCurrentTouch.pointers[i].id;
4056 mPointerGesture.spotIdBits.markBit(id);
4057 mPointerGesture.spotIdToIndex[id] = i;
4058
4059 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.referenceTouchX)
4060 * mLocked.pointerGestureXZoomScale + mPointerGesture.referenceGestureX;
4061 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.referenceTouchY)
4062 * mLocked.pointerGestureYZoomScale + mPointerGesture.referenceGestureY;
4063
4064 mPointerGesture.spotCoords[i].clear();
4065 mPointerGesture.spotCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4066 mPointerGesture.spotCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4067 mPointerGesture.spotCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4068 }
4069 moveSpotsLocked();
4070 }
Jeff Brown96ad3972011-03-09 17:39:48 -08004071 }
4072
4073#if DEBUG_GESTURES
4074 LOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
Jeff Brown86ea1f52011-04-12 22:39:53 -07004075 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
4076 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
Jeff Brown96ad3972011-03-09 17:39:48 -08004077 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
Jeff Brown86ea1f52011-04-12 22:39:53 -07004078 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
4079 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
Jeff Brown96ad3972011-03-09 17:39:48 -08004080 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
4081 uint32_t id = idBits.firstMarkedBit();
4082 idBits.clearBit(id);
4083 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
4084 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
4085 LOGD(" currentGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
4086 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
4087 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
4088 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
4089 }
4090 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
4091 uint32_t id = idBits.firstMarkedBit();
4092 idBits.clearBit(id);
4093 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
4094 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
4095 LOGD(" lastGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
4096 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
4097 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
4098 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
4099 }
4100#endif
4101}
4102
Jeff Brown86ea1f52011-04-12 22:39:53 -07004103void TouchInputMapper::moveSpotsLocked() {
4104 mPointerController->setSpots(mPointerGesture.spotGesture,
4105 mPointerGesture.spotCoords, mPointerGesture.spotIdToIndex, mPointerGesture.spotIdBits);
4106}
4107
Jeff Brown96ad3972011-03-09 17:39:48 -08004108void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
4109 int32_t action, int32_t flags, uint32_t metaState, int32_t edgeFlags,
4110 const PointerCoords* coords, const uint32_t* idToIndex, BitSet32 idBits,
4111 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
4112 PointerCoords pointerCoords[MAX_POINTERS];
4113 int32_t pointerIds[MAX_POINTERS];
4114 uint32_t pointerCount = 0;
4115 while (!idBits.isEmpty()) {
4116 uint32_t id = idBits.firstMarkedBit();
4117 idBits.clearBit(id);
4118 uint32_t index = idToIndex[id];
4119 pointerIds[pointerCount] = id;
4120 pointerCoords[pointerCount].copyFrom(coords[index]);
4121
4122 if (changedId >= 0 && id == uint32_t(changedId)) {
4123 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
4124 }
4125
4126 pointerCount += 1;
4127 }
4128
4129 assert(pointerCount != 0);
4130
4131 if (changedId >= 0 && pointerCount == 1) {
4132 // Replace initial down and final up action.
4133 // We can compare the action without masking off the changed pointer index
4134 // because we know the index is 0.
4135 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
4136 action = AMOTION_EVENT_ACTION_DOWN;
4137 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
4138 action = AMOTION_EVENT_ACTION_UP;
4139 } else {
4140 // Can't happen.
4141 assert(false);
4142 }
4143 }
4144
4145 getDispatcher()->notifyMotion(when, getDeviceId(), source, policyFlags,
4146 action, flags, metaState, edgeFlags,
4147 pointerCount, pointerIds, pointerCoords, xPrecision, yPrecision, downTime);
4148}
4149
4150bool TouchInputMapper::updateMovedPointerCoords(
4151 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
4152 PointerCoords* outCoords, const uint32_t* outIdToIndex, BitSet32 idBits) const {
4153 bool changed = false;
4154 while (!idBits.isEmpty()) {
4155 uint32_t id = idBits.firstMarkedBit();
4156 idBits.clearBit(id);
4157
4158 uint32_t inIndex = inIdToIndex[id];
4159 uint32_t outIndex = outIdToIndex[id];
4160 const PointerCoords& curInCoords = inCoords[inIndex];
4161 PointerCoords& curOutCoords = outCoords[outIndex];
4162
4163 if (curInCoords != curOutCoords) {
4164 curOutCoords.copyFrom(curInCoords);
4165 changed = true;
4166 }
4167 }
4168 return changed;
4169}
4170
4171void TouchInputMapper::fadePointer() {
4172 { // acquire lock
4173 AutoMutex _l(mLock);
4174 if (mPointerController != NULL) {
4175 mPointerController->fade();
4176 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004177 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07004178}
4179
Jeff Brown6328cdc2010-07-29 18:18:33 -07004180bool TouchInputMapper::isPointInsideSurfaceLocked(int32_t x, int32_t y) {
Jeff Brown9626b142011-03-03 02:09:54 -08004181 return x >= mRawAxes.x.minValue && x <= mRawAxes.x.maxValue
4182 && y >= mRawAxes.y.minValue && y <= mRawAxes.y.maxValue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004183}
4184
Jeff Brown6328cdc2010-07-29 18:18:33 -07004185const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHitLocked(
4186 int32_t x, int32_t y) {
4187 size_t numVirtualKeys = mLocked.virtualKeys.size();
4188 for (size_t i = 0; i < numVirtualKeys; i++) {
4189 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004190
4191#if DEBUG_VIRTUAL_KEYS
4192 LOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
4193 "left=%d, top=%d, right=%d, bottom=%d",
4194 x, y,
4195 virtualKey.keyCode, virtualKey.scanCode,
4196 virtualKey.hitLeft, virtualKey.hitTop,
4197 virtualKey.hitRight, virtualKey.hitBottom);
4198#endif
4199
4200 if (virtualKey.isHit(x, y)) {
4201 return & virtualKey;
4202 }
4203 }
4204
4205 return NULL;
4206}
4207
4208void TouchInputMapper::calculatePointerIds() {
4209 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
4210 uint32_t lastPointerCount = mLastTouch.pointerCount;
4211
4212 if (currentPointerCount == 0) {
4213 // No pointers to assign.
4214 mCurrentTouch.idBits.clear();
4215 } else if (lastPointerCount == 0) {
4216 // All pointers are new.
4217 mCurrentTouch.idBits.clear();
4218 for (uint32_t i = 0; i < currentPointerCount; i++) {
4219 mCurrentTouch.pointers[i].id = i;
4220 mCurrentTouch.idToIndex[i] = i;
4221 mCurrentTouch.idBits.markBit(i);
4222 }
4223 } else if (currentPointerCount == 1 && lastPointerCount == 1) {
4224 // Only one pointer and no change in count so it must have the same id as before.
4225 uint32_t id = mLastTouch.pointers[0].id;
4226 mCurrentTouch.pointers[0].id = id;
4227 mCurrentTouch.idToIndex[id] = 0;
4228 mCurrentTouch.idBits.value = BitSet32::valueForBit(id);
4229 } else {
4230 // General case.
4231 // We build a heap of squared euclidean distances between current and last pointers
4232 // associated with the current and last pointer indices. Then, we find the best
4233 // match (by distance) for each current pointer.
4234 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
4235
4236 uint32_t heapSize = 0;
4237 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
4238 currentPointerIndex++) {
4239 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
4240 lastPointerIndex++) {
4241 int64_t deltaX = mCurrentTouch.pointers[currentPointerIndex].x
4242 - mLastTouch.pointers[lastPointerIndex].x;
4243 int64_t deltaY = mCurrentTouch.pointers[currentPointerIndex].y
4244 - mLastTouch.pointers[lastPointerIndex].y;
4245
4246 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4247
4248 // Insert new element into the heap (sift up).
4249 heap[heapSize].currentPointerIndex = currentPointerIndex;
4250 heap[heapSize].lastPointerIndex = lastPointerIndex;
4251 heap[heapSize].distance = distance;
4252 heapSize += 1;
4253 }
4254 }
4255
4256 // Heapify
4257 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
4258 startIndex -= 1;
4259 for (uint32_t parentIndex = startIndex; ;) {
4260 uint32_t childIndex = parentIndex * 2 + 1;
4261 if (childIndex >= heapSize) {
4262 break;
4263 }
4264
4265 if (childIndex + 1 < heapSize
4266 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4267 childIndex += 1;
4268 }
4269
4270 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4271 break;
4272 }
4273
4274 swap(heap[parentIndex], heap[childIndex]);
4275 parentIndex = childIndex;
4276 }
4277 }
4278
4279#if DEBUG_POINTER_ASSIGNMENT
4280 LOGD("calculatePointerIds - initial distance min-heap: size=%d", heapSize);
4281 for (size_t i = 0; i < heapSize; i++) {
4282 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4283 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4284 heap[i].distance);
4285 }
4286#endif
4287
4288 // Pull matches out by increasing order of distance.
4289 // To avoid reassigning pointers that have already been matched, the loop keeps track
4290 // of which last and current pointers have been matched using the matchedXXXBits variables.
4291 // It also tracks the used pointer id bits.
4292 BitSet32 matchedLastBits(0);
4293 BitSet32 matchedCurrentBits(0);
4294 BitSet32 usedIdBits(0);
4295 bool first = true;
4296 for (uint32_t i = min(currentPointerCount, lastPointerCount); i > 0; i--) {
4297 for (;;) {
4298 if (first) {
4299 // The first time through the loop, we just consume the root element of
4300 // the heap (the one with smallest distance).
4301 first = false;
4302 } else {
4303 // Previous iterations consumed the root element of the heap.
4304 // Pop root element off of the heap (sift down).
4305 heapSize -= 1;
4306 assert(heapSize > 0);
4307
4308 // Sift down.
4309 heap[0] = heap[heapSize];
4310 for (uint32_t parentIndex = 0; ;) {
4311 uint32_t childIndex = parentIndex * 2 + 1;
4312 if (childIndex >= heapSize) {
4313 break;
4314 }
4315
4316 if (childIndex + 1 < heapSize
4317 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4318 childIndex += 1;
4319 }
4320
4321 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4322 break;
4323 }
4324
4325 swap(heap[parentIndex], heap[childIndex]);
4326 parentIndex = childIndex;
4327 }
4328
4329#if DEBUG_POINTER_ASSIGNMENT
4330 LOGD("calculatePointerIds - reduced distance min-heap: size=%d", heapSize);
4331 for (size_t i = 0; i < heapSize; i++) {
4332 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4333 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4334 heap[i].distance);
4335 }
4336#endif
4337 }
4338
4339 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4340 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4341
4342 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4343 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4344
4345 matchedCurrentBits.markBit(currentPointerIndex);
4346 matchedLastBits.markBit(lastPointerIndex);
4347
4348 uint32_t id = mLastTouch.pointers[lastPointerIndex].id;
4349 mCurrentTouch.pointers[currentPointerIndex].id = id;
4350 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4351 usedIdBits.markBit(id);
4352
4353#if DEBUG_POINTER_ASSIGNMENT
4354 LOGD("calculatePointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
4355 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
4356#endif
4357 break;
4358 }
4359 }
4360
4361 // Assign fresh ids to new pointers.
4362 if (currentPointerCount > lastPointerCount) {
4363 for (uint32_t i = currentPointerCount - lastPointerCount; ;) {
4364 uint32_t currentPointerIndex = matchedCurrentBits.firstUnmarkedBit();
4365 uint32_t id = usedIdBits.firstUnmarkedBit();
4366
4367 mCurrentTouch.pointers[currentPointerIndex].id = id;
4368 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4369 usedIdBits.markBit(id);
4370
4371#if DEBUG_POINTER_ASSIGNMENT
4372 LOGD("calculatePointerIds - assigned: cur=%d, id=%d",
4373 currentPointerIndex, id);
4374#endif
4375
4376 if (--i == 0) break; // done
4377 matchedCurrentBits.markBit(currentPointerIndex);
4378 }
4379 }
4380
4381 // Fix id bits.
4382 mCurrentTouch.idBits = usedIdBits;
4383 }
4384}
4385
4386/* Special hack for devices that have bad screen data: if one of the
4387 * points has moved more than a screen height from the last position,
4388 * then drop it. */
4389bool TouchInputMapper::applyBadTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004390 uint32_t pointerCount = mCurrentTouch.pointerCount;
4391
4392 // Nothing to do if there are no points.
4393 if (pointerCount == 0) {
4394 return false;
4395 }
4396
4397 // Don't do anything if a finger is going down or up. We run
4398 // here before assigning pointer IDs, so there isn't a good
4399 // way to do per-finger matching.
4400 if (pointerCount != mLastTouch.pointerCount) {
4401 return false;
4402 }
4403
4404 // We consider a single movement across more than a 7/16 of
4405 // the long size of the screen to be bad. This was a magic value
4406 // determined by looking at the maximum distance it is feasible
4407 // to actually move in one sample.
Jeff Brown9626b142011-03-03 02:09:54 -08004408 int32_t maxDeltaY = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) * 7 / 16;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004409
4410 // XXX The original code in InputDevice.java included commented out
4411 // code for testing the X axis. Note that when we drop a point
4412 // we don't actually restore the old X either. Strange.
4413 // The old code also tries to track when bad points were previously
4414 // detected but it turns out that due to the placement of a "break"
4415 // at the end of the loop, we never set mDroppedBadPoint to true
4416 // so it is effectively dead code.
4417 // Need to figure out if the old code is busted or just overcomplicated
4418 // but working as intended.
4419
4420 // Look through all new points and see if any are farther than
4421 // acceptable from all previous points.
4422 for (uint32_t i = pointerCount; i-- > 0; ) {
4423 int32_t y = mCurrentTouch.pointers[i].y;
4424 int32_t closestY = INT_MAX;
4425 int32_t closestDeltaY = 0;
4426
4427#if DEBUG_HACKS
4428 LOGD("BadTouchFilter: Looking at next point #%d: y=%d", i, y);
4429#endif
4430
4431 for (uint32_t j = pointerCount; j-- > 0; ) {
4432 int32_t lastY = mLastTouch.pointers[j].y;
4433 int32_t deltaY = abs(y - lastY);
4434
4435#if DEBUG_HACKS
4436 LOGD("BadTouchFilter: Comparing with last point #%d: y=%d deltaY=%d",
4437 j, lastY, deltaY);
4438#endif
4439
4440 if (deltaY < maxDeltaY) {
4441 goto SkipSufficientlyClosePoint;
4442 }
4443 if (deltaY < closestDeltaY) {
4444 closestDeltaY = deltaY;
4445 closestY = lastY;
4446 }
4447 }
4448
4449 // Must not have found a close enough match.
4450#if DEBUG_HACKS
4451 LOGD("BadTouchFilter: Dropping bad point #%d: newY=%d oldY=%d deltaY=%d maxDeltaY=%d",
4452 i, y, closestY, closestDeltaY, maxDeltaY);
4453#endif
4454
4455 mCurrentTouch.pointers[i].y = closestY;
4456 return true; // XXX original code only corrects one point
4457
4458 SkipSufficientlyClosePoint: ;
4459 }
4460
4461 // No change.
4462 return false;
4463}
4464
4465/* Special hack for devices that have bad screen data: drop points where
4466 * the coordinate value for one axis has jumped to the other pointer's location.
4467 */
4468bool TouchInputMapper::applyJumpyTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004469 uint32_t pointerCount = mCurrentTouch.pointerCount;
4470 if (mLastTouch.pointerCount != pointerCount) {
4471#if DEBUG_HACKS
4472 LOGD("JumpyTouchFilter: Different pointer count %d -> %d",
4473 mLastTouch.pointerCount, pointerCount);
4474 for (uint32_t i = 0; i < pointerCount; i++) {
4475 LOGD(" Pointer %d (%d, %d)", i,
4476 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4477 }
4478#endif
4479
4480 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_TRANSITION_DROPS) {
4481 if (mLastTouch.pointerCount == 1 && pointerCount == 2) {
4482 // Just drop the first few events going from 1 to 2 pointers.
4483 // They're bad often enough that they're not worth considering.
4484 mCurrentTouch.pointerCount = 1;
4485 mJumpyTouchFilter.jumpyPointsDropped += 1;
4486
4487#if DEBUG_HACKS
4488 LOGD("JumpyTouchFilter: Pointer 2 dropped");
4489#endif
4490 return true;
4491 } else if (mLastTouch.pointerCount == 2 && pointerCount == 1) {
4492 // The event when we go from 2 -> 1 tends to be messed up too
4493 mCurrentTouch.pointerCount = 2;
4494 mCurrentTouch.pointers[0] = mLastTouch.pointers[0];
4495 mCurrentTouch.pointers[1] = mLastTouch.pointers[1];
4496 mJumpyTouchFilter.jumpyPointsDropped += 1;
4497
4498#if DEBUG_HACKS
4499 for (int32_t i = 0; i < 2; i++) {
4500 LOGD("JumpyTouchFilter: Pointer %d replaced (%d, %d)", i,
4501 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4502 }
4503#endif
4504 return true;
4505 }
4506 }
4507 // Reset jumpy points dropped on other transitions or if limit exceeded.
4508 mJumpyTouchFilter.jumpyPointsDropped = 0;
4509
4510#if DEBUG_HACKS
4511 LOGD("JumpyTouchFilter: Transition - drop limit reset");
4512#endif
4513 return false;
4514 }
4515
4516 // We have the same number of pointers as last time.
4517 // A 'jumpy' point is one where the coordinate value for one axis
4518 // has jumped to the other pointer's location. No need to do anything
4519 // else if we only have one pointer.
4520 if (pointerCount < 2) {
4521 return false;
4522 }
4523
4524 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_DROP_LIMIT) {
Jeff Brown9626b142011-03-03 02:09:54 -08004525 int jumpyEpsilon = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) / JUMPY_EPSILON_DIVISOR;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004526
4527 // We only replace the single worst jumpy point as characterized by pointer distance
4528 // in a single axis.
4529 int32_t badPointerIndex = -1;
4530 int32_t badPointerReplacementIndex = -1;
4531 int32_t badPointerDistance = INT_MIN; // distance to be corrected
4532
4533 for (uint32_t i = pointerCount; i-- > 0; ) {
4534 int32_t x = mCurrentTouch.pointers[i].x;
4535 int32_t y = mCurrentTouch.pointers[i].y;
4536
4537#if DEBUG_HACKS
4538 LOGD("JumpyTouchFilter: Point %d (%d, %d)", i, x, y);
4539#endif
4540
4541 // Check if a touch point is too close to another's coordinates
4542 bool dropX = false, dropY = false;
4543 for (uint32_t j = 0; j < pointerCount; j++) {
4544 if (i == j) {
4545 continue;
4546 }
4547
4548 if (abs(x - mCurrentTouch.pointers[j].x) <= jumpyEpsilon) {
4549 dropX = true;
4550 break;
4551 }
4552
4553 if (abs(y - mCurrentTouch.pointers[j].y) <= jumpyEpsilon) {
4554 dropY = true;
4555 break;
4556 }
4557 }
4558 if (! dropX && ! dropY) {
4559 continue; // not jumpy
4560 }
4561
4562 // Find a replacement candidate by comparing with older points on the
4563 // complementary (non-jumpy) axis.
4564 int32_t distance = INT_MIN; // distance to be corrected
4565 int32_t replacementIndex = -1;
4566
4567 if (dropX) {
4568 // X looks too close. Find an older replacement point with a close Y.
4569 int32_t smallestDeltaY = INT_MAX;
4570 for (uint32_t j = 0; j < pointerCount; j++) {
4571 int32_t deltaY = abs(y - mLastTouch.pointers[j].y);
4572 if (deltaY < smallestDeltaY) {
4573 smallestDeltaY = deltaY;
4574 replacementIndex = j;
4575 }
4576 }
4577 distance = abs(x - mLastTouch.pointers[replacementIndex].x);
4578 } else {
4579 // Y looks too close. Find an older replacement point with a close X.
4580 int32_t smallestDeltaX = INT_MAX;
4581 for (uint32_t j = 0; j < pointerCount; j++) {
4582 int32_t deltaX = abs(x - mLastTouch.pointers[j].x);
4583 if (deltaX < smallestDeltaX) {
4584 smallestDeltaX = deltaX;
4585 replacementIndex = j;
4586 }
4587 }
4588 distance = abs(y - mLastTouch.pointers[replacementIndex].y);
4589 }
4590
4591 // If replacing this pointer would correct a worse error than the previous ones
4592 // considered, then use this replacement instead.
4593 if (distance > badPointerDistance) {
4594 badPointerIndex = i;
4595 badPointerReplacementIndex = replacementIndex;
4596 badPointerDistance = distance;
4597 }
4598 }
4599
4600 // Correct the jumpy pointer if one was found.
4601 if (badPointerIndex >= 0) {
4602#if DEBUG_HACKS
4603 LOGD("JumpyTouchFilter: Replacing bad pointer %d with (%d, %d)",
4604 badPointerIndex,
4605 mLastTouch.pointers[badPointerReplacementIndex].x,
4606 mLastTouch.pointers[badPointerReplacementIndex].y);
4607#endif
4608
4609 mCurrentTouch.pointers[badPointerIndex].x =
4610 mLastTouch.pointers[badPointerReplacementIndex].x;
4611 mCurrentTouch.pointers[badPointerIndex].y =
4612 mLastTouch.pointers[badPointerReplacementIndex].y;
4613 mJumpyTouchFilter.jumpyPointsDropped += 1;
4614 return true;
4615 }
4616 }
4617
4618 mJumpyTouchFilter.jumpyPointsDropped = 0;
4619 return false;
4620}
4621
4622/* Special hack for devices that have bad screen data: aggregate and
4623 * compute averages of the coordinate data, to reduce the amount of
4624 * jitter seen by applications. */
4625void TouchInputMapper::applyAveragingTouchFilter() {
4626 for (uint32_t currentIndex = 0; currentIndex < mCurrentTouch.pointerCount; currentIndex++) {
4627 uint32_t id = mCurrentTouch.pointers[currentIndex].id;
4628 int32_t x = mCurrentTouch.pointers[currentIndex].x;
4629 int32_t y = mCurrentTouch.pointers[currentIndex].y;
Jeff Brown8d608662010-08-30 03:02:23 -07004630 int32_t pressure;
4631 switch (mCalibration.pressureSource) {
4632 case Calibration::PRESSURE_SOURCE_PRESSURE:
4633 pressure = mCurrentTouch.pointers[currentIndex].pressure;
4634 break;
4635 case Calibration::PRESSURE_SOURCE_TOUCH:
4636 pressure = mCurrentTouch.pointers[currentIndex].touchMajor;
4637 break;
4638 default:
4639 pressure = 1;
4640 break;
4641 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004642
4643 if (mLastTouch.idBits.hasBit(id)) {
4644 // Pointer was down before and is still down now.
4645 // Compute average over history trace.
4646 uint32_t start = mAveragingTouchFilter.historyStart[id];
4647 uint32_t end = mAveragingTouchFilter.historyEnd[id];
4648
4649 int64_t deltaX = x - mAveragingTouchFilter.historyData[end].pointers[id].x;
4650 int64_t deltaY = y - mAveragingTouchFilter.historyData[end].pointers[id].y;
4651 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4652
4653#if DEBUG_HACKS
4654 LOGD("AveragingTouchFilter: Pointer id %d - Distance from last sample: %lld",
4655 id, distance);
4656#endif
4657
4658 if (distance < AVERAGING_DISTANCE_LIMIT) {
4659 // Increment end index in preparation for recording new historical data.
4660 end += 1;
4661 if (end > AVERAGING_HISTORY_SIZE) {
4662 end = 0;
4663 }
4664
4665 // If the end index has looped back to the start index then we have filled
4666 // the historical trace up to the desired size so we drop the historical
4667 // data at the start of the trace.
4668 if (end == start) {
4669 start += 1;
4670 if (start > AVERAGING_HISTORY_SIZE) {
4671 start = 0;
4672 }
4673 }
4674
4675 // Add the raw data to the historical trace.
4676 mAveragingTouchFilter.historyStart[id] = start;
4677 mAveragingTouchFilter.historyEnd[id] = end;
4678 mAveragingTouchFilter.historyData[end].pointers[id].x = x;
4679 mAveragingTouchFilter.historyData[end].pointers[id].y = y;
4680 mAveragingTouchFilter.historyData[end].pointers[id].pressure = pressure;
4681
4682 // Average over all historical positions in the trace by total pressure.
4683 int32_t averagedX = 0;
4684 int32_t averagedY = 0;
4685 int32_t totalPressure = 0;
4686 for (;;) {
4687 int32_t historicalX = mAveragingTouchFilter.historyData[start].pointers[id].x;
4688 int32_t historicalY = mAveragingTouchFilter.historyData[start].pointers[id].y;
4689 int32_t historicalPressure = mAveragingTouchFilter.historyData[start]
4690 .pointers[id].pressure;
4691
4692 averagedX += historicalX * historicalPressure;
4693 averagedY += historicalY * historicalPressure;
4694 totalPressure += historicalPressure;
4695
4696 if (start == end) {
4697 break;
4698 }
4699
4700 start += 1;
4701 if (start > AVERAGING_HISTORY_SIZE) {
4702 start = 0;
4703 }
4704 }
4705
Jeff Brown8d608662010-08-30 03:02:23 -07004706 if (totalPressure != 0) {
4707 averagedX /= totalPressure;
4708 averagedY /= totalPressure;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004709
4710#if DEBUG_HACKS
Jeff Brown8d608662010-08-30 03:02:23 -07004711 LOGD("AveragingTouchFilter: Pointer id %d - "
4712 "totalPressure=%d, averagedX=%d, averagedY=%d", id, totalPressure,
4713 averagedX, averagedY);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004714#endif
4715
Jeff Brown8d608662010-08-30 03:02:23 -07004716 mCurrentTouch.pointers[currentIndex].x = averagedX;
4717 mCurrentTouch.pointers[currentIndex].y = averagedY;
4718 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004719 } else {
4720#if DEBUG_HACKS
4721 LOGD("AveragingTouchFilter: Pointer id %d - Exceeded max distance", id);
4722#endif
4723 }
4724 } else {
4725#if DEBUG_HACKS
4726 LOGD("AveragingTouchFilter: Pointer id %d - Pointer went up", id);
4727#endif
4728 }
4729
4730 // Reset pointer history.
4731 mAveragingTouchFilter.historyStart[id] = 0;
4732 mAveragingTouchFilter.historyEnd[id] = 0;
4733 mAveragingTouchFilter.historyData[0].pointers[id].x = x;
4734 mAveragingTouchFilter.historyData[0].pointers[id].y = y;
4735 mAveragingTouchFilter.historyData[0].pointers[id].pressure = pressure;
4736 }
4737}
4738
4739int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004740 { // acquire lock
4741 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004742
Jeff Brown6328cdc2010-07-29 18:18:33 -07004743 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.keyCode == keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004744 return AKEY_STATE_VIRTUAL;
4745 }
4746
Jeff Brown6328cdc2010-07-29 18:18:33 -07004747 size_t numVirtualKeys = mLocked.virtualKeys.size();
4748 for (size_t i = 0; i < numVirtualKeys; i++) {
4749 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004750 if (virtualKey.keyCode == keyCode) {
4751 return AKEY_STATE_UP;
4752 }
4753 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004754 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004755
4756 return AKEY_STATE_UNKNOWN;
4757}
4758
4759int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004760 { // acquire lock
4761 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004762
Jeff Brown6328cdc2010-07-29 18:18:33 -07004763 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004764 return AKEY_STATE_VIRTUAL;
4765 }
4766
Jeff Brown6328cdc2010-07-29 18:18:33 -07004767 size_t numVirtualKeys = mLocked.virtualKeys.size();
4768 for (size_t i = 0; i < numVirtualKeys; i++) {
4769 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004770 if (virtualKey.scanCode == scanCode) {
4771 return AKEY_STATE_UP;
4772 }
4773 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004774 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004775
4776 return AKEY_STATE_UNKNOWN;
4777}
4778
4779bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4780 const int32_t* keyCodes, uint8_t* outFlags) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004781 { // acquire lock
4782 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004783
Jeff Brown6328cdc2010-07-29 18:18:33 -07004784 size_t numVirtualKeys = mLocked.virtualKeys.size();
4785 for (size_t i = 0; i < numVirtualKeys; i++) {
4786 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004787
4788 for (size_t i = 0; i < numCodes; i++) {
4789 if (virtualKey.keyCode == keyCodes[i]) {
4790 outFlags[i] = 1;
4791 }
4792 }
4793 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004794 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004795
4796 return true;
4797}
4798
4799
4800// --- SingleTouchInputMapper ---
4801
Jeff Brown47e6b1b2010-11-29 17:37:49 -08004802SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
4803 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004804 initialize();
4805}
4806
4807SingleTouchInputMapper::~SingleTouchInputMapper() {
4808}
4809
4810void SingleTouchInputMapper::initialize() {
4811 mAccumulator.clear();
4812
4813 mDown = false;
4814 mX = 0;
4815 mY = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07004816 mPressure = 0; // default to 0 for devices that don't report pressure
4817 mToolWidth = 0; // default to 0 for devices that don't report tool width
Jeff Brown96ad3972011-03-09 17:39:48 -08004818 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004819}
4820
4821void SingleTouchInputMapper::reset() {
4822 TouchInputMapper::reset();
4823
Jeff Brown6d0fec22010-07-23 21:28:06 -07004824 initialize();
4825 }
4826
4827void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
4828 switch (rawEvent->type) {
4829 case EV_KEY:
4830 switch (rawEvent->scanCode) {
4831 case BTN_TOUCH:
4832 mAccumulator.fields |= Accumulator::FIELD_BTN_TOUCH;
4833 mAccumulator.btnTouch = rawEvent->value != 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004834 // Don't sync immediately. Wait until the next SYN_REPORT since we might
4835 // not have received valid position information yet. This logic assumes that
4836 // BTN_TOUCH is always followed by SYN_REPORT as part of a complete packet.
Jeff Brown6d0fec22010-07-23 21:28:06 -07004837 break;
Jeff Brown96ad3972011-03-09 17:39:48 -08004838 default:
4839 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
4840 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
4841 if (buttonState) {
4842 if (rawEvent->value) {
4843 mAccumulator.buttonDown |= buttonState;
4844 } else {
4845 mAccumulator.buttonUp |= buttonState;
4846 }
4847 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
4848 }
4849 }
4850 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004851 }
4852 break;
4853
4854 case EV_ABS:
4855 switch (rawEvent->scanCode) {
4856 case ABS_X:
4857 mAccumulator.fields |= Accumulator::FIELD_ABS_X;
4858 mAccumulator.absX = rawEvent->value;
4859 break;
4860 case ABS_Y:
4861 mAccumulator.fields |= Accumulator::FIELD_ABS_Y;
4862 mAccumulator.absY = rawEvent->value;
4863 break;
4864 case ABS_PRESSURE:
4865 mAccumulator.fields |= Accumulator::FIELD_ABS_PRESSURE;
4866 mAccumulator.absPressure = rawEvent->value;
4867 break;
4868 case ABS_TOOL_WIDTH:
4869 mAccumulator.fields |= Accumulator::FIELD_ABS_TOOL_WIDTH;
4870 mAccumulator.absToolWidth = rawEvent->value;
4871 break;
4872 }
4873 break;
4874
4875 case EV_SYN:
4876 switch (rawEvent->scanCode) {
4877 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004878 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004879 break;
4880 }
4881 break;
4882 }
4883}
4884
4885void SingleTouchInputMapper::sync(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004886 uint32_t fields = mAccumulator.fields;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004887 if (fields == 0) {
4888 return; // no new state changes, so nothing to do
4889 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004890
4891 if (fields & Accumulator::FIELD_BTN_TOUCH) {
4892 mDown = mAccumulator.btnTouch;
4893 }
4894
4895 if (fields & Accumulator::FIELD_ABS_X) {
4896 mX = mAccumulator.absX;
4897 }
4898
4899 if (fields & Accumulator::FIELD_ABS_Y) {
4900 mY = mAccumulator.absY;
4901 }
4902
4903 if (fields & Accumulator::FIELD_ABS_PRESSURE) {
4904 mPressure = mAccumulator.absPressure;
4905 }
4906
4907 if (fields & Accumulator::FIELD_ABS_TOOL_WIDTH) {
Jeff Brown8d608662010-08-30 03:02:23 -07004908 mToolWidth = mAccumulator.absToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004909 }
4910
Jeff Brown96ad3972011-03-09 17:39:48 -08004911 if (fields & Accumulator::FIELD_BUTTONS) {
4912 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
4913 }
4914
Jeff Brown6d0fec22010-07-23 21:28:06 -07004915 mCurrentTouch.clear();
4916
4917 if (mDown) {
4918 mCurrentTouch.pointerCount = 1;
4919 mCurrentTouch.pointers[0].id = 0;
4920 mCurrentTouch.pointers[0].x = mX;
4921 mCurrentTouch.pointers[0].y = mY;
4922 mCurrentTouch.pointers[0].pressure = mPressure;
Jeff Brown8d608662010-08-30 03:02:23 -07004923 mCurrentTouch.pointers[0].touchMajor = 0;
4924 mCurrentTouch.pointers[0].touchMinor = 0;
4925 mCurrentTouch.pointers[0].toolMajor = mToolWidth;
4926 mCurrentTouch.pointers[0].toolMinor = mToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004927 mCurrentTouch.pointers[0].orientation = 0;
4928 mCurrentTouch.idToIndex[0] = 0;
4929 mCurrentTouch.idBits.markBit(0);
Jeff Brown96ad3972011-03-09 17:39:48 -08004930 mCurrentTouch.buttonState = mButtonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004931 }
4932
4933 syncTouch(when, true);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004934
4935 mAccumulator.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07004936}
4937
Jeff Brown8d608662010-08-30 03:02:23 -07004938void SingleTouchInputMapper::configureRawAxes() {
4939 TouchInputMapper::configureRawAxes();
Jeff Brown6d0fec22010-07-23 21:28:06 -07004940
Jeff Brown8d608662010-08-30 03:02:23 -07004941 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_X, & mRawAxes.x);
4942 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_Y, & mRawAxes.y);
4943 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_PRESSURE, & mRawAxes.pressure);
4944 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_TOOL_WIDTH, & mRawAxes.toolMajor);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004945}
4946
4947
4948// --- MultiTouchInputMapper ---
4949
Jeff Brown47e6b1b2010-11-29 17:37:49 -08004950MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
4951 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004952 initialize();
4953}
4954
4955MultiTouchInputMapper::~MultiTouchInputMapper() {
4956}
4957
4958void MultiTouchInputMapper::initialize() {
4959 mAccumulator.clear();
Jeff Brown96ad3972011-03-09 17:39:48 -08004960 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004961}
4962
4963void MultiTouchInputMapper::reset() {
4964 TouchInputMapper::reset();
4965
Jeff Brown6d0fec22010-07-23 21:28:06 -07004966 initialize();
4967}
4968
4969void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
4970 switch (rawEvent->type) {
Jeff Brown96ad3972011-03-09 17:39:48 -08004971 case EV_KEY: {
4972 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
4973 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
4974 if (buttonState) {
4975 if (rawEvent->value) {
4976 mAccumulator.buttonDown |= buttonState;
4977 } else {
4978 mAccumulator.buttonUp |= buttonState;
4979 }
4980 }
4981 }
4982 break;
4983 }
4984
Jeff Brown6d0fec22010-07-23 21:28:06 -07004985 case EV_ABS: {
4986 uint32_t pointerIndex = mAccumulator.pointerCount;
4987 Accumulator::Pointer* pointer = & mAccumulator.pointers[pointerIndex];
4988
4989 switch (rawEvent->scanCode) {
4990 case ABS_MT_POSITION_X:
4991 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_X;
4992 pointer->absMTPositionX = rawEvent->value;
4993 break;
4994 case ABS_MT_POSITION_Y:
4995 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_Y;
4996 pointer->absMTPositionY = rawEvent->value;
4997 break;
4998 case ABS_MT_TOUCH_MAJOR:
4999 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MAJOR;
5000 pointer->absMTTouchMajor = rawEvent->value;
5001 break;
5002 case ABS_MT_TOUCH_MINOR:
5003 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MINOR;
5004 pointer->absMTTouchMinor = rawEvent->value;
5005 break;
5006 case ABS_MT_WIDTH_MAJOR:
5007 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MAJOR;
5008 pointer->absMTWidthMajor = rawEvent->value;
5009 break;
5010 case ABS_MT_WIDTH_MINOR:
5011 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MINOR;
5012 pointer->absMTWidthMinor = rawEvent->value;
5013 break;
5014 case ABS_MT_ORIENTATION:
5015 pointer->fields |= Accumulator::FIELD_ABS_MT_ORIENTATION;
5016 pointer->absMTOrientation = rawEvent->value;
5017 break;
5018 case ABS_MT_TRACKING_ID:
5019 pointer->fields |= Accumulator::FIELD_ABS_MT_TRACKING_ID;
5020 pointer->absMTTrackingId = rawEvent->value;
5021 break;
Jeff Brown8d608662010-08-30 03:02:23 -07005022 case ABS_MT_PRESSURE:
5023 pointer->fields |= Accumulator::FIELD_ABS_MT_PRESSURE;
5024 pointer->absMTPressure = rawEvent->value;
5025 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005026 }
5027 break;
5028 }
5029
5030 case EV_SYN:
5031 switch (rawEvent->scanCode) {
5032 case SYN_MT_REPORT: {
5033 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
5034 uint32_t pointerIndex = mAccumulator.pointerCount;
5035
5036 if (mAccumulator.pointers[pointerIndex].fields) {
5037 if (pointerIndex == MAX_POINTERS) {
5038 LOGW("MultiTouch device driver returned more than maximum of %d pointers.",
5039 MAX_POINTERS);
5040 } else {
5041 pointerIndex += 1;
5042 mAccumulator.pointerCount = pointerIndex;
5043 }
5044 }
5045
5046 mAccumulator.pointers[pointerIndex].clear();
5047 break;
5048 }
5049
5050 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005051 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005052 break;
5053 }
5054 break;
5055 }
5056}
5057
5058void MultiTouchInputMapper::sync(nsecs_t when) {
5059 static const uint32_t REQUIRED_FIELDS =
Jeff Brown8d608662010-08-30 03:02:23 -07005060 Accumulator::FIELD_ABS_MT_POSITION_X | Accumulator::FIELD_ABS_MT_POSITION_Y;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005061
Jeff Brown6d0fec22010-07-23 21:28:06 -07005062 uint32_t inCount = mAccumulator.pointerCount;
5063 uint32_t outCount = 0;
5064 bool havePointerIds = true;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005065
Jeff Brown6d0fec22010-07-23 21:28:06 -07005066 mCurrentTouch.clear();
Jeff Brown46b9ac02010-04-22 18:58:52 -07005067
Jeff Brown6d0fec22010-07-23 21:28:06 -07005068 for (uint32_t inIndex = 0; inIndex < inCount; inIndex++) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005069 const Accumulator::Pointer& inPointer = mAccumulator.pointers[inIndex];
5070 uint32_t fields = inPointer.fields;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005071
Jeff Brown6d0fec22010-07-23 21:28:06 -07005072 if ((fields & REQUIRED_FIELDS) != REQUIRED_FIELDS) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005073 // Some drivers send empty MT sync packets without X / Y to indicate a pointer up.
5074 // Drop this finger.
Jeff Brown46b9ac02010-04-22 18:58:52 -07005075 continue;
5076 }
5077
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005078 PointerData& outPointer = mCurrentTouch.pointers[outCount];
5079 outPointer.x = inPointer.absMTPositionX;
5080 outPointer.y = inPointer.absMTPositionY;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005081
Jeff Brown8d608662010-08-30 03:02:23 -07005082 if (fields & Accumulator::FIELD_ABS_MT_PRESSURE) {
5083 if (inPointer.absMTPressure <= 0) {
Jeff Brownc3db8582010-10-20 15:33:38 -07005084 // Some devices send sync packets with X / Y but with a 0 pressure to indicate
5085 // a pointer going up. Drop this finger.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005086 continue;
5087 }
Jeff Brown8d608662010-08-30 03:02:23 -07005088 outPointer.pressure = inPointer.absMTPressure;
5089 } else {
5090 // Default pressure to 0 if absent.
5091 outPointer.pressure = 0;
5092 }
5093
5094 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MAJOR) {
5095 if (inPointer.absMTTouchMajor <= 0) {
5096 // Some devices send sync packets with X / Y but with a 0 touch major to indicate
5097 // a pointer going up. Drop this finger.
5098 continue;
5099 }
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005100 outPointer.touchMajor = inPointer.absMTTouchMajor;
5101 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005102 // Default touch area to 0 if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005103 outPointer.touchMajor = 0;
5104 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07005105
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005106 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MINOR) {
5107 outPointer.touchMinor = inPointer.absMTTouchMinor;
5108 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005109 // Assume touch area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005110 outPointer.touchMinor = outPointer.touchMajor;
5111 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07005112
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005113 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MAJOR) {
5114 outPointer.toolMajor = inPointer.absMTWidthMajor;
5115 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005116 // Default tool area to 0 if absent.
5117 outPointer.toolMajor = 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005118 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07005119
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005120 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MINOR) {
5121 outPointer.toolMinor = inPointer.absMTWidthMinor;
5122 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005123 // Assume tool area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005124 outPointer.toolMinor = outPointer.toolMajor;
5125 }
5126
5127 if (fields & Accumulator::FIELD_ABS_MT_ORIENTATION) {
5128 outPointer.orientation = inPointer.absMTOrientation;
5129 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005130 // Default orientation to vertical if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005131 outPointer.orientation = 0;
5132 }
5133
Jeff Brown8d608662010-08-30 03:02:23 -07005134 // Assign pointer id using tracking id if available.
Jeff Brown6d0fec22010-07-23 21:28:06 -07005135 if (havePointerIds) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005136 if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) {
5137 uint32_t id = uint32_t(inPointer.absMTTrackingId);
Jeff Brown46b9ac02010-04-22 18:58:52 -07005138
Jeff Brown6d0fec22010-07-23 21:28:06 -07005139 if (id > MAX_POINTER_ID) {
5140#if DEBUG_POINTERS
5141 LOGD("Pointers: Ignoring driver provided pointer id %d because "
Jeff Brown01ce2e92010-09-26 22:20:12 -07005142 "it is larger than max supported id %d",
Jeff Brown6d0fec22010-07-23 21:28:06 -07005143 id, MAX_POINTER_ID);
5144#endif
5145 havePointerIds = false;
5146 }
5147 else {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005148 outPointer.id = id;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005149 mCurrentTouch.idToIndex[id] = outCount;
5150 mCurrentTouch.idBits.markBit(id);
5151 }
5152 } else {
5153 havePointerIds = false;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005154 }
5155 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07005156
Jeff Brown6d0fec22010-07-23 21:28:06 -07005157 outCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005158 }
5159
Jeff Brown6d0fec22010-07-23 21:28:06 -07005160 mCurrentTouch.pointerCount = outCount;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005161
Jeff Brown96ad3972011-03-09 17:39:48 -08005162 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
5163 mCurrentTouch.buttonState = mButtonState;
5164
Jeff Brown6d0fec22010-07-23 21:28:06 -07005165 syncTouch(when, havePointerIds);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005166
5167 mAccumulator.clear();
Jeff Brown46b9ac02010-04-22 18:58:52 -07005168}
5169
Jeff Brown8d608662010-08-30 03:02:23 -07005170void MultiTouchInputMapper::configureRawAxes() {
5171 TouchInputMapper::configureRawAxes();
Jeff Brown46b9ac02010-04-22 18:58:52 -07005172
Jeff Brown8d608662010-08-30 03:02:23 -07005173 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_X, & mRawAxes.x);
5174 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_Y, & mRawAxes.y);
5175 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MAJOR, & mRawAxes.touchMajor);
5176 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MINOR, & mRawAxes.touchMinor);
5177 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MAJOR, & mRawAxes.toolMajor);
5178 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MINOR, & mRawAxes.toolMinor);
5179 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_ORIENTATION, & mRawAxes.orientation);
5180 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_PRESSURE, & mRawAxes.pressure);
Jeff Brown9c3cda02010-06-15 01:31:58 -07005181}
5182
Jeff Brown46b9ac02010-04-22 18:58:52 -07005183
Jeff Browncb1404e2011-01-15 18:14:15 -08005184// --- JoystickInputMapper ---
5185
5186JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
5187 InputMapper(device) {
Jeff Browncb1404e2011-01-15 18:14:15 -08005188}
5189
5190JoystickInputMapper::~JoystickInputMapper() {
5191}
5192
5193uint32_t JoystickInputMapper::getSources() {
5194 return AINPUT_SOURCE_JOYSTICK;
5195}
5196
5197void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
5198 InputMapper::populateDeviceInfo(info);
5199
Jeff Brown6f2fba42011-02-19 01:08:02 -08005200 for (size_t i = 0; i < mAxes.size(); i++) {
5201 const Axis& axis = mAxes.valueAt(i);
Jeff Brownefd32662011-03-08 15:13:06 -08005202 info->addMotionRange(axis.axisInfo.axis, AINPUT_SOURCE_JOYSTICK,
5203 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08005204 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
Jeff Brownefd32662011-03-08 15:13:06 -08005205 info->addMotionRange(axis.axisInfo.highAxis, AINPUT_SOURCE_JOYSTICK,
5206 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08005207 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005208 }
5209}
5210
5211void JoystickInputMapper::dump(String8& dump) {
5212 dump.append(INDENT2 "Joystick Input Mapper:\n");
5213
Jeff Brown6f2fba42011-02-19 01:08:02 -08005214 dump.append(INDENT3 "Axes:\n");
5215 size_t numAxes = mAxes.size();
5216 for (size_t i = 0; i < numAxes; i++) {
5217 const Axis& axis = mAxes.valueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005218 const char* label = getAxisLabel(axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005219 if (label) {
Jeff Brown85297452011-03-04 13:07:49 -08005220 dump.appendFormat(INDENT4 "%s", label);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005221 } else {
Jeff Brown85297452011-03-04 13:07:49 -08005222 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005223 }
Jeff Brown85297452011-03-04 13:07:49 -08005224 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5225 label = getAxisLabel(axis.axisInfo.highAxis);
5226 if (label) {
5227 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
5228 } else {
5229 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
5230 axis.axisInfo.splitValue);
5231 }
5232 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
5233 dump.append(" (invert)");
5234 }
5235
5236 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f\n",
5237 axis.min, axis.max, axis.flat, axis.fuzz);
5238 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
5239 "highScale=%0.5f, highOffset=%0.5f\n",
5240 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005241 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, rawFlat=%d, rawFuzz=%d\n",
5242 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
5243 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz);
Jeff Browncb1404e2011-01-15 18:14:15 -08005244 }
5245}
5246
5247void JoystickInputMapper::configure() {
5248 InputMapper::configure();
5249
Jeff Brown6f2fba42011-02-19 01:08:02 -08005250 // Collect all axes.
5251 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
5252 RawAbsoluteAxisInfo rawAxisInfo;
5253 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), abs, &rawAxisInfo);
5254 if (rawAxisInfo.valid) {
Jeff Brown85297452011-03-04 13:07:49 -08005255 // Map axis.
5256 AxisInfo axisInfo;
5257 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005258 if (!explicitlyMapped) {
5259 // Axis is not explicitly mapped, will choose a generic axis later.
Jeff Brown85297452011-03-04 13:07:49 -08005260 axisInfo.mode = AxisInfo::MODE_NORMAL;
5261 axisInfo.axis = -1;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005262 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005263
Jeff Brown85297452011-03-04 13:07:49 -08005264 // Apply flat override.
5265 int32_t rawFlat = axisInfo.flatOverride < 0
5266 ? rawAxisInfo.flat : axisInfo.flatOverride;
5267
5268 // Calculate scaling factors and limits.
Jeff Brown6f2fba42011-02-19 01:08:02 -08005269 Axis axis;
Jeff Brown85297452011-03-04 13:07:49 -08005270 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
5271 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
5272 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
5273 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5274 scale, 0.0f, highScale, 0.0f,
5275 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
5276 } else if (isCenteredAxis(axisInfo.axis)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005277 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
5278 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
Jeff Brown85297452011-03-04 13:07:49 -08005279 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5280 scale, offset, scale, offset,
5281 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005282 } else {
5283 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
Jeff Brown85297452011-03-04 13:07:49 -08005284 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5285 scale, 0.0f, scale, 0.0f,
5286 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005287 }
5288
5289 // To eliminate noise while the joystick is at rest, filter out small variations
5290 // in axis values up front.
5291 axis.filter = axis.flat * 0.25f;
5292
5293 mAxes.add(abs, axis);
5294 }
5295 }
5296
5297 // If there are too many axes, start dropping them.
5298 // Prefer to keep explicitly mapped axes.
5299 if (mAxes.size() > PointerCoords::MAX_AXES) {
5300 LOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.",
5301 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
5302 pruneAxes(true);
5303 pruneAxes(false);
5304 }
5305
5306 // Assign generic axis ids to remaining axes.
5307 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
5308 size_t numAxes = mAxes.size();
5309 for (size_t i = 0; i < numAxes; i++) {
5310 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005311 if (axis.axisInfo.axis < 0) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005312 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
5313 && haveAxis(nextGenericAxisId)) {
5314 nextGenericAxisId += 1;
5315 }
5316
5317 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
Jeff Brown85297452011-03-04 13:07:49 -08005318 axis.axisInfo.axis = nextGenericAxisId;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005319 nextGenericAxisId += 1;
5320 } else {
5321 LOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
5322 "have already been assigned to other axes.",
5323 getDeviceName().string(), mAxes.keyAt(i));
5324 mAxes.removeItemsAt(i--);
5325 numAxes -= 1;
5326 }
5327 }
5328 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005329}
5330
Jeff Brown85297452011-03-04 13:07:49 -08005331bool JoystickInputMapper::haveAxis(int32_t axisId) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005332 size_t numAxes = mAxes.size();
5333 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005334 const Axis& axis = mAxes.valueAt(i);
5335 if (axis.axisInfo.axis == axisId
5336 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
5337 && axis.axisInfo.highAxis == axisId)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005338 return true;
5339 }
5340 }
5341 return false;
5342}
Jeff Browncb1404e2011-01-15 18:14:15 -08005343
Jeff Brown6f2fba42011-02-19 01:08:02 -08005344void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
5345 size_t i = mAxes.size();
5346 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
5347 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
5348 continue;
5349 }
5350 LOGI("Discarding joystick '%s' axis %d because there are too many axes.",
5351 getDeviceName().string(), mAxes.keyAt(i));
5352 mAxes.removeItemsAt(i);
5353 }
5354}
5355
5356bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
5357 switch (axis) {
5358 case AMOTION_EVENT_AXIS_X:
5359 case AMOTION_EVENT_AXIS_Y:
5360 case AMOTION_EVENT_AXIS_Z:
5361 case AMOTION_EVENT_AXIS_RX:
5362 case AMOTION_EVENT_AXIS_RY:
5363 case AMOTION_EVENT_AXIS_RZ:
5364 case AMOTION_EVENT_AXIS_HAT_X:
5365 case AMOTION_EVENT_AXIS_HAT_Y:
5366 case AMOTION_EVENT_AXIS_ORIENTATION:
Jeff Brown85297452011-03-04 13:07:49 -08005367 case AMOTION_EVENT_AXIS_RUDDER:
5368 case AMOTION_EVENT_AXIS_WHEEL:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005369 return true;
5370 default:
5371 return false;
5372 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005373}
5374
5375void JoystickInputMapper::reset() {
5376 // Recenter all axes.
5377 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Browncb1404e2011-01-15 18:14:15 -08005378
Jeff Brown6f2fba42011-02-19 01:08:02 -08005379 size_t numAxes = mAxes.size();
5380 for (size_t i = 0; i < numAxes; i++) {
5381 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005382 axis.resetValue();
Jeff Brown6f2fba42011-02-19 01:08:02 -08005383 }
5384
5385 sync(when, true /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005386
5387 InputMapper::reset();
5388}
5389
5390void JoystickInputMapper::process(const RawEvent* rawEvent) {
5391 switch (rawEvent->type) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005392 case EV_ABS: {
5393 ssize_t index = mAxes.indexOfKey(rawEvent->scanCode);
5394 if (index >= 0) {
5395 Axis& axis = mAxes.editValueAt(index);
Jeff Brown85297452011-03-04 13:07:49 -08005396 float newValue, highNewValue;
5397 switch (axis.axisInfo.mode) {
5398 case AxisInfo::MODE_INVERT:
5399 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
5400 * axis.scale + axis.offset;
5401 highNewValue = 0.0f;
5402 break;
5403 case AxisInfo::MODE_SPLIT:
5404 if (rawEvent->value < axis.axisInfo.splitValue) {
5405 newValue = (axis.axisInfo.splitValue - rawEvent->value)
5406 * axis.scale + axis.offset;
5407 highNewValue = 0.0f;
5408 } else if (rawEvent->value > axis.axisInfo.splitValue) {
5409 newValue = 0.0f;
5410 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
5411 * axis.highScale + axis.highOffset;
5412 } else {
5413 newValue = 0.0f;
5414 highNewValue = 0.0f;
5415 }
5416 break;
5417 default:
5418 newValue = rawEvent->value * axis.scale + axis.offset;
5419 highNewValue = 0.0f;
5420 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005421 }
Jeff Brown85297452011-03-04 13:07:49 -08005422 axis.newValue = newValue;
5423 axis.highNewValue = highNewValue;
Jeff Browncb1404e2011-01-15 18:14:15 -08005424 }
5425 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005426 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005427
5428 case EV_SYN:
5429 switch (rawEvent->scanCode) {
5430 case SYN_REPORT:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005431 sync(rawEvent->when, false /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005432 break;
5433 }
5434 break;
5435 }
5436}
5437
Jeff Brown6f2fba42011-02-19 01:08:02 -08005438void JoystickInputMapper::sync(nsecs_t when, bool force) {
Jeff Brown85297452011-03-04 13:07:49 -08005439 if (!filterAxes(force)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005440 return;
Jeff Browncb1404e2011-01-15 18:14:15 -08005441 }
5442
5443 int32_t metaState = mContext->getGlobalMetaState();
5444
Jeff Brown6f2fba42011-02-19 01:08:02 -08005445 PointerCoords pointerCoords;
5446 pointerCoords.clear();
5447
5448 size_t numAxes = mAxes.size();
5449 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005450 const Axis& axis = mAxes.valueAt(i);
5451 pointerCoords.setAxisValue(axis.axisInfo.axis, axis.currentValue);
5452 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5453 pointerCoords.setAxisValue(axis.axisInfo.highAxis, axis.highCurrentValue);
5454 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005455 }
5456
Jeff Brown56194eb2011-03-02 19:23:13 -08005457 // Moving a joystick axis should not wake the devide because joysticks can
5458 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
5459 // button will likely wake the device.
5460 // TODO: Use the input device configuration to control this behavior more finely.
5461 uint32_t policyFlags = 0;
5462
Jeff Brown6f2fba42011-02-19 01:08:02 -08005463 int32_t pointerId = 0;
Jeff Brown56194eb2011-03-02 19:23:13 -08005464 getDispatcher()->notifyMotion(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Jeff Brown6f2fba42011-02-19 01:08:02 -08005465 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
5466 1, &pointerId, &pointerCoords, 0, 0, 0);
Jeff Browncb1404e2011-01-15 18:14:15 -08005467}
5468
Jeff Brown85297452011-03-04 13:07:49 -08005469bool JoystickInputMapper::filterAxes(bool force) {
5470 bool atLeastOneSignificantChange = force;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005471 size_t numAxes = mAxes.size();
5472 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005473 Axis& axis = mAxes.editValueAt(i);
5474 if (force || hasValueChangedSignificantly(axis.filter,
5475 axis.newValue, axis.currentValue, axis.min, axis.max)) {
5476 axis.currentValue = axis.newValue;
5477 atLeastOneSignificantChange = true;
5478 }
5479 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5480 if (force || hasValueChangedSignificantly(axis.filter,
5481 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
5482 axis.highCurrentValue = axis.highNewValue;
5483 atLeastOneSignificantChange = true;
5484 }
5485 }
5486 }
5487 return atLeastOneSignificantChange;
5488}
5489
5490bool JoystickInputMapper::hasValueChangedSignificantly(
5491 float filter, float newValue, float currentValue, float min, float max) {
5492 if (newValue != currentValue) {
5493 // Filter out small changes in value unless the value is converging on the axis
5494 // bounds or center point. This is intended to reduce the amount of information
5495 // sent to applications by particularly noisy joysticks (such as PS3).
5496 if (fabs(newValue - currentValue) > filter
5497 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
5498 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
5499 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
5500 return true;
5501 }
5502 }
5503 return false;
5504}
5505
5506bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
5507 float filter, float newValue, float currentValue, float thresholdValue) {
5508 float newDistance = fabs(newValue - thresholdValue);
5509 if (newDistance < filter) {
5510 float oldDistance = fabs(currentValue - thresholdValue);
5511 if (newDistance < oldDistance) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005512 return true;
5513 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005514 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08005515 return false;
Jeff Browncb1404e2011-01-15 18:14:15 -08005516}
5517
Jeff Brown46b9ac02010-04-22 18:58:52 -07005518} // namespace android