blob: 98b35268f09a8e10f80ea04c8645c93c42471f02 [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 Brownace13b12011-03-09 17:39:48 -080036// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
Jeff Brownb4ff35d2011-01-02 16:37:43 -080039#include "InputReader.h"
40
Jeff 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 Brownace13b12011-03-09 17:39:48 -080059// --- Constants ---
60
61// Quiet time between certain gesture transitions.
62// Time to allow for all fingers or buttons to settle into a stable state before
63// starting a new gesture.
64static const nsecs_t QUIET_INTERVAL = 100 * 1000000; // 100 ms
65
66// The minimum speed that a pointer must travel for us to consider switching the active
67// touch pointer to it during a drag. This threshold is set to avoid switching due
68// to noise from a finger resting on the touch pad (perhaps just pressing it down).
69static const float DRAG_MIN_SWITCH_SPEED = 50.0f; // pixels per second
70
71// Tap gesture delay time.
72// The time between down and up must be less than this to be considered a tap.
Jeff Brown2352b972011-04-12 22:39:53 -070073static const nsecs_t TAP_INTERVAL = 150 * 1000000; // 150 ms
Jeff Brownace13b12011-03-09 17:39:48 -080074
Jeff Brown79ac9692011-04-19 21:20:10 -070075// Tap drag gesture delay time.
76// The time between up and the next up must be greater than this to be considered a
77// drag. Otherwise, the previous tap is finished and a new tap begins.
78static const nsecs_t TAP_DRAG_INTERVAL = 150 * 1000000; // 150 ms
79
Jeff Brownace13b12011-03-09 17:39:48 -080080// The distance in pixels that the pointer is allowed to move from initial down
81// to up and still be called a tap.
Jeff Brown79ac9692011-04-19 21:20:10 -070082static const float TAP_SLOP = 10.0f; // 10 pixels
Jeff Brownace13b12011-03-09 17:39:48 -080083
Jeff Brown2352b972011-04-12 22:39:53 -070084// Time after the first touch points go down to settle on an initial centroid.
85// This is intended to be enough time to handle cases where the user puts down two
86// fingers at almost but not quite exactly the same time.
87static const nsecs_t MULTITOUCH_SETTLE_INTERVAL = 100 * 1000000; // 100ms
Jeff Brownace13b12011-03-09 17:39:48 -080088
Jeff Brown2352b972011-04-12 22:39:53 -070089// The transition from PRESS to SWIPE or FREEFORM gesture mode is made when
90// both of the pointers are moving at least this fast.
91static const float MULTITOUCH_MIN_SPEED = 150.0f; // pixels per second
92
93// The transition from PRESS to SWIPE gesture mode can only occur when the
Jeff Brownace13b12011-03-09 17:39:48 -080094// cosine of the angle between the two vectors is greater than or equal to than this value
95// which indicates that the vectors are oriented in the same direction.
96// When the vectors are oriented in the exactly same direction, the cosine is 1.0.
97// (In exactly opposite directions, the cosine is -1.0.)
98static const float SWIPE_TRANSITION_ANGLE_COSINE = 0.5f; // cosine of 45 degrees
99
Jeff Brown2352b972011-04-12 22:39:53 -0700100// The transition from PRESS to SWIPE gesture mode can only occur when the
101// fingers are no more than this far apart relative to the diagonal size of
102// the touch pad. For example, a ratio of 0.5 means that the fingers must be
103// no more than half the diagonal size of the touch pad apart.
104static const float SWIPE_MAX_WIDTH_RATIO = 0.333f; // 1/3
105
106// The gesture movement speed factor relative to the size of the display.
107// Movement speed applies when the fingers are moving in the same direction.
108// Without acceleration, a full swipe of the touch pad diagonal in movement mode
109// will cover this portion of the display diagonal.
110static const float GESTURE_MOVEMENT_SPEED_RATIO = 0.8f;
111
112// The gesture zoom speed factor relative to the size of the display.
113// Zoom speed applies when the fingers are mostly moving relative to each other
114// to execute a scale gesture or similar.
115// Without acceleration, a full swipe of the touch pad diagonal in zoom mode
116// will cover this portion of the display diagonal.
117static const float GESTURE_ZOOM_SPEED_RATIO = 0.3f;
118
Jeff Brownace13b12011-03-09 17:39:48 -0800119
Jeff Brown46b9ac02010-04-22 18:58:52 -0700120// --- Static Functions ---
121
122template<typename T>
123inline static T abs(const T& value) {
124 return value < 0 ? - value : value;
125}
126
127template<typename T>
128inline static T min(const T& a, const T& b) {
129 return a < b ? a : b;
130}
131
Jeff Brown5c225b12010-06-16 01:53:36 -0700132template<typename T>
133inline static void swap(T& a, T& b) {
134 T temp = a;
135 a = b;
136 b = temp;
137}
138
Jeff Brown8d608662010-08-30 03:02:23 -0700139inline static float avg(float x, float y) {
140 return (x + y) / 2;
141}
142
Jeff Brown2352b972011-04-12 22:39:53 -0700143inline static float distance(float x1, float y1, float x2, float y2) {
144 return hypotf(x1 - x2, y1 - y2);
Jeff Brownace13b12011-03-09 17:39:48 -0800145}
146
Jeff Brown517bb4c2011-01-14 19:09:23 -0800147inline static int32_t signExtendNybble(int32_t value) {
148 return value >= 8 ? value - 16 : value;
149}
150
Jeff Brownef3d7e82010-09-30 14:33:04 -0700151static inline const char* toString(bool value) {
152 return value ? "true" : "false";
153}
154
Jeff Brown9626b142011-03-03 02:09:54 -0800155static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
156 const int32_t map[][4], size_t mapSize) {
157 if (orientation != DISPLAY_ORIENTATION_0) {
158 for (size_t i = 0; i < mapSize; i++) {
159 if (value == map[i][0]) {
160 return map[i][orientation];
161 }
162 }
163 }
164 return value;
165}
166
Jeff Brown46b9ac02010-04-22 18:58:52 -0700167static const int32_t keyCodeRotationMap[][4] = {
168 // key codes enumerated counter-clockwise with the original (unrotated) key first
169 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
Jeff Brownfd035822010-06-30 16:10:35 -0700170 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
171 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
172 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
173 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jeff Brown46b9ac02010-04-22 18:58:52 -0700174};
Jeff Brown9626b142011-03-03 02:09:54 -0800175static const size_t keyCodeRotationMapSize =
Jeff Brown46b9ac02010-04-22 18:58:52 -0700176 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
177
178int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Jeff Brown9626b142011-03-03 02:09:54 -0800179 return rotateValueUsingRotationMap(keyCode, orientation,
180 keyCodeRotationMap, keyCodeRotationMapSize);
181}
182
183static const int32_t edgeFlagRotationMap[][4] = {
184 // edge flags enumerated counter-clockwise with the original (unrotated) edge flag first
185 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
186 { AMOTION_EVENT_EDGE_FLAG_BOTTOM, AMOTION_EVENT_EDGE_FLAG_RIGHT,
187 AMOTION_EVENT_EDGE_FLAG_TOP, AMOTION_EVENT_EDGE_FLAG_LEFT },
188 { AMOTION_EVENT_EDGE_FLAG_RIGHT, AMOTION_EVENT_EDGE_FLAG_TOP,
189 AMOTION_EVENT_EDGE_FLAG_LEFT, AMOTION_EVENT_EDGE_FLAG_BOTTOM },
190 { AMOTION_EVENT_EDGE_FLAG_TOP, AMOTION_EVENT_EDGE_FLAG_LEFT,
191 AMOTION_EVENT_EDGE_FLAG_BOTTOM, AMOTION_EVENT_EDGE_FLAG_RIGHT },
192 { AMOTION_EVENT_EDGE_FLAG_LEFT, AMOTION_EVENT_EDGE_FLAG_BOTTOM,
193 AMOTION_EVENT_EDGE_FLAG_RIGHT, AMOTION_EVENT_EDGE_FLAG_TOP },
194};
195static const size_t edgeFlagRotationMapSize =
196 sizeof(edgeFlagRotationMap) / sizeof(edgeFlagRotationMap[0]);
197
198static int32_t rotateEdgeFlag(int32_t edgeFlag, int32_t orientation) {
199 return rotateValueUsingRotationMap(edgeFlag, orientation,
200 edgeFlagRotationMap, edgeFlagRotationMapSize);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700201}
202
Jeff Brown6d0fec22010-07-23 21:28:06 -0700203static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
204 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
205}
206
Jeff Brownefd32662011-03-08 15:13:06 -0800207static uint32_t getButtonStateForScanCode(int32_t scanCode) {
208 // Currently all buttons are mapped to the primary button.
209 switch (scanCode) {
210 case BTN_LEFT:
211 case BTN_RIGHT:
212 case BTN_MIDDLE:
213 case BTN_SIDE:
214 case BTN_EXTRA:
215 case BTN_FORWARD:
216 case BTN_BACK:
217 case BTN_TASK:
218 return BUTTON_STATE_PRIMARY;
219 default:
220 return 0;
221 }
222}
223
224// Returns true if the pointer should be reported as being down given the specified
225// button states.
226static bool isPointerDown(uint32_t buttonState) {
227 return buttonState & BUTTON_STATE_PRIMARY;
228}
229
230static int32_t calculateEdgeFlagsUsingPointerBounds(
231 const sp<PointerControllerInterface>& pointerController, float x, float y) {
232 int32_t edgeFlags = 0;
233 float minX, minY, maxX, maxY;
234 if (pointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
235 if (x <= minX) {
236 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_LEFT;
237 } else if (x >= maxX) {
238 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_RIGHT;
239 }
240 if (y <= minY) {
241 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_TOP;
242 } else if (y >= maxY) {
243 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_BOTTOM;
244 }
245 }
246 return edgeFlags;
247}
248
Jeff Brown2352b972011-04-12 22:39:53 -0700249static void clampPositionUsingPointerBounds(
250 const sp<PointerControllerInterface>& pointerController, float* x, float* y) {
251 float minX, minY, maxX, maxY;
252 if (pointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
253 if (*x < minX) {
254 *x = minX;
255 } else if (*x > maxX) {
256 *x = maxX;
257 }
258 if (*y < minY) {
259 *y = minY;
260 } else if (*y > maxY) {
261 *y = maxY;
262 }
263 }
264}
265
266static float calculateCommonVector(float a, float b) {
267 if (a > 0 && b > 0) {
268 return a < b ? a : b;
269 } else if (a < 0 && b < 0) {
270 return a > b ? a : b;
271 } else {
272 return 0;
273 }
274}
275
Jeff Brown46b9ac02010-04-22 18:58:52 -0700276
Jeff Brown46b9ac02010-04-22 18:58:52 -0700277// --- InputReader ---
278
279InputReader::InputReader(const sp<EventHubInterface>& eventHub,
Jeff Brown9c3cda02010-06-15 01:31:58 -0700280 const sp<InputReaderPolicyInterface>& policy,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700281 const sp<InputDispatcherInterface>& dispatcher) :
Jeff Brown6d0fec22010-07-23 21:28:06 -0700282 mEventHub(eventHub), mPolicy(policy), mDispatcher(dispatcher),
Jeff Brownaa3855d2011-03-17 01:34:19 -0700283 mGlobalMetaState(0), mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX) {
Jeff Brown9c3cda02010-06-15 01:31:58 -0700284 configureExcludedDevices();
Jeff Brown6d0fec22010-07-23 21:28:06 -0700285 updateGlobalMetaState();
286 updateInputConfiguration();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700287}
288
289InputReader::~InputReader() {
290 for (size_t i = 0; i < mDevices.size(); i++) {
291 delete mDevices.valueAt(i);
292 }
293}
294
295void InputReader::loopOnce() {
Jeff Brownaa3855d2011-03-17 01:34:19 -0700296 int32_t timeoutMillis = -1;
297 if (mNextTimeout != LLONG_MAX) {
298 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
299 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
300 }
301
Jeff Brownb7198742011-03-18 18:14:26 -0700302 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
303 if (count) {
304 processEvents(mEventBuffer, count);
305 }
306 if (!count || timeoutMillis == 0) {
Jeff Brownaa3855d2011-03-17 01:34:19 -0700307 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
308#if DEBUG_RAW_EVENTS
309 LOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
310#endif
311 mNextTimeout = LLONG_MAX;
312 timeoutExpired(now);
313 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700314}
315
Jeff Brownb7198742011-03-18 18:14:26 -0700316void InputReader::processEvents(const RawEvent* rawEvents, size_t count) {
317 for (const RawEvent* rawEvent = rawEvents; count;) {
318 int32_t type = rawEvent->type;
319 size_t batchSize = 1;
320 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
321 int32_t deviceId = rawEvent->deviceId;
322 while (batchSize < count) {
323 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
324 || rawEvent[batchSize].deviceId != deviceId) {
325 break;
326 }
327 batchSize += 1;
328 }
329#if DEBUG_RAW_EVENTS
330 LOGD("BatchSize: %d Count: %d", batchSize, count);
331#endif
332 processEventsForDevice(deviceId, rawEvent, batchSize);
333 } else {
334 switch (rawEvent->type) {
335 case EventHubInterface::DEVICE_ADDED:
336 addDevice(rawEvent->deviceId);
337 break;
338 case EventHubInterface::DEVICE_REMOVED:
339 removeDevice(rawEvent->deviceId);
340 break;
341 case EventHubInterface::FINISHED_DEVICE_SCAN:
342 handleConfigurationChanged(rawEvent->when);
343 break;
344 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700345 LOG_ASSERT(false); // can't happen
Jeff Brownb7198742011-03-18 18:14:26 -0700346 break;
347 }
348 }
349 count -= batchSize;
350 rawEvent += batchSize;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700351 }
352}
353
Jeff Brown7342bb92010-10-01 18:55:43 -0700354void InputReader::addDevice(int32_t deviceId) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700355 String8 name = mEventHub->getDeviceName(deviceId);
356 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
357
358 InputDevice* device = createDevice(deviceId, name, classes);
359 device->configure();
360
Jeff Brown8d608662010-08-30 03:02:23 -0700361 if (device->isIgnored()) {
Jeff Brown90655042010-12-02 13:50:46 -0800362 LOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, name.string());
Jeff Brown8d608662010-08-30 03:02:23 -0700363 } else {
Jeff Brown90655042010-12-02 13:50:46 -0800364 LOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, name.string(),
Jeff Brownef3d7e82010-09-30 14:33:04 -0700365 device->getSources());
Jeff Brown8d608662010-08-30 03:02:23 -0700366 }
367
Jeff Brown6d0fec22010-07-23 21:28:06 -0700368 bool added = false;
369 { // acquire device registry writer lock
370 RWLock::AutoWLock _wl(mDeviceRegistryLock);
371
372 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
373 if (deviceIndex < 0) {
374 mDevices.add(deviceId, device);
375 added = true;
376 }
377 } // release device registry writer lock
378
379 if (! added) {
380 LOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
381 delete device;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700382 return;
383 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700384}
385
Jeff Brown7342bb92010-10-01 18:55:43 -0700386void InputReader::removeDevice(int32_t deviceId) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700387 bool removed = false;
388 InputDevice* device = NULL;
389 { // acquire device registry writer lock
390 RWLock::AutoWLock _wl(mDeviceRegistryLock);
391
392 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
393 if (deviceIndex >= 0) {
394 device = mDevices.valueAt(deviceIndex);
395 mDevices.removeItemsAt(deviceIndex, 1);
396 removed = true;
397 }
398 } // release device registry writer lock
399
400 if (! removed) {
401 LOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700402 return;
403 }
404
Jeff Brown6d0fec22010-07-23 21:28:06 -0700405 if (device->isIgnored()) {
Jeff Brown90655042010-12-02 13:50:46 -0800406 LOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Jeff Brown6d0fec22010-07-23 21:28:06 -0700407 device->getId(), device->getName().string());
408 } else {
Jeff Brown90655042010-12-02 13:50:46 -0800409 LOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Jeff Brown6d0fec22010-07-23 21:28:06 -0700410 device->getId(), device->getName().string(), device->getSources());
411 }
412
Jeff Brown8d608662010-08-30 03:02:23 -0700413 device->reset();
414
Jeff Brown6d0fec22010-07-23 21:28:06 -0700415 delete device;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700416}
417
Jeff Brown6d0fec22010-07-23 21:28:06 -0700418InputDevice* InputReader::createDevice(int32_t deviceId, const String8& name, uint32_t classes) {
419 InputDevice* device = new InputDevice(this, deviceId, name);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700420
Jeff Brown56194eb2011-03-02 19:23:13 -0800421 // External devices.
422 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
423 device->setExternal(true);
424 }
425
Jeff Brown6d0fec22010-07-23 21:28:06 -0700426 // Switch-like devices.
427 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
428 device->addMapper(new SwitchInputMapper(device));
429 }
430
431 // Keyboard-like devices.
Jeff Brownefd32662011-03-08 15:13:06 -0800432 uint32_t keyboardSource = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700433 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
434 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800435 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700436 }
437 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
438 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
439 }
440 if (classes & INPUT_DEVICE_CLASS_DPAD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800441 keyboardSource |= AINPUT_SOURCE_DPAD;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700442 }
Jeff Browncb1404e2011-01-15 18:14:15 -0800443 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800444 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
Jeff Browncb1404e2011-01-15 18:14:15 -0800445 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700446
Jeff Brownefd32662011-03-08 15:13:06 -0800447 if (keyboardSource != 0) {
448 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700449 }
450
Jeff Brown83c09682010-12-23 17:50:18 -0800451 // Cursor-like devices.
452 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
453 device->addMapper(new CursorInputMapper(device));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700454 }
455
Jeff Brown58a2da82011-01-25 16:02:22 -0800456 // Touchscreens and touchpad devices.
457 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800458 device->addMapper(new MultiTouchInputMapper(device));
Jeff Brown58a2da82011-01-25 16:02:22 -0800459 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800460 device->addMapper(new SingleTouchInputMapper(device));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700461 }
462
Jeff Browncb1404e2011-01-15 18:14:15 -0800463 // Joystick-like devices.
464 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
465 device->addMapper(new JoystickInputMapper(device));
466 }
467
Jeff Brown6d0fec22010-07-23 21:28:06 -0700468 return device;
469}
470
Jeff Brownb7198742011-03-18 18:14:26 -0700471void InputReader::processEventsForDevice(int32_t deviceId,
472 const RawEvent* rawEvents, size_t count) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700473 { // acquire device registry reader lock
474 RWLock::AutoRLock _rl(mDeviceRegistryLock);
475
476 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
477 if (deviceIndex < 0) {
478 LOGW("Discarding event for unknown deviceId %d.", deviceId);
479 return;
480 }
481
482 InputDevice* device = mDevices.valueAt(deviceIndex);
483 if (device->isIgnored()) {
484 //LOGD("Discarding event for ignored deviceId %d.", deviceId);
485 return;
486 }
487
Jeff Brownb7198742011-03-18 18:14:26 -0700488 device->process(rawEvents, count);
Jeff Brown6d0fec22010-07-23 21:28:06 -0700489 } // release device registry reader lock
490}
491
Jeff Brownaa3855d2011-03-17 01:34:19 -0700492void InputReader::timeoutExpired(nsecs_t when) {
493 { // acquire device registry reader lock
494 RWLock::AutoRLock _rl(mDeviceRegistryLock);
495
496 for (size_t i = 0; i < mDevices.size(); i++) {
497 InputDevice* device = mDevices.valueAt(i);
498 if (!device->isIgnored()) {
499 device->timeoutExpired(when);
500 }
501 }
502 } // release device registry reader lock
503}
504
Jeff Brownc3db8582010-10-20 15:33:38 -0700505void InputReader::handleConfigurationChanged(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700506 // Reset global meta state because it depends on the list of all configured devices.
507 updateGlobalMetaState();
508
509 // Update input configuration.
510 updateInputConfiguration();
511
512 // Enqueue configuration changed.
513 mDispatcher->notifyConfigurationChanged(when);
514}
515
516void InputReader::configureExcludedDevices() {
517 Vector<String8> excludedDeviceNames;
518 mPolicy->getExcludedDeviceNames(excludedDeviceNames);
519
520 for (size_t i = 0; i < excludedDeviceNames.size(); i++) {
521 mEventHub->addExcludedDevice(excludedDeviceNames[i]);
522 }
523}
524
525void InputReader::updateGlobalMetaState() {
526 { // acquire state lock
527 AutoMutex _l(mStateLock);
528
529 mGlobalMetaState = 0;
530
531 { // acquire device registry reader lock
532 RWLock::AutoRLock _rl(mDeviceRegistryLock);
533
534 for (size_t i = 0; i < mDevices.size(); i++) {
535 InputDevice* device = mDevices.valueAt(i);
536 mGlobalMetaState |= device->getMetaState();
537 }
538 } // release device registry reader lock
539 } // release state lock
540}
541
542int32_t InputReader::getGlobalMetaState() {
543 { // acquire state lock
544 AutoMutex _l(mStateLock);
545
546 return mGlobalMetaState;
547 } // release state lock
548}
549
550void InputReader::updateInputConfiguration() {
551 { // acquire state lock
552 AutoMutex _l(mStateLock);
553
554 int32_t touchScreenConfig = InputConfiguration::TOUCHSCREEN_NOTOUCH;
555 int32_t keyboardConfig = InputConfiguration::KEYBOARD_NOKEYS;
556 int32_t navigationConfig = InputConfiguration::NAVIGATION_NONAV;
557 { // acquire device registry reader lock
558 RWLock::AutoRLock _rl(mDeviceRegistryLock);
559
560 InputDeviceInfo deviceInfo;
561 for (size_t i = 0; i < mDevices.size(); i++) {
562 InputDevice* device = mDevices.valueAt(i);
563 device->getDeviceInfo(& deviceInfo);
564 uint32_t sources = deviceInfo.getSources();
565
566 if ((sources & AINPUT_SOURCE_TOUCHSCREEN) == AINPUT_SOURCE_TOUCHSCREEN) {
567 touchScreenConfig = InputConfiguration::TOUCHSCREEN_FINGER;
568 }
569 if ((sources & AINPUT_SOURCE_TRACKBALL) == AINPUT_SOURCE_TRACKBALL) {
570 navigationConfig = InputConfiguration::NAVIGATION_TRACKBALL;
571 } else if ((sources & AINPUT_SOURCE_DPAD) == AINPUT_SOURCE_DPAD) {
572 navigationConfig = InputConfiguration::NAVIGATION_DPAD;
573 }
574 if (deviceInfo.getKeyboardType() == AINPUT_KEYBOARD_TYPE_ALPHABETIC) {
575 keyboardConfig = InputConfiguration::KEYBOARD_QWERTY;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700576 }
577 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700578 } // release device registry reader lock
Jeff Brown46b9ac02010-04-22 18:58:52 -0700579
Jeff Brown6d0fec22010-07-23 21:28:06 -0700580 mInputConfiguration.touchScreen = touchScreenConfig;
581 mInputConfiguration.keyboard = keyboardConfig;
582 mInputConfiguration.navigation = navigationConfig;
583 } // release state lock
584}
585
Jeff Brownfe508922011-01-18 15:10:10 -0800586void InputReader::disableVirtualKeysUntil(nsecs_t time) {
587 mDisableVirtualKeysTimeout = time;
588}
589
590bool InputReader::shouldDropVirtualKey(nsecs_t now,
591 InputDevice* device, int32_t keyCode, int32_t scanCode) {
592 if (now < mDisableVirtualKeysTimeout) {
593 LOGI("Dropping virtual key from device %s because virtual keys are "
594 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
595 device->getName().string(),
596 (mDisableVirtualKeysTimeout - now) * 0.000001,
597 keyCode, scanCode);
598 return true;
599 } else {
600 return false;
601 }
602}
603
Jeff Brown05dc66a2011-03-02 14:41:58 -0800604void InputReader::fadePointer() {
605 { // acquire device registry reader lock
606 RWLock::AutoRLock _rl(mDeviceRegistryLock);
607
608 for (size_t i = 0; i < mDevices.size(); i++) {
609 InputDevice* device = mDevices.valueAt(i);
610 device->fadePointer();
611 }
612 } // release device registry reader lock
613}
614
Jeff Brownaa3855d2011-03-17 01:34:19 -0700615void InputReader::requestTimeoutAtTime(nsecs_t when) {
616 if (when < mNextTimeout) {
617 mNextTimeout = when;
618 }
619}
620
Jeff Brown6d0fec22010-07-23 21:28:06 -0700621void InputReader::getInputConfiguration(InputConfiguration* outConfiguration) {
622 { // acquire state lock
623 AutoMutex _l(mStateLock);
624
625 *outConfiguration = mInputConfiguration;
626 } // release state lock
627}
628
629status_t InputReader::getInputDeviceInfo(int32_t deviceId, InputDeviceInfo* outDeviceInfo) {
630 { // acquire device registry reader lock
631 RWLock::AutoRLock _rl(mDeviceRegistryLock);
632
633 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
634 if (deviceIndex < 0) {
635 return NAME_NOT_FOUND;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700636 }
637
Jeff Brown6d0fec22010-07-23 21:28:06 -0700638 InputDevice* device = mDevices.valueAt(deviceIndex);
639 if (device->isIgnored()) {
640 return NAME_NOT_FOUND;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700641 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700642
643 device->getDeviceInfo(outDeviceInfo);
644 return OK;
645 } // release device registy reader lock
646}
647
648void InputReader::getInputDeviceIds(Vector<int32_t>& outDeviceIds) {
649 outDeviceIds.clear();
650
651 { // acquire device registry reader lock
652 RWLock::AutoRLock _rl(mDeviceRegistryLock);
653
654 size_t numDevices = mDevices.size();
655 for (size_t i = 0; i < numDevices; i++) {
656 InputDevice* device = mDevices.valueAt(i);
657 if (! device->isIgnored()) {
658 outDeviceIds.add(device->getId());
659 }
660 }
661 } // release device registy reader lock
662}
663
664int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
665 int32_t keyCode) {
666 return getState(deviceId, sourceMask, keyCode, & InputDevice::getKeyCodeState);
667}
668
669int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
670 int32_t scanCode) {
671 return getState(deviceId, sourceMask, scanCode, & InputDevice::getScanCodeState);
672}
673
674int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
675 return getState(deviceId, sourceMask, switchCode, & InputDevice::getSwitchState);
676}
677
678int32_t InputReader::getState(int32_t deviceId, uint32_t sourceMask, int32_t code,
679 GetStateFunc getStateFunc) {
680 { // acquire device registry reader lock
681 RWLock::AutoRLock _rl(mDeviceRegistryLock);
682
683 int32_t result = AKEY_STATE_UNKNOWN;
684 if (deviceId >= 0) {
685 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
686 if (deviceIndex >= 0) {
687 InputDevice* device = mDevices.valueAt(deviceIndex);
688 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
689 result = (device->*getStateFunc)(sourceMask, code);
690 }
691 }
692 } else {
693 size_t numDevices = mDevices.size();
694 for (size_t i = 0; i < numDevices; i++) {
695 InputDevice* device = mDevices.valueAt(i);
696 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
697 result = (device->*getStateFunc)(sourceMask, code);
698 if (result >= AKEY_STATE_DOWN) {
699 return result;
700 }
701 }
702 }
703 }
704 return result;
705 } // release device registy reader lock
706}
707
708bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
709 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
710 memset(outFlags, 0, numCodes);
711 return markSupportedKeyCodes(deviceId, sourceMask, numCodes, keyCodes, outFlags);
712}
713
714bool InputReader::markSupportedKeyCodes(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
715 const int32_t* keyCodes, uint8_t* outFlags) {
716 { // acquire device registry reader lock
717 RWLock::AutoRLock _rl(mDeviceRegistryLock);
718 bool result = false;
719 if (deviceId >= 0) {
720 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
721 if (deviceIndex >= 0) {
722 InputDevice* device = mDevices.valueAt(deviceIndex);
723 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
724 result = device->markSupportedKeyCodes(sourceMask,
725 numCodes, keyCodes, outFlags);
726 }
727 }
728 } else {
729 size_t numDevices = mDevices.size();
730 for (size_t i = 0; i < numDevices; i++) {
731 InputDevice* device = mDevices.valueAt(i);
732 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
733 result |= device->markSupportedKeyCodes(sourceMask,
734 numCodes, keyCodes, outFlags);
735 }
736 }
737 }
738 return result;
739 } // release device registy reader lock
740}
741
Jeff Brownb88102f2010-09-08 11:49:43 -0700742void InputReader::dump(String8& dump) {
Jeff Brownf2f48712010-10-01 17:46:21 -0700743 mEventHub->dump(dump);
744 dump.append("\n");
745
746 dump.append("Input Reader State:\n");
747
Jeff Brownef3d7e82010-09-30 14:33:04 -0700748 { // acquire device registry reader lock
749 RWLock::AutoRLock _rl(mDeviceRegistryLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700750
Jeff Brownef3d7e82010-09-30 14:33:04 -0700751 for (size_t i = 0; i < mDevices.size(); i++) {
752 mDevices.valueAt(i)->dump(dump);
Jeff Brownb88102f2010-09-08 11:49:43 -0700753 }
Jeff Brownef3d7e82010-09-30 14:33:04 -0700754 } // release device registy reader lock
Jeff Brownb88102f2010-09-08 11:49:43 -0700755}
756
Jeff Brown6d0fec22010-07-23 21:28:06 -0700757
758// --- InputReaderThread ---
759
760InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
761 Thread(/*canCallJava*/ true), mReader(reader) {
762}
763
764InputReaderThread::~InputReaderThread() {
765}
766
767bool InputReaderThread::threadLoop() {
768 mReader->loopOnce();
769 return true;
770}
771
772
773// --- InputDevice ---
774
775InputDevice::InputDevice(InputReaderContext* context, int32_t id, const String8& name) :
Jeff Brown56194eb2011-03-02 19:23:13 -0800776 mContext(context), mId(id), mName(name), mSources(0), mIsExternal(false) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700777}
778
779InputDevice::~InputDevice() {
780 size_t numMappers = mMappers.size();
781 for (size_t i = 0; i < numMappers; i++) {
782 delete mMappers[i];
783 }
784 mMappers.clear();
785}
786
Jeff Brownef3d7e82010-09-30 14:33:04 -0700787void InputDevice::dump(String8& dump) {
788 InputDeviceInfo deviceInfo;
789 getDeviceInfo(& deviceInfo);
790
Jeff Brown90655042010-12-02 13:50:46 -0800791 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
Jeff Brownef3d7e82010-09-30 14:33:04 -0700792 deviceInfo.getName().string());
Jeff Brown56194eb2011-03-02 19:23:13 -0800793 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Jeff Brownef3d7e82010-09-30 14:33:04 -0700794 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
795 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Jeff Browncc0c1592011-02-19 05:07:28 -0800796
Jeff Brownefd32662011-03-08 15:13:06 -0800797 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
Jeff Browncc0c1592011-02-19 05:07:28 -0800798 if (!ranges.isEmpty()) {
Jeff Brownef3d7e82010-09-30 14:33:04 -0700799 dump.append(INDENT2 "Motion Ranges:\n");
Jeff Browncc0c1592011-02-19 05:07:28 -0800800 for (size_t i = 0; i < ranges.size(); i++) {
Jeff Brownefd32662011-03-08 15:13:06 -0800801 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
802 const char* label = getAxisLabel(range.axis);
Jeff Browncc0c1592011-02-19 05:07:28 -0800803 char name[32];
804 if (label) {
805 strncpy(name, label, sizeof(name));
806 name[sizeof(name) - 1] = '\0';
807 } else {
Jeff Brownefd32662011-03-08 15:13:06 -0800808 snprintf(name, sizeof(name), "%d", range.axis);
Jeff Browncc0c1592011-02-19 05:07:28 -0800809 }
Jeff Brownefd32662011-03-08 15:13:06 -0800810 dump.appendFormat(INDENT3 "%s: source=0x%08x, "
811 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f\n",
812 name, range.source, range.min, range.max, range.flat, range.fuzz);
Jeff Browncc0c1592011-02-19 05:07:28 -0800813 }
Jeff Brownef3d7e82010-09-30 14:33:04 -0700814 }
815
816 size_t numMappers = mMappers.size();
817 for (size_t i = 0; i < numMappers; i++) {
818 InputMapper* mapper = mMappers[i];
819 mapper->dump(dump);
820 }
821}
822
Jeff Brown6d0fec22010-07-23 21:28:06 -0700823void InputDevice::addMapper(InputMapper* mapper) {
824 mMappers.add(mapper);
825}
826
827void InputDevice::configure() {
Jeff Brown8d608662010-08-30 03:02:23 -0700828 if (! isIgnored()) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800829 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
Jeff Brown8d608662010-08-30 03:02:23 -0700830 }
831
Jeff Brown6d0fec22010-07-23 21:28:06 -0700832 mSources = 0;
833
834 size_t numMappers = mMappers.size();
835 for (size_t i = 0; i < numMappers; i++) {
836 InputMapper* mapper = mMappers[i];
837 mapper->configure();
838 mSources |= mapper->getSources();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700839 }
840}
841
Jeff Brown6d0fec22010-07-23 21:28:06 -0700842void InputDevice::reset() {
843 size_t numMappers = mMappers.size();
844 for (size_t i = 0; i < numMappers; i++) {
845 InputMapper* mapper = mMappers[i];
846 mapper->reset();
847 }
848}
Jeff Brown46b9ac02010-04-22 18:58:52 -0700849
Jeff Brownb7198742011-03-18 18:14:26 -0700850void InputDevice::process(const RawEvent* rawEvents, size_t count) {
851 // Process all of the events in order for each mapper.
852 // We cannot simply ask each mapper to process them in bulk because mappers may
853 // have side-effects that must be interleaved. For example, joystick movement events and
854 // gamepad button presses are handled by different mappers but they should be dispatched
855 // in the order received.
Jeff Brown6d0fec22010-07-23 21:28:06 -0700856 size_t numMappers = mMappers.size();
Jeff Brownb7198742011-03-18 18:14:26 -0700857 for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
858#if DEBUG_RAW_EVENTS
859 LOGD("Input event: device=%d type=0x%04x scancode=0x%04x "
860 "keycode=0x%04x value=0x%04x flags=0x%08x",
861 rawEvent->deviceId, rawEvent->type, rawEvent->scanCode, rawEvent->keyCode,
862 rawEvent->value, rawEvent->flags);
863#endif
864
865 for (size_t i = 0; i < numMappers; i++) {
866 InputMapper* mapper = mMappers[i];
867 mapper->process(rawEvent);
868 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700869 }
870}
Jeff Brown46b9ac02010-04-22 18:58:52 -0700871
Jeff Brownaa3855d2011-03-17 01:34:19 -0700872void InputDevice::timeoutExpired(nsecs_t when) {
873 size_t numMappers = mMappers.size();
874 for (size_t i = 0; i < numMappers; i++) {
875 InputMapper* mapper = mMappers[i];
876 mapper->timeoutExpired(when);
877 }
878}
879
Jeff Brown6d0fec22010-07-23 21:28:06 -0700880void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
881 outDeviceInfo->initialize(mId, mName);
882
883 size_t numMappers = mMappers.size();
884 for (size_t i = 0; i < numMappers; i++) {
885 InputMapper* mapper = mMappers[i];
886 mapper->populateDeviceInfo(outDeviceInfo);
887 }
888}
889
890int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
891 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
892}
893
894int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
895 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
896}
897
898int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
899 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
900}
901
902int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
903 int32_t result = AKEY_STATE_UNKNOWN;
904 size_t numMappers = mMappers.size();
905 for (size_t i = 0; i < numMappers; i++) {
906 InputMapper* mapper = mMappers[i];
907 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
908 result = (mapper->*getStateFunc)(sourceMask, code);
909 if (result >= AKEY_STATE_DOWN) {
910 return result;
911 }
912 }
913 }
914 return result;
915}
916
917bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
918 const int32_t* keyCodes, uint8_t* outFlags) {
919 bool result = false;
920 size_t numMappers = mMappers.size();
921 for (size_t i = 0; i < numMappers; i++) {
922 InputMapper* mapper = mMappers[i];
923 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
924 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
925 }
926 }
927 return result;
928}
929
930int32_t InputDevice::getMetaState() {
931 int32_t result = 0;
932 size_t numMappers = mMappers.size();
933 for (size_t i = 0; i < numMappers; i++) {
934 InputMapper* mapper = mMappers[i];
935 result |= mapper->getMetaState();
936 }
937 return result;
938}
939
Jeff Brown05dc66a2011-03-02 14:41:58 -0800940void InputDevice::fadePointer() {
941 size_t numMappers = mMappers.size();
942 for (size_t i = 0; i < numMappers; i++) {
943 InputMapper* mapper = mMappers[i];
944 mapper->fadePointer();
945 }
946}
947
Jeff Brown6d0fec22010-07-23 21:28:06 -0700948
949// --- InputMapper ---
950
951InputMapper::InputMapper(InputDevice* device) :
952 mDevice(device), mContext(device->getContext()) {
953}
954
955InputMapper::~InputMapper() {
956}
957
958void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
959 info->addSource(getSources());
960}
961
Jeff Brownef3d7e82010-09-30 14:33:04 -0700962void InputMapper::dump(String8& dump) {
963}
964
Jeff Brown6d0fec22010-07-23 21:28:06 -0700965void InputMapper::configure() {
966}
967
968void InputMapper::reset() {
969}
970
Jeff Brownaa3855d2011-03-17 01:34:19 -0700971void InputMapper::timeoutExpired(nsecs_t when) {
972}
973
Jeff Brown6d0fec22010-07-23 21:28:06 -0700974int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
975 return AKEY_STATE_UNKNOWN;
976}
977
978int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
979 return AKEY_STATE_UNKNOWN;
980}
981
982int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
983 return AKEY_STATE_UNKNOWN;
984}
985
986bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
987 const int32_t* keyCodes, uint8_t* outFlags) {
988 return false;
989}
990
991int32_t InputMapper::getMetaState() {
992 return 0;
993}
994
Jeff Brown05dc66a2011-03-02 14:41:58 -0800995void InputMapper::fadePointer() {
996}
997
Jeff Browncb1404e2011-01-15 18:14:15 -0800998void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
999 const RawAbsoluteAxisInfo& axis, const char* name) {
1000 if (axis.valid) {
1001 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d\n",
1002 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz);
1003 } else {
1004 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
1005 }
1006}
1007
Jeff Brown6d0fec22010-07-23 21:28:06 -07001008
1009// --- SwitchInputMapper ---
1010
1011SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
1012 InputMapper(device) {
1013}
1014
1015SwitchInputMapper::~SwitchInputMapper() {
1016}
1017
1018uint32_t SwitchInputMapper::getSources() {
Jeff Brown89de57a2011-01-19 18:41:38 -08001019 return AINPUT_SOURCE_SWITCH;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001020}
1021
1022void SwitchInputMapper::process(const RawEvent* rawEvent) {
1023 switch (rawEvent->type) {
1024 case EV_SW:
1025 processSwitch(rawEvent->when, rawEvent->scanCode, rawEvent->value);
1026 break;
1027 }
1028}
1029
1030void SwitchInputMapper::processSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue) {
Jeff Brownb6997262010-10-08 22:31:17 -07001031 getDispatcher()->notifySwitch(when, switchCode, switchValue, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001032}
1033
1034int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1035 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
1036}
1037
1038
1039// --- KeyboardInputMapper ---
1040
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001041KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
Jeff Brownefd32662011-03-08 15:13:06 -08001042 uint32_t source, int32_t keyboardType) :
1043 InputMapper(device), mSource(source),
Jeff Brown6d0fec22010-07-23 21:28:06 -07001044 mKeyboardType(keyboardType) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001045 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001046}
1047
1048KeyboardInputMapper::~KeyboardInputMapper() {
1049}
1050
Jeff Brown6328cdc2010-07-29 18:18:33 -07001051void KeyboardInputMapper::initializeLocked() {
1052 mLocked.metaState = AMETA_NONE;
1053 mLocked.downTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001054}
1055
1056uint32_t KeyboardInputMapper::getSources() {
Jeff Brownefd32662011-03-08 15:13:06 -08001057 return mSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001058}
1059
1060void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1061 InputMapper::populateDeviceInfo(info);
1062
1063 info->setKeyboardType(mKeyboardType);
1064}
1065
Jeff Brownef3d7e82010-09-30 14:33:04 -07001066void KeyboardInputMapper::dump(String8& dump) {
1067 { // acquire lock
1068 AutoMutex _l(mLock);
1069 dump.append(INDENT2 "Keyboard Input Mapper:\n");
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001070 dumpParameters(dump);
Jeff Brownef3d7e82010-09-30 14:33:04 -07001071 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
1072 dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mLocked.keyDowns.size());
1073 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mLocked.metaState);
1074 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
1075 } // release lock
1076}
1077
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001078
1079void KeyboardInputMapper::configure() {
1080 InputMapper::configure();
1081
1082 // Configure basic parameters.
1083 configureParameters();
Jeff Brown49ed71d2010-12-06 17:13:33 -08001084
1085 // Reset LEDs.
1086 {
1087 AutoMutex _l(mLock);
1088 resetLedStateLocked();
1089 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001090}
1091
1092void KeyboardInputMapper::configureParameters() {
1093 mParameters.orientationAware = false;
1094 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
1095 mParameters.orientationAware);
1096
1097 mParameters.associatedDisplayId = mParameters.orientationAware ? 0 : -1;
1098}
1099
1100void KeyboardInputMapper::dumpParameters(String8& dump) {
1101 dump.append(INDENT3 "Parameters:\n");
1102 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1103 mParameters.associatedDisplayId);
1104 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1105 toString(mParameters.orientationAware));
1106}
1107
Jeff Brown6d0fec22010-07-23 21:28:06 -07001108void KeyboardInputMapper::reset() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001109 for (;;) {
1110 int32_t keyCode, scanCode;
1111 { // acquire lock
1112 AutoMutex _l(mLock);
1113
1114 // Synthesize key up event on reset if keys are currently down.
1115 if (mLocked.keyDowns.isEmpty()) {
1116 initializeLocked();
Jeff Brown49ed71d2010-12-06 17:13:33 -08001117 resetLedStateLocked();
Jeff Brown6328cdc2010-07-29 18:18:33 -07001118 break; // done
1119 }
1120
1121 const KeyDown& keyDown = mLocked.keyDowns.top();
1122 keyCode = keyDown.keyCode;
1123 scanCode = keyDown.scanCode;
1124 } // release lock
1125
Jeff Brown6d0fec22010-07-23 21:28:06 -07001126 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown6328cdc2010-07-29 18:18:33 -07001127 processKey(when, false, keyCode, scanCode, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001128 }
1129
1130 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001131 getContext()->updateGlobalMetaState();
1132}
1133
1134void KeyboardInputMapper::process(const RawEvent* rawEvent) {
1135 switch (rawEvent->type) {
1136 case EV_KEY: {
1137 int32_t scanCode = rawEvent->scanCode;
1138 if (isKeyboardOrGamepadKey(scanCode)) {
1139 processKey(rawEvent->when, rawEvent->value != 0, rawEvent->keyCode, scanCode,
1140 rawEvent->flags);
1141 }
1142 break;
1143 }
1144 }
1145}
1146
1147bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
1148 return scanCode < BTN_MOUSE
1149 || scanCode >= KEY_OK
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001150 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
Jeff Browncb1404e2011-01-15 18:14:15 -08001151 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001152}
1153
Jeff Brown6328cdc2010-07-29 18:18:33 -07001154void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode,
1155 int32_t scanCode, uint32_t policyFlags) {
1156 int32_t newMetaState;
1157 nsecs_t downTime;
1158 bool metaStateChanged = false;
1159
1160 { // acquire lock
1161 AutoMutex _l(mLock);
1162
1163 if (down) {
1164 // Rotate key codes according to orientation if needed.
1165 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001166 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001167 int32_t orientation;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001168 if (!getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1169 NULL, NULL, & orientation)) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001170 orientation = DISPLAY_ORIENTATION_0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001171 }
1172
1173 keyCode = rotateKeyCode(keyCode, orientation);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001174 }
1175
Jeff Brown6328cdc2010-07-29 18:18:33 -07001176 // Add key down.
1177 ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1178 if (keyDownIndex >= 0) {
1179 // key repeat, be sure to use same keycode as before in case of rotation
Jeff Brown6b53e8d2010-11-10 16:03:06 -08001180 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001181 } else {
1182 // key down
Jeff Brownfe508922011-01-18 15:10:10 -08001183 if ((policyFlags & POLICY_FLAG_VIRTUAL)
1184 && mContext->shouldDropVirtualKey(when,
1185 getDevice(), keyCode, scanCode)) {
1186 return;
1187 }
1188
Jeff Brown6328cdc2010-07-29 18:18:33 -07001189 mLocked.keyDowns.push();
1190 KeyDown& keyDown = mLocked.keyDowns.editTop();
1191 keyDown.keyCode = keyCode;
1192 keyDown.scanCode = scanCode;
1193 }
1194
1195 mLocked.downTime = when;
1196 } else {
1197 // Remove key down.
1198 ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1199 if (keyDownIndex >= 0) {
1200 // key up, be sure to use same keycode as before in case of rotation
Jeff Brown6b53e8d2010-11-10 16:03:06 -08001201 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001202 mLocked.keyDowns.removeAt(size_t(keyDownIndex));
1203 } else {
1204 // key was not actually down
1205 LOGI("Dropping key up from device %s because the key was not down. "
1206 "keyCode=%d, scanCode=%d",
1207 getDeviceName().string(), keyCode, scanCode);
1208 return;
1209 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001210 }
1211
Jeff Brown6328cdc2010-07-29 18:18:33 -07001212 int32_t oldMetaState = mLocked.metaState;
1213 newMetaState = updateMetaState(keyCode, down, oldMetaState);
1214 if (oldMetaState != newMetaState) {
1215 mLocked.metaState = newMetaState;
1216 metaStateChanged = true;
Jeff Brown497a92c2010-09-12 17:55:08 -07001217 updateLedStateLocked(false);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001218 }
Jeff Brownfd035822010-06-30 16:10:35 -07001219
Jeff Brown6328cdc2010-07-29 18:18:33 -07001220 downTime = mLocked.downTime;
1221 } // release lock
1222
Jeff Brown56194eb2011-03-02 19:23:13 -08001223 // Key down on external an keyboard should wake the device.
1224 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
1225 // For internal keyboards, the key layout file should specify the policy flags for
1226 // each wake key individually.
1227 // TODO: Use the input device configuration to control this behavior more finely.
1228 if (down && getDevice()->isExternal()
1229 && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) {
1230 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1231 }
1232
Jeff Brown6328cdc2010-07-29 18:18:33 -07001233 if (metaStateChanged) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001234 getContext()->updateGlobalMetaState();
Jeff Brown46b9ac02010-04-22 18:58:52 -07001235 }
1236
Jeff Brown05dc66a2011-03-02 14:41:58 -08001237 if (down && !isMetaKey(keyCode)) {
1238 getContext()->fadePointer();
1239 }
1240
Jeff Brownefd32662011-03-08 15:13:06 -08001241 getDispatcher()->notifyKey(when, getDeviceId(), mSource, policyFlags,
Jeff Brownb6997262010-10-08 22:31:17 -07001242 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
1243 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001244}
1245
Jeff Brown6328cdc2010-07-29 18:18:33 -07001246ssize_t KeyboardInputMapper::findKeyDownLocked(int32_t scanCode) {
1247 size_t n = mLocked.keyDowns.size();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001248 for (size_t i = 0; i < n; i++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001249 if (mLocked.keyDowns[i].scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001250 return i;
1251 }
1252 }
1253 return -1;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001254}
1255
Jeff Brown6d0fec22010-07-23 21:28:06 -07001256int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1257 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
1258}
Jeff Brown46b9ac02010-04-22 18:58:52 -07001259
Jeff Brown6d0fec22010-07-23 21:28:06 -07001260int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1261 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1262}
Jeff Brown46b9ac02010-04-22 18:58:52 -07001263
Jeff Brown6d0fec22010-07-23 21:28:06 -07001264bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1265 const int32_t* keyCodes, uint8_t* outFlags) {
1266 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
1267}
1268
1269int32_t KeyboardInputMapper::getMetaState() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001270 { // acquire lock
1271 AutoMutex _l(mLock);
1272 return mLocked.metaState;
1273 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001274}
1275
Jeff Brown49ed71d2010-12-06 17:13:33 -08001276void KeyboardInputMapper::resetLedStateLocked() {
1277 initializeLedStateLocked(mLocked.capsLockLedState, LED_CAPSL);
1278 initializeLedStateLocked(mLocked.numLockLedState, LED_NUML);
1279 initializeLedStateLocked(mLocked.scrollLockLedState, LED_SCROLLL);
1280
1281 updateLedStateLocked(true);
1282}
1283
1284void KeyboardInputMapper::initializeLedStateLocked(LockedState::LedState& ledState, int32_t led) {
1285 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
1286 ledState.on = false;
1287}
1288
Jeff Brown497a92c2010-09-12 17:55:08 -07001289void KeyboardInputMapper::updateLedStateLocked(bool reset) {
1290 updateLedStateForModifierLocked(mLocked.capsLockLedState, LED_CAPSL,
Jeff Brown51e7fe72010-10-29 22:19:53 -07001291 AMETA_CAPS_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001292 updateLedStateForModifierLocked(mLocked.numLockLedState, LED_NUML,
Jeff Brown51e7fe72010-10-29 22:19:53 -07001293 AMETA_NUM_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001294 updateLedStateForModifierLocked(mLocked.scrollLockLedState, LED_SCROLLL,
Jeff Brown51e7fe72010-10-29 22:19:53 -07001295 AMETA_SCROLL_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001296}
1297
1298void KeyboardInputMapper::updateLedStateForModifierLocked(LockedState::LedState& ledState,
1299 int32_t led, int32_t modifier, bool reset) {
1300 if (ledState.avail) {
1301 bool desiredState = (mLocked.metaState & modifier) != 0;
Jeff Brown49ed71d2010-12-06 17:13:33 -08001302 if (reset || ledState.on != desiredState) {
Jeff Brown497a92c2010-09-12 17:55:08 -07001303 getEventHub()->setLedState(getDeviceId(), led, desiredState);
1304 ledState.on = desiredState;
1305 }
1306 }
1307}
1308
Jeff Brown6d0fec22010-07-23 21:28:06 -07001309
Jeff Brown83c09682010-12-23 17:50:18 -08001310// --- CursorInputMapper ---
Jeff Brown6d0fec22010-07-23 21:28:06 -07001311
Jeff Brown83c09682010-12-23 17:50:18 -08001312CursorInputMapper::CursorInputMapper(InputDevice* device) :
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001313 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001314 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001315}
1316
Jeff Brown83c09682010-12-23 17:50:18 -08001317CursorInputMapper::~CursorInputMapper() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001318}
1319
Jeff Brown83c09682010-12-23 17:50:18 -08001320uint32_t CursorInputMapper::getSources() {
Jeff Brownefd32662011-03-08 15:13:06 -08001321 return mSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001322}
1323
Jeff Brown83c09682010-12-23 17:50:18 -08001324void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001325 InputMapper::populateDeviceInfo(info);
1326
Jeff Brown83c09682010-12-23 17:50:18 -08001327 if (mParameters.mode == Parameters::MODE_POINTER) {
1328 float minX, minY, maxX, maxY;
1329 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
Jeff Brownefd32662011-03-08 15:13:06 -08001330 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f);
1331 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f);
Jeff Brown83c09682010-12-23 17:50:18 -08001332 }
1333 } else {
Jeff Brownefd32662011-03-08 15:13:06 -08001334 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale);
1335 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale);
Jeff Brown83c09682010-12-23 17:50:18 -08001336 }
Jeff Brownefd32662011-03-08 15:13:06 -08001337 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001338
1339 if (mHaveVWheel) {
Jeff Brownefd32662011-03-08 15:13:06 -08001340 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001341 }
1342 if (mHaveHWheel) {
Jeff Brownefd32662011-03-08 15:13:06 -08001343 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001344 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001345}
1346
Jeff Brown83c09682010-12-23 17:50:18 -08001347void CursorInputMapper::dump(String8& dump) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07001348 { // acquire lock
1349 AutoMutex _l(mLock);
Jeff Brown83c09682010-12-23 17:50:18 -08001350 dump.append(INDENT2 "Cursor Input Mapper:\n");
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001351 dumpParameters(dump);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001352 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
1353 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
Jeff Brownef3d7e82010-09-30 14:33:04 -07001354 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
1355 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001356 dump.appendFormat(INDENT3 "HaveVWheel: %s\n", toString(mHaveVWheel));
1357 dump.appendFormat(INDENT3 "HaveHWheel: %s\n", toString(mHaveHWheel));
1358 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
1359 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001360 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mLocked.buttonState);
1361 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mLocked.buttonState)));
Jeff Brownef3d7e82010-09-30 14:33:04 -07001362 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
1363 } // release lock
1364}
1365
Jeff Brown83c09682010-12-23 17:50:18 -08001366void CursorInputMapper::configure() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001367 InputMapper::configure();
1368
1369 // Configure basic parameters.
1370 configureParameters();
Jeff Brown83c09682010-12-23 17:50:18 -08001371
1372 // Configure device mode.
1373 switch (mParameters.mode) {
1374 case Parameters::MODE_POINTER:
Jeff Brownefd32662011-03-08 15:13:06 -08001375 mSource = AINPUT_SOURCE_MOUSE;
Jeff Brown83c09682010-12-23 17:50:18 -08001376 mXPrecision = 1.0f;
1377 mYPrecision = 1.0f;
1378 mXScale = 1.0f;
1379 mYScale = 1.0f;
1380 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
1381 break;
1382 case Parameters::MODE_NAVIGATION:
Jeff Brownefd32662011-03-08 15:13:06 -08001383 mSource = AINPUT_SOURCE_TRACKBALL;
Jeff Brown83c09682010-12-23 17:50:18 -08001384 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1385 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1386 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1387 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1388 break;
1389 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08001390
1391 mVWheelScale = 1.0f;
1392 mHWheelScale = 1.0f;
Jeff Browncc0c1592011-02-19 05:07:28 -08001393
1394 mHaveVWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_WHEEL);
1395 mHaveHWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_HWHEEL);
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001396}
1397
Jeff Brown83c09682010-12-23 17:50:18 -08001398void CursorInputMapper::configureParameters() {
1399 mParameters.mode = Parameters::MODE_POINTER;
1400 String8 cursorModeString;
1401 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
1402 if (cursorModeString == "navigation") {
1403 mParameters.mode = Parameters::MODE_NAVIGATION;
1404 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
1405 LOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
1406 }
1407 }
1408
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001409 mParameters.orientationAware = false;
Jeff Brown83c09682010-12-23 17:50:18 -08001410 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001411 mParameters.orientationAware);
1412
Jeff Brown83c09682010-12-23 17:50:18 -08001413 mParameters.associatedDisplayId = mParameters.mode == Parameters::MODE_POINTER
1414 || mParameters.orientationAware ? 0 : -1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001415}
1416
Jeff Brown83c09682010-12-23 17:50:18 -08001417void CursorInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001418 dump.append(INDENT3 "Parameters:\n");
1419 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1420 mParameters.associatedDisplayId);
Jeff Brown83c09682010-12-23 17:50:18 -08001421
1422 switch (mParameters.mode) {
1423 case Parameters::MODE_POINTER:
1424 dump.append(INDENT4 "Mode: pointer\n");
1425 break;
1426 case Parameters::MODE_NAVIGATION:
1427 dump.append(INDENT4 "Mode: navigation\n");
1428 break;
1429 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07001430 LOG_ASSERT(false);
Jeff Brown83c09682010-12-23 17:50:18 -08001431 }
1432
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001433 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1434 toString(mParameters.orientationAware));
1435}
1436
Jeff Brown83c09682010-12-23 17:50:18 -08001437void CursorInputMapper::initializeLocked() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001438 mAccumulator.clear();
1439
Jeff Brownefd32662011-03-08 15:13:06 -08001440 mLocked.buttonState = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001441 mLocked.downTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001442}
1443
Jeff Brown83c09682010-12-23 17:50:18 -08001444void CursorInputMapper::reset() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001445 for (;;) {
Jeff Brownefd32662011-03-08 15:13:06 -08001446 uint32_t buttonState;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001447 { // acquire lock
1448 AutoMutex _l(mLock);
1449
Jeff Brownefd32662011-03-08 15:13:06 -08001450 buttonState = mLocked.buttonState;
1451 if (!buttonState) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001452 initializeLocked();
1453 break; // done
1454 }
1455 } // release lock
1456
Jeff Brown83c09682010-12-23 17:50:18 -08001457 // Synthesize button up event on reset.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001458 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brownefd32662011-03-08 15:13:06 -08001459 mAccumulator.clear();
1460 mAccumulator.buttonDown = 0;
1461 mAccumulator.buttonUp = buttonState;
1462 mAccumulator.fields = Accumulator::FIELD_BUTTONS;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001463 sync(when);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001464 }
1465
Jeff Brown6d0fec22010-07-23 21:28:06 -07001466 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001467}
Jeff Brown46b9ac02010-04-22 18:58:52 -07001468
Jeff Brown83c09682010-12-23 17:50:18 -08001469void CursorInputMapper::process(const RawEvent* rawEvent) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001470 switch (rawEvent->type) {
Jeff Brownefd32662011-03-08 15:13:06 -08001471 case EV_KEY: {
1472 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
1473 if (buttonState) {
1474 if (rawEvent->value) {
1475 mAccumulator.buttonDown = buttonState;
1476 mAccumulator.buttonUp = 0;
1477 } else {
1478 mAccumulator.buttonDown = 0;
1479 mAccumulator.buttonUp = buttonState;
1480 }
1481 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
1482
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001483 // Sync now since BTN_MOUSE is not necessarily followed by SYN_REPORT and
1484 // we need to ensure that we report the up/down promptly.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001485 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001486 break;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001487 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001488 break;
Jeff Brownefd32662011-03-08 15:13:06 -08001489 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001490
Jeff Brown6d0fec22010-07-23 21:28:06 -07001491 case EV_REL:
1492 switch (rawEvent->scanCode) {
1493 case REL_X:
1494 mAccumulator.fields |= Accumulator::FIELD_REL_X;
1495 mAccumulator.relX = rawEvent->value;
1496 break;
1497 case REL_Y:
1498 mAccumulator.fields |= Accumulator::FIELD_REL_Y;
1499 mAccumulator.relY = rawEvent->value;
1500 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001501 case REL_WHEEL:
1502 mAccumulator.fields |= Accumulator::FIELD_REL_WHEEL;
1503 mAccumulator.relWheel = rawEvent->value;
1504 break;
1505 case REL_HWHEEL:
1506 mAccumulator.fields |= Accumulator::FIELD_REL_HWHEEL;
1507 mAccumulator.relHWheel = rawEvent->value;
1508 break;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001509 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001510 break;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001511
Jeff Brown6d0fec22010-07-23 21:28:06 -07001512 case EV_SYN:
1513 switch (rawEvent->scanCode) {
1514 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001515 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001516 break;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001517 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001518 break;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001519 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001520}
1521
Jeff Brown83c09682010-12-23 17:50:18 -08001522void CursorInputMapper::sync(nsecs_t when) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001523 uint32_t fields = mAccumulator.fields;
1524 if (fields == 0) {
1525 return; // no new state changes, so nothing to do
1526 }
1527
Jeff Brown9626b142011-03-03 02:09:54 -08001528 int32_t motionEventAction;
1529 int32_t motionEventEdgeFlags;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001530 PointerCoords pointerCoords;
1531 nsecs_t downTime;
Jeff Brown33bbfd22011-02-24 20:55:35 -08001532 float vscroll, hscroll;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001533 { // acquire lock
1534 AutoMutex _l(mLock);
Jeff Brown46b9ac02010-04-22 18:58:52 -07001535
Jeff Brownefd32662011-03-08 15:13:06 -08001536 bool down, downChanged;
1537 bool wasDown = isPointerDown(mLocked.buttonState);
1538 bool buttonsChanged = fields & Accumulator::FIELD_BUTTONS;
1539 if (buttonsChanged) {
1540 mLocked.buttonState = (mLocked.buttonState | mAccumulator.buttonDown)
1541 & ~mAccumulator.buttonUp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001542
Jeff Brownefd32662011-03-08 15:13:06 -08001543 down = isPointerDown(mLocked.buttonState);
1544
1545 if (!wasDown && down) {
1546 mLocked.downTime = when;
1547 downChanged = true;
1548 } else if (wasDown && !down) {
1549 downChanged = true;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001550 } else {
Jeff Brownefd32662011-03-08 15:13:06 -08001551 downChanged = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001552 }
Jeff Brownefd32662011-03-08 15:13:06 -08001553 } else {
1554 down = wasDown;
1555 downChanged = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001556 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001557
Jeff Brown6328cdc2010-07-29 18:18:33 -07001558 downTime = mLocked.downTime;
Jeff Brown83c09682010-12-23 17:50:18 -08001559 float deltaX = fields & Accumulator::FIELD_REL_X ? mAccumulator.relX * mXScale : 0.0f;
1560 float deltaY = fields & Accumulator::FIELD_REL_Y ? mAccumulator.relY * mYScale : 0.0f;
Jeff Brown46b9ac02010-04-22 18:58:52 -07001561
Jeff Brown6328cdc2010-07-29 18:18:33 -07001562 if (downChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08001563 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
1564 } else if (down || mPointerController == NULL) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001565 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
Jeff Browncc0c1592011-02-19 05:07:28 -08001566 } else {
1567 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001568 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001569
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001570 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0
Jeff Brown83c09682010-12-23 17:50:18 -08001571 && (deltaX != 0.0f || deltaY != 0.0f)) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001572 // Rotate motion based on display orientation if needed.
1573 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
1574 int32_t orientation;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001575 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1576 NULL, NULL, & orientation)) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001577 orientation = DISPLAY_ORIENTATION_0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001578 }
1579
1580 float temp;
1581 switch (orientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001582 case DISPLAY_ORIENTATION_90:
Jeff Brown83c09682010-12-23 17:50:18 -08001583 temp = deltaX;
1584 deltaX = deltaY;
1585 deltaY = -temp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001586 break;
1587
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001588 case DISPLAY_ORIENTATION_180:
Jeff Brown83c09682010-12-23 17:50:18 -08001589 deltaX = -deltaX;
1590 deltaY = -deltaY;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001591 break;
1592
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001593 case DISPLAY_ORIENTATION_270:
Jeff Brown83c09682010-12-23 17:50:18 -08001594 temp = deltaX;
1595 deltaX = -deltaY;
1596 deltaY = temp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001597 break;
1598 }
1599 }
Jeff Brown83c09682010-12-23 17:50:18 -08001600
Jeff Brown91c69ab2011-02-14 17:03:18 -08001601 pointerCoords.clear();
1602
Jeff Brown9626b142011-03-03 02:09:54 -08001603 motionEventEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
1604
Jeff Brown2352b972011-04-12 22:39:53 -07001605 if (mHaveVWheel && (fields & Accumulator::FIELD_REL_WHEEL)) {
1606 vscroll = mAccumulator.relWheel;
1607 } else {
1608 vscroll = 0;
1609 }
1610 if (mHaveHWheel && (fields & Accumulator::FIELD_REL_HWHEEL)) {
1611 hscroll = mAccumulator.relHWheel;
1612 } else {
1613 hscroll = 0;
1614 }
1615
Jeff Brown83c09682010-12-23 17:50:18 -08001616 if (mPointerController != NULL) {
Jeff Brown2352b972011-04-12 22:39:53 -07001617 if (deltaX != 0 || deltaY != 0 || vscroll != 0 || hscroll != 0
1618 || buttonsChanged) {
1619 mPointerController->setPresentation(
1620 PointerControllerInterface::PRESENTATION_POINTER);
1621
1622 if (deltaX != 0 || deltaY != 0) {
1623 mPointerController->move(deltaX, deltaY);
1624 }
1625
1626 if (buttonsChanged) {
1627 mPointerController->setButtonState(mLocked.buttonState);
1628 }
1629
1630 mPointerController->unfade();
Jeff Brown83c09682010-12-23 17:50:18 -08001631 }
Jeff Brownefd32662011-03-08 15:13:06 -08001632
Jeff Brown91c69ab2011-02-14 17:03:18 -08001633 float x, y;
1634 mPointerController->getPosition(&x, &y);
Jeff Brownebbd5d12011-02-17 13:01:34 -08001635 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
1636 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jeff Brown9626b142011-03-03 02:09:54 -08001637
1638 if (motionEventAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownefd32662011-03-08 15:13:06 -08001639 motionEventEdgeFlags = calculateEdgeFlagsUsingPointerBounds(
1640 mPointerController, x, y);
Jeff Brown9626b142011-03-03 02:09:54 -08001641 }
Jeff Brown83c09682010-12-23 17:50:18 -08001642 } else {
Jeff Brownebbd5d12011-02-17 13:01:34 -08001643 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
1644 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
Jeff Brown83c09682010-12-23 17:50:18 -08001645 }
1646
Jeff Brownefd32662011-03-08 15:13:06 -08001647 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
Jeff Brown6328cdc2010-07-29 18:18:33 -07001648 } // release lock
1649
Jeff Brown56194eb2011-03-02 19:23:13 -08001650 // Moving an external trackball or mouse should wake the device.
1651 // We don't do this for internal cursor devices to prevent them from waking up
1652 // the device in your pocket.
1653 // TODO: Use the input device configuration to control this behavior more finely.
1654 uint32_t policyFlags = 0;
1655 if (getDevice()->isExternal()) {
1656 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1657 }
1658
Jeff Brown6d0fec22010-07-23 21:28:06 -07001659 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown6328cdc2010-07-29 18:18:33 -07001660 int32_t pointerId = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08001661 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brown9626b142011-03-03 02:09:54 -08001662 motionEventAction, 0, metaState, motionEventEdgeFlags,
Jeff Brownb6997262010-10-08 22:31:17 -07001663 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1664
Jeff Browna032cc02011-03-07 16:56:21 -08001665 // Send hover move after UP to tell the application that the mouse is hovering now.
1666 if (motionEventAction == AMOTION_EVENT_ACTION_UP
1667 && mPointerController != NULL) {
1668 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
1669 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
1670 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1671 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001672
Jeff Browna032cc02011-03-07 16:56:21 -08001673 // Send scroll events.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001674 if (vscroll != 0 || hscroll != 0) {
1675 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
1676 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
1677
Jeff Brownefd32662011-03-08 15:13:06 -08001678 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brown33bbfd22011-02-24 20:55:35 -08001679 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
1680 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1681 }
Jeff Browna032cc02011-03-07 16:56:21 -08001682
1683 mAccumulator.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001684}
1685
Jeff Brown83c09682010-12-23 17:50:18 -08001686int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brownc3fc2d02010-08-10 15:47:53 -07001687 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
1688 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1689 } else {
1690 return AKEY_STATE_UNKNOWN;
1691 }
1692}
1693
Jeff Brown05dc66a2011-03-02 14:41:58 -08001694void CursorInputMapper::fadePointer() {
1695 { // acquire lock
1696 AutoMutex _l(mLock);
Jeff Brownefd32662011-03-08 15:13:06 -08001697 if (mPointerController != NULL) {
1698 mPointerController->fade();
1699 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001700 } // release lock
1701}
1702
Jeff Brown6d0fec22010-07-23 21:28:06 -07001703
1704// --- TouchInputMapper ---
1705
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001706TouchInputMapper::TouchInputMapper(InputDevice* device) :
1707 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001708 mLocked.surfaceOrientation = -1;
1709 mLocked.surfaceWidth = -1;
1710 mLocked.surfaceHeight = -1;
1711
1712 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001713}
1714
1715TouchInputMapper::~TouchInputMapper() {
1716}
1717
1718uint32_t TouchInputMapper::getSources() {
Jeff Brownace13b12011-03-09 17:39:48 -08001719 return mTouchSource | mPointerSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001720}
1721
1722void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1723 InputMapper::populateDeviceInfo(info);
1724
Jeff Brown6328cdc2010-07-29 18:18:33 -07001725 { // acquire lock
1726 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001727
Jeff Brown6328cdc2010-07-29 18:18:33 -07001728 // Ensure surface information is up to date so that orientation changes are
1729 // noticed immediately.
Jeff Brownefd32662011-03-08 15:13:06 -08001730 if (!configureSurfaceLocked()) {
1731 return;
1732 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001733
Jeff Brownefd32662011-03-08 15:13:06 -08001734 info->addMotionRange(mLocked.orientedRanges.x);
1735 info->addMotionRange(mLocked.orientedRanges.y);
Jeff Brown8d608662010-08-30 03:02:23 -07001736
1737 if (mLocked.orientedRanges.havePressure) {
Jeff Brownefd32662011-03-08 15:13:06 -08001738 info->addMotionRange(mLocked.orientedRanges.pressure);
Jeff Brown8d608662010-08-30 03:02:23 -07001739 }
1740
1741 if (mLocked.orientedRanges.haveSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001742 info->addMotionRange(mLocked.orientedRanges.size);
Jeff Brown8d608662010-08-30 03:02:23 -07001743 }
1744
Jeff Brownc6d282b2010-10-14 21:42:15 -07001745 if (mLocked.orientedRanges.haveTouchSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001746 info->addMotionRange(mLocked.orientedRanges.touchMajor);
1747 info->addMotionRange(mLocked.orientedRanges.touchMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001748 }
1749
Jeff Brownc6d282b2010-10-14 21:42:15 -07001750 if (mLocked.orientedRanges.haveToolSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001751 info->addMotionRange(mLocked.orientedRanges.toolMajor);
1752 info->addMotionRange(mLocked.orientedRanges.toolMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001753 }
1754
1755 if (mLocked.orientedRanges.haveOrientation) {
Jeff Brownefd32662011-03-08 15:13:06 -08001756 info->addMotionRange(mLocked.orientedRanges.orientation);
Jeff Brown8d608662010-08-30 03:02:23 -07001757 }
Jeff Brownace13b12011-03-09 17:39:48 -08001758
1759 if (mPointerController != NULL) {
1760 float minX, minY, maxX, maxY;
1761 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
1762 info->addMotionRange(AMOTION_EVENT_AXIS_X, mPointerSource,
1763 minX, maxX, 0.0f, 0.0f);
1764 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mPointerSource,
1765 minY, maxY, 0.0f, 0.0f);
1766 }
1767 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mPointerSource,
1768 0.0f, 1.0f, 0.0f, 0.0f);
1769 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001770 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001771}
1772
Jeff Brownef3d7e82010-09-30 14:33:04 -07001773void TouchInputMapper::dump(String8& dump) {
1774 { // acquire lock
1775 AutoMutex _l(mLock);
1776 dump.append(INDENT2 "Touch Input Mapper:\n");
Jeff Brownef3d7e82010-09-30 14:33:04 -07001777 dumpParameters(dump);
1778 dumpVirtualKeysLocked(dump);
1779 dumpRawAxes(dump);
1780 dumpCalibration(dump);
1781 dumpSurfaceLocked(dump);
Jeff Brownefd32662011-03-08 15:13:06 -08001782
Jeff Brown511ee5f2010-10-18 13:32:20 -07001783 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
Jeff Brownc6d282b2010-10-14 21:42:15 -07001784 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mLocked.xScale);
1785 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mLocked.yScale);
1786 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mLocked.xPrecision);
1787 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mLocked.yPrecision);
1788 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mLocked.geometricScale);
1789 dump.appendFormat(INDENT4 "ToolSizeLinearScale: %0.3f\n", mLocked.toolSizeLinearScale);
1790 dump.appendFormat(INDENT4 "ToolSizeLinearBias: %0.3f\n", mLocked.toolSizeLinearBias);
1791 dump.appendFormat(INDENT4 "ToolSizeAreaScale: %0.3f\n", mLocked.toolSizeAreaScale);
1792 dump.appendFormat(INDENT4 "ToolSizeAreaBias: %0.3f\n", mLocked.toolSizeAreaBias);
1793 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mLocked.pressureScale);
1794 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mLocked.sizeScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001795 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mLocked.orientationScale);
1796
1797 dump.appendFormat(INDENT3 "Last Touch:\n");
1798 dump.appendFormat(INDENT4 "Pointer Count: %d\n", mLastTouch.pointerCount);
Jeff Brownace13b12011-03-09 17:39:48 -08001799 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", mLastTouch.buttonState);
1800
1801 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
1802 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
1803 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
1804 mLocked.pointerGestureXMovementScale);
1805 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
1806 mLocked.pointerGestureYMovementScale);
1807 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
1808 mLocked.pointerGestureXZoomScale);
1809 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
1810 mLocked.pointerGestureYZoomScale);
Jeff Brown2352b972011-04-12 22:39:53 -07001811 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
1812 mLocked.pointerGestureMaxSwipeWidth);
Jeff Brownace13b12011-03-09 17:39:48 -08001813 }
Jeff Brownef3d7e82010-09-30 14:33:04 -07001814 } // release lock
1815}
1816
Jeff Brown6328cdc2010-07-29 18:18:33 -07001817void TouchInputMapper::initializeLocked() {
1818 mCurrentTouch.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001819 mLastTouch.clear();
1820 mDownTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001821
1822 for (uint32_t i = 0; i < MAX_POINTERS; i++) {
1823 mAveragingTouchFilter.historyStart[i] = 0;
1824 mAveragingTouchFilter.historyEnd[i] = 0;
1825 }
1826
1827 mJumpyTouchFilter.jumpyPointsDropped = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001828
1829 mLocked.currentVirtualKey.down = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001830
1831 mLocked.orientedRanges.havePressure = false;
1832 mLocked.orientedRanges.haveSize = false;
Jeff Brownc6d282b2010-10-14 21:42:15 -07001833 mLocked.orientedRanges.haveTouchSize = false;
1834 mLocked.orientedRanges.haveToolSize = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001835 mLocked.orientedRanges.haveOrientation = false;
Jeff Brownace13b12011-03-09 17:39:48 -08001836
1837 mPointerGesture.reset();
Jeff Brown8d608662010-08-30 03:02:23 -07001838}
1839
Jeff Brown6d0fec22010-07-23 21:28:06 -07001840void TouchInputMapper::configure() {
1841 InputMapper::configure();
1842
1843 // Configure basic parameters.
Jeff Brown8d608662010-08-30 03:02:23 -07001844 configureParameters();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001845
Jeff Brown83c09682010-12-23 17:50:18 -08001846 // Configure sources.
1847 switch (mParameters.deviceType) {
1848 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Jeff Brownefd32662011-03-08 15:13:06 -08001849 mTouchSource = AINPUT_SOURCE_TOUCHSCREEN;
Jeff Brownace13b12011-03-09 17:39:48 -08001850 mPointerSource = 0;
Jeff Brown83c09682010-12-23 17:50:18 -08001851 break;
1852 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Jeff Brownefd32662011-03-08 15:13:06 -08001853 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
Jeff Brownace13b12011-03-09 17:39:48 -08001854 mPointerSource = 0;
1855 break;
1856 case Parameters::DEVICE_TYPE_POINTER:
1857 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
1858 mPointerSource = AINPUT_SOURCE_MOUSE;
Jeff Brown83c09682010-12-23 17:50:18 -08001859 break;
1860 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07001861 LOG_ASSERT(false);
Jeff Brown83c09682010-12-23 17:50:18 -08001862 }
1863
Jeff Brown6d0fec22010-07-23 21:28:06 -07001864 // Configure absolute axis information.
Jeff Brown8d608662010-08-30 03:02:23 -07001865 configureRawAxes();
Jeff Brown8d608662010-08-30 03:02:23 -07001866
1867 // Prepare input device calibration.
1868 parseCalibration();
1869 resolveCalibration();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001870
Jeff Brown6328cdc2010-07-29 18:18:33 -07001871 { // acquire lock
1872 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001873
Jeff Brown8d608662010-08-30 03:02:23 -07001874 // Configure surface dimensions and orientation.
Jeff Brown6328cdc2010-07-29 18:18:33 -07001875 configureSurfaceLocked();
1876 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001877}
1878
Jeff Brown8d608662010-08-30 03:02:23 -07001879void TouchInputMapper::configureParameters() {
1880 mParameters.useBadTouchFilter = getPolicy()->filterTouchEvents();
1881 mParameters.useAveragingTouchFilter = getPolicy()->filterTouchEvents();
1882 mParameters.useJumpyTouchFilter = getPolicy()->filterJumpyTouchEvents();
Jeff Brownfe508922011-01-18 15:10:10 -08001883 mParameters.virtualKeyQuietTime = getPolicy()->getVirtualKeyQuietTime();
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001884
Jeff Brown2352b972011-04-12 22:39:53 -07001885 // TODO: Make this configurable.
1886 //mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER;
1887 mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
1888
Jeff Brownace13b12011-03-09 17:39:48 -08001889 if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
1890 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
1891 // The device is a cursor device with a touch pad attached.
1892 // By default don't use the touch pad to move the pointer.
1893 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
1894 } else {
1895 // The device is just a touch pad.
1896 // By default use the touch pad to move the pointer and to perform related gestures.
1897 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
1898 }
1899
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001900 String8 deviceTypeString;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001901 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
1902 deviceTypeString)) {
Jeff Brown58a2da82011-01-25 16:02:22 -08001903 if (deviceTypeString == "touchScreen") {
1904 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brownefd32662011-03-08 15:13:06 -08001905 } else if (deviceTypeString == "touchPad") {
1906 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
Jeff Brownace13b12011-03-09 17:39:48 -08001907 } else if (deviceTypeString == "pointer") {
1908 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
Jeff Brownefd32662011-03-08 15:13:06 -08001909 } else {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001910 LOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
1911 }
1912 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001913
Jeff Brownefd32662011-03-08 15:13:06 -08001914 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001915 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
1916 mParameters.orientationAware);
1917
Jeff Brownefd32662011-03-08 15:13:06 -08001918 mParameters.associatedDisplayId = mParameters.orientationAware
1919 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
Jeff Brownace13b12011-03-09 17:39:48 -08001920 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
Jeff Brownefd32662011-03-08 15:13:06 -08001921 ? 0 : -1;
Jeff Brown8d608662010-08-30 03:02:23 -07001922}
1923
Jeff Brownef3d7e82010-09-30 14:33:04 -07001924void TouchInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001925 dump.append(INDENT3 "Parameters:\n");
1926
1927 switch (mParameters.deviceType) {
1928 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
1929 dump.append(INDENT4 "DeviceType: touchScreen\n");
1930 break;
1931 case Parameters::DEVICE_TYPE_TOUCH_PAD:
1932 dump.append(INDENT4 "DeviceType: touchPad\n");
1933 break;
Jeff Brownace13b12011-03-09 17:39:48 -08001934 case Parameters::DEVICE_TYPE_POINTER:
1935 dump.append(INDENT4 "DeviceType: pointer\n");
1936 break;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001937 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07001938 LOG_ASSERT(false);
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001939 }
1940
1941 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1942 mParameters.associatedDisplayId);
1943 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1944 toString(mParameters.orientationAware));
1945
1946 dump.appendFormat(INDENT4 "UseBadTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001947 toString(mParameters.useBadTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001948 dump.appendFormat(INDENT4 "UseAveragingTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001949 toString(mParameters.useAveragingTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001950 dump.appendFormat(INDENT4 "UseJumpyTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001951 toString(mParameters.useJumpyTouchFilter));
Jeff Brownb88102f2010-09-08 11:49:43 -07001952}
1953
Jeff Brown8d608662010-08-30 03:02:23 -07001954void TouchInputMapper::configureRawAxes() {
1955 mRawAxes.x.clear();
1956 mRawAxes.y.clear();
1957 mRawAxes.pressure.clear();
1958 mRawAxes.touchMajor.clear();
1959 mRawAxes.touchMinor.clear();
1960 mRawAxes.toolMajor.clear();
1961 mRawAxes.toolMinor.clear();
1962 mRawAxes.orientation.clear();
1963}
1964
Jeff Brownef3d7e82010-09-30 14:33:04 -07001965void TouchInputMapper::dumpRawAxes(String8& dump) {
1966 dump.append(INDENT3 "Raw Axes:\n");
Jeff Browncb1404e2011-01-15 18:14:15 -08001967 dumpRawAbsoluteAxisInfo(dump, mRawAxes.x, "X");
1968 dumpRawAbsoluteAxisInfo(dump, mRawAxes.y, "Y");
1969 dumpRawAbsoluteAxisInfo(dump, mRawAxes.pressure, "Pressure");
1970 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMajor, "TouchMajor");
1971 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMinor, "TouchMinor");
1972 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMajor, "ToolMajor");
1973 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMinor, "ToolMinor");
1974 dumpRawAbsoluteAxisInfo(dump, mRawAxes.orientation, "Orientation");
Jeff Brown6d0fec22010-07-23 21:28:06 -07001975}
1976
Jeff Brown6328cdc2010-07-29 18:18:33 -07001977bool TouchInputMapper::configureSurfaceLocked() {
Jeff Brown9626b142011-03-03 02:09:54 -08001978 // Ensure we have valid X and Y axes.
1979 if (!mRawAxes.x.valid || !mRawAxes.y.valid) {
1980 LOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
1981 "The device will be inoperable.", getDeviceName().string());
1982 return false;
1983 }
1984
Jeff Brown6d0fec22010-07-23 21:28:06 -07001985 // Update orientation and dimensions if needed.
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001986 int32_t orientation = DISPLAY_ORIENTATION_0;
Jeff Brown9626b142011-03-03 02:09:54 -08001987 int32_t width = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
1988 int32_t height = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001989
1990 if (mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001991 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001992 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
Jeff Brownefd32662011-03-08 15:13:06 -08001993 &mLocked.associatedDisplayWidth, &mLocked.associatedDisplayHeight,
1994 &mLocked.associatedDisplayOrientation)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001995 return false;
1996 }
Jeff Brownefd32662011-03-08 15:13:06 -08001997
1998 // A touch screen inherits the dimensions of the display.
1999 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
2000 width = mLocked.associatedDisplayWidth;
2001 height = mLocked.associatedDisplayHeight;
2002 }
2003
2004 // The device inherits the orientation of the display if it is orientation aware.
2005 if (mParameters.orientationAware) {
2006 orientation = mLocked.associatedDisplayOrientation;
2007 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002008 }
2009
Jeff Brownace13b12011-03-09 17:39:48 -08002010 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
2011 && mPointerController == NULL) {
2012 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2013 }
2014
Jeff Brown6328cdc2010-07-29 18:18:33 -07002015 bool orientationChanged = mLocked.surfaceOrientation != orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002016 if (orientationChanged) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002017 mLocked.surfaceOrientation = orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002018 }
2019
Jeff Brown6328cdc2010-07-29 18:18:33 -07002020 bool sizeChanged = mLocked.surfaceWidth != width || mLocked.surfaceHeight != height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002021 if (sizeChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08002022 LOGI("Device reconfigured: id=%d, name='%s', surface size is now %dx%d",
Jeff Brownef3d7e82010-09-30 14:33:04 -07002023 getDeviceId(), getDeviceName().string(), width, height);
Jeff Brown8d608662010-08-30 03:02:23 -07002024
Jeff Brown6328cdc2010-07-29 18:18:33 -07002025 mLocked.surfaceWidth = width;
2026 mLocked.surfaceHeight = height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002027
Jeff Brown8d608662010-08-30 03:02:23 -07002028 // Configure X and Y factors.
Jeff Brown9626b142011-03-03 02:09:54 -08002029 mLocked.xScale = float(width) / (mRawAxes.x.maxValue - mRawAxes.x.minValue + 1);
2030 mLocked.yScale = float(height) / (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1);
2031 mLocked.xPrecision = 1.0f / mLocked.xScale;
2032 mLocked.yPrecision = 1.0f / mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002033
Jeff Brownefd32662011-03-08 15:13:06 -08002034 mLocked.orientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
2035 mLocked.orientedRanges.x.source = mTouchSource;
2036 mLocked.orientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
2037 mLocked.orientedRanges.y.source = mTouchSource;
2038
Jeff Brown9626b142011-03-03 02:09:54 -08002039 configureVirtualKeysLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002040
Jeff Brown8d608662010-08-30 03:02:23 -07002041 // Scale factor for terms that are not oriented in a particular axis.
2042 // If the pixels are square then xScale == yScale otherwise we fake it
2043 // by choosing an average.
2044 mLocked.geometricScale = avg(mLocked.xScale, mLocked.yScale);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002045
Jeff Brown8d608662010-08-30 03:02:23 -07002046 // Size of diagonal axis.
Jeff Brown2352b972011-04-12 22:39:53 -07002047 float diagonalSize = hypotf(width, height);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002048
Jeff Brown8d608662010-08-30 03:02:23 -07002049 // TouchMajor and TouchMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002050 if (mCalibration.touchSizeCalibration != Calibration::TOUCH_SIZE_CALIBRATION_NONE) {
2051 mLocked.orientedRanges.haveTouchSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002052
2053 mLocked.orientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
2054 mLocked.orientedRanges.touchMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002055 mLocked.orientedRanges.touchMajor.min = 0;
2056 mLocked.orientedRanges.touchMajor.max = diagonalSize;
2057 mLocked.orientedRanges.touchMajor.flat = 0;
2058 mLocked.orientedRanges.touchMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08002059
Jeff Brown8d608662010-08-30 03:02:23 -07002060 mLocked.orientedRanges.touchMinor = mLocked.orientedRanges.touchMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08002061 mLocked.orientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002062 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002063
Jeff Brown8d608662010-08-30 03:02:23 -07002064 // ToolMajor and ToolMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002065 mLocked.toolSizeLinearScale = 0;
2066 mLocked.toolSizeLinearBias = 0;
2067 mLocked.toolSizeAreaScale = 0;
2068 mLocked.toolSizeAreaBias = 0;
2069 if (mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2070 if (mCalibration.toolSizeCalibration == Calibration::TOOL_SIZE_CALIBRATION_LINEAR) {
2071 if (mCalibration.haveToolSizeLinearScale) {
2072 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
Jeff Brown8d608662010-08-30 03:02:23 -07002073 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002074 mLocked.toolSizeLinearScale = float(min(width, height))
Jeff Brown8d608662010-08-30 03:02:23 -07002075 / mRawAxes.toolMajor.maxValue;
2076 }
2077
Jeff Brownc6d282b2010-10-14 21:42:15 -07002078 if (mCalibration.haveToolSizeLinearBias) {
2079 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2080 }
2081 } else if (mCalibration.toolSizeCalibration ==
2082 Calibration::TOOL_SIZE_CALIBRATION_AREA) {
2083 if (mCalibration.haveToolSizeLinearScale) {
2084 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
2085 } else {
2086 mLocked.toolSizeLinearScale = min(width, height);
2087 }
2088
2089 if (mCalibration.haveToolSizeLinearBias) {
2090 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2091 }
2092
2093 if (mCalibration.haveToolSizeAreaScale) {
2094 mLocked.toolSizeAreaScale = mCalibration.toolSizeAreaScale;
2095 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2096 mLocked.toolSizeAreaScale = 1.0f / mRawAxes.toolMajor.maxValue;
2097 }
2098
2099 if (mCalibration.haveToolSizeAreaBias) {
2100 mLocked.toolSizeAreaBias = mCalibration.toolSizeAreaBias;
Jeff Brown8d608662010-08-30 03:02:23 -07002101 }
2102 }
2103
Jeff Brownc6d282b2010-10-14 21:42:15 -07002104 mLocked.orientedRanges.haveToolSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002105
2106 mLocked.orientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
2107 mLocked.orientedRanges.toolMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002108 mLocked.orientedRanges.toolMajor.min = 0;
2109 mLocked.orientedRanges.toolMajor.max = diagonalSize;
2110 mLocked.orientedRanges.toolMajor.flat = 0;
2111 mLocked.orientedRanges.toolMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08002112
Jeff Brown8d608662010-08-30 03:02:23 -07002113 mLocked.orientedRanges.toolMinor = mLocked.orientedRanges.toolMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08002114 mLocked.orientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002115 }
2116
2117 // Pressure factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002118 mLocked.pressureScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002119 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE) {
2120 RawAbsoluteAxisInfo rawPressureAxis;
2121 switch (mCalibration.pressureSource) {
2122 case Calibration::PRESSURE_SOURCE_PRESSURE:
2123 rawPressureAxis = mRawAxes.pressure;
2124 break;
2125 case Calibration::PRESSURE_SOURCE_TOUCH:
2126 rawPressureAxis = mRawAxes.touchMajor;
2127 break;
2128 default:
2129 rawPressureAxis.clear();
2130 }
2131
Jeff Brown8d608662010-08-30 03:02:23 -07002132 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
2133 || mCalibration.pressureCalibration
2134 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
2135 if (mCalibration.havePressureScale) {
2136 mLocked.pressureScale = mCalibration.pressureScale;
2137 } else if (rawPressureAxis.valid && rawPressureAxis.maxValue != 0) {
2138 mLocked.pressureScale = 1.0f / rawPressureAxis.maxValue;
2139 }
2140 }
2141
2142 mLocked.orientedRanges.havePressure = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002143
2144 mLocked.orientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
2145 mLocked.orientedRanges.pressure.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002146 mLocked.orientedRanges.pressure.min = 0;
2147 mLocked.orientedRanges.pressure.max = 1.0;
2148 mLocked.orientedRanges.pressure.flat = 0;
2149 mLocked.orientedRanges.pressure.fuzz = 0;
2150 }
2151
2152 // Size factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002153 mLocked.sizeScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002154 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002155 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_NORMALIZED) {
2156 if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2157 mLocked.sizeScale = 1.0f / mRawAxes.toolMajor.maxValue;
2158 }
2159 }
2160
2161 mLocked.orientedRanges.haveSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002162
2163 mLocked.orientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
2164 mLocked.orientedRanges.size.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002165 mLocked.orientedRanges.size.min = 0;
2166 mLocked.orientedRanges.size.max = 1.0;
2167 mLocked.orientedRanges.size.flat = 0;
2168 mLocked.orientedRanges.size.fuzz = 0;
2169 }
2170
2171 // Orientation
Jeff Brownc6d282b2010-10-14 21:42:15 -07002172 mLocked.orientationScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002173 if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002174 if (mCalibration.orientationCalibration
2175 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
2176 if (mRawAxes.orientation.valid && mRawAxes.orientation.maxValue != 0) {
2177 mLocked.orientationScale = float(M_PI_2) / mRawAxes.orientation.maxValue;
2178 }
2179 }
2180
Jeff Brownefd32662011-03-08 15:13:06 -08002181 mLocked.orientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
2182 mLocked.orientedRanges.orientation.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002183 mLocked.orientedRanges.orientation.min = - M_PI_2;
2184 mLocked.orientedRanges.orientation.max = M_PI_2;
2185 mLocked.orientedRanges.orientation.flat = 0;
2186 mLocked.orientedRanges.orientation.fuzz = 0;
2187 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002188 }
2189
2190 if (orientationChanged || sizeChanged) {
Jeff Brown9626b142011-03-03 02:09:54 -08002191 // Compute oriented surface dimensions, precision, scales and ranges.
2192 // Note that the maximum value reported is an inclusive maximum value so it is one
2193 // unit less than the total width or height of surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002194 switch (mLocked.surfaceOrientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08002195 case DISPLAY_ORIENTATION_90:
2196 case DISPLAY_ORIENTATION_270:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002197 mLocked.orientedSurfaceWidth = mLocked.surfaceHeight;
2198 mLocked.orientedSurfaceHeight = mLocked.surfaceWidth;
Jeff Brown9626b142011-03-03 02:09:54 -08002199
Jeff Brown6328cdc2010-07-29 18:18:33 -07002200 mLocked.orientedXPrecision = mLocked.yPrecision;
2201 mLocked.orientedYPrecision = mLocked.xPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002202
2203 mLocked.orientedRanges.x.min = 0;
2204 mLocked.orientedRanges.x.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2205 * mLocked.yScale;
2206 mLocked.orientedRanges.x.flat = 0;
2207 mLocked.orientedRanges.x.fuzz = mLocked.yScale;
2208
2209 mLocked.orientedRanges.y.min = 0;
2210 mLocked.orientedRanges.y.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2211 * mLocked.xScale;
2212 mLocked.orientedRanges.y.flat = 0;
2213 mLocked.orientedRanges.y.fuzz = mLocked.xScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002214 break;
Jeff Brown9626b142011-03-03 02:09:54 -08002215
Jeff Brown6d0fec22010-07-23 21:28:06 -07002216 default:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002217 mLocked.orientedSurfaceWidth = mLocked.surfaceWidth;
2218 mLocked.orientedSurfaceHeight = mLocked.surfaceHeight;
Jeff Brown9626b142011-03-03 02:09:54 -08002219
Jeff Brown6328cdc2010-07-29 18:18:33 -07002220 mLocked.orientedXPrecision = mLocked.xPrecision;
2221 mLocked.orientedYPrecision = mLocked.yPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002222
2223 mLocked.orientedRanges.x.min = 0;
2224 mLocked.orientedRanges.x.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2225 * mLocked.xScale;
2226 mLocked.orientedRanges.x.flat = 0;
2227 mLocked.orientedRanges.x.fuzz = mLocked.xScale;
2228
2229 mLocked.orientedRanges.y.min = 0;
2230 mLocked.orientedRanges.y.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2231 * mLocked.yScale;
2232 mLocked.orientedRanges.y.flat = 0;
2233 mLocked.orientedRanges.y.fuzz = mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002234 break;
2235 }
Jeff Brownace13b12011-03-09 17:39:48 -08002236
2237 // Compute pointer gesture detection parameters.
2238 // TODO: These factors should not be hardcoded.
2239 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
2240 int32_t rawWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2241 int32_t rawHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown2352b972011-04-12 22:39:53 -07002242 float rawDiagonal = hypotf(rawWidth, rawHeight);
2243 float displayDiagonal = hypotf(mLocked.associatedDisplayWidth,
2244 mLocked.associatedDisplayHeight);
Jeff Brownace13b12011-03-09 17:39:48 -08002245
Jeff Brown2352b972011-04-12 22:39:53 -07002246 // Scale movements such that one whole swipe of the touch pad covers a
2247 // given area relative to the diagonal size of the display.
Jeff Brownace13b12011-03-09 17:39:48 -08002248 // Assume that the touch pad has a square aspect ratio such that movements in
2249 // X and Y of the same number of raw units cover the same physical distance.
2250 const float scaleFactor = 0.8f;
2251
Jeff Brown2352b972011-04-12 22:39:53 -07002252 mLocked.pointerGestureXMovementScale = GESTURE_MOVEMENT_SPEED_RATIO
2253 * displayDiagonal / rawDiagonal;
Jeff Brownace13b12011-03-09 17:39:48 -08002254 mLocked.pointerGestureYMovementScale = mLocked.pointerGestureXMovementScale;
2255
2256 // Scale zooms to cover a smaller range of the display than movements do.
2257 // This value determines the area around the pointer that is affected by freeform
2258 // pointer gestures.
Jeff Brown2352b972011-04-12 22:39:53 -07002259 mLocked.pointerGestureXZoomScale = GESTURE_ZOOM_SPEED_RATIO
2260 * displayDiagonal / rawDiagonal;
2261 mLocked.pointerGestureYZoomScale = mLocked.pointerGestureXZoomScale;
Jeff Brownace13b12011-03-09 17:39:48 -08002262
Jeff Brown2352b972011-04-12 22:39:53 -07002263 // Max width between pointers to detect a swipe gesture is more than some fraction
2264 // of the diagonal axis of the touch pad. Touches that are wider than this are
2265 // translated into freeform gestures.
2266 mLocked.pointerGestureMaxSwipeWidth = SWIPE_MAX_WIDTH_RATIO * rawDiagonal;
2267
2268 // Reset the current pointer gesture.
2269 mPointerGesture.reset();
2270
2271 // Remove any current spots.
2272 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
2273 mPointerController->clearSpots();
2274 }
Jeff Brownace13b12011-03-09 17:39:48 -08002275 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002276 }
2277
2278 return true;
2279}
2280
Jeff Brownef3d7e82010-09-30 14:33:04 -07002281void TouchInputMapper::dumpSurfaceLocked(String8& dump) {
2282 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mLocked.surfaceWidth);
2283 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mLocked.surfaceHeight);
2284 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mLocked.surfaceOrientation);
Jeff Brownb88102f2010-09-08 11:49:43 -07002285}
2286
Jeff Brown6328cdc2010-07-29 18:18:33 -07002287void TouchInputMapper::configureVirtualKeysLocked() {
Jeff Brown8d608662010-08-30 03:02:23 -07002288 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
Jeff Brown90655042010-12-02 13:50:46 -08002289 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002290
Jeff Brown6328cdc2010-07-29 18:18:33 -07002291 mLocked.virtualKeys.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002292
Jeff Brown6328cdc2010-07-29 18:18:33 -07002293 if (virtualKeyDefinitions.size() == 0) {
2294 return;
2295 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002296
Jeff Brown6328cdc2010-07-29 18:18:33 -07002297 mLocked.virtualKeys.setCapacity(virtualKeyDefinitions.size());
2298
Jeff Brown8d608662010-08-30 03:02:23 -07002299 int32_t touchScreenLeft = mRawAxes.x.minValue;
2300 int32_t touchScreenTop = mRawAxes.y.minValue;
Jeff Brown9626b142011-03-03 02:09:54 -08002301 int32_t touchScreenWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2302 int32_t touchScreenHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002303
2304 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002305 const VirtualKeyDefinition& virtualKeyDefinition =
Jeff Brown6328cdc2010-07-29 18:18:33 -07002306 virtualKeyDefinitions[i];
2307
2308 mLocked.virtualKeys.add();
2309 VirtualKey& virtualKey = mLocked.virtualKeys.editTop();
2310
2311 virtualKey.scanCode = virtualKeyDefinition.scanCode;
2312 int32_t keyCode;
2313 uint32_t flags;
Jeff Brown6f2fba42011-02-19 01:08:02 -08002314 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode,
Jeff Brown6328cdc2010-07-29 18:18:33 -07002315 & keyCode, & flags)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002316 LOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
2317 virtualKey.scanCode);
Jeff Brown6328cdc2010-07-29 18:18:33 -07002318 mLocked.virtualKeys.pop(); // drop the key
2319 continue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002320 }
2321
Jeff Brown6328cdc2010-07-29 18:18:33 -07002322 virtualKey.keyCode = keyCode;
2323 virtualKey.flags = flags;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002324
Jeff Brown6328cdc2010-07-29 18:18:33 -07002325 // convert the key definition's display coordinates into touch coordinates for a hit box
2326 int32_t halfWidth = virtualKeyDefinition.width / 2;
2327 int32_t halfHeight = virtualKeyDefinition.height / 2;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002328
Jeff Brown6328cdc2010-07-29 18:18:33 -07002329 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
2330 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2331 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
2332 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2333 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
2334 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
2335 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
2336 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
Jeff Brownef3d7e82010-09-30 14:33:04 -07002337 }
2338}
2339
2340void TouchInputMapper::dumpVirtualKeysLocked(String8& dump) {
2341 if (!mLocked.virtualKeys.isEmpty()) {
2342 dump.append(INDENT3 "Virtual Keys:\n");
2343
2344 for (size_t i = 0; i < mLocked.virtualKeys.size(); i++) {
2345 const VirtualKey& virtualKey = mLocked.virtualKeys.itemAt(i);
2346 dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, "
2347 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
2348 i, virtualKey.scanCode, virtualKey.keyCode,
2349 virtualKey.hitLeft, virtualKey.hitRight,
2350 virtualKey.hitTop, virtualKey.hitBottom);
2351 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002352 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002353}
2354
Jeff Brown8d608662010-08-30 03:02:23 -07002355void TouchInputMapper::parseCalibration() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002356 const PropertyMap& in = getDevice()->getConfiguration();
Jeff Brown8d608662010-08-30 03:02:23 -07002357 Calibration& out = mCalibration;
2358
Jeff Brownc6d282b2010-10-14 21:42:15 -07002359 // Touch Size
2360 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT;
2361 String8 touchSizeCalibrationString;
2362 if (in.tryGetProperty(String8("touch.touchSize.calibration"), touchSizeCalibrationString)) {
2363 if (touchSizeCalibrationString == "none") {
2364 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
2365 } else if (touchSizeCalibrationString == "geometric") {
2366 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC;
2367 } else if (touchSizeCalibrationString == "pressure") {
2368 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
2369 } else if (touchSizeCalibrationString != "default") {
2370 LOGW("Invalid value for touch.touchSize.calibration: '%s'",
2371 touchSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002372 }
2373 }
2374
Jeff Brownc6d282b2010-10-14 21:42:15 -07002375 // Tool Size
2376 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_DEFAULT;
2377 String8 toolSizeCalibrationString;
2378 if (in.tryGetProperty(String8("touch.toolSize.calibration"), toolSizeCalibrationString)) {
2379 if (toolSizeCalibrationString == "none") {
2380 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
2381 } else if (toolSizeCalibrationString == "geometric") {
2382 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC;
2383 } else if (toolSizeCalibrationString == "linear") {
2384 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
2385 } else if (toolSizeCalibrationString == "area") {
2386 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_AREA;
2387 } else if (toolSizeCalibrationString != "default") {
2388 LOGW("Invalid value for touch.toolSize.calibration: '%s'",
2389 toolSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002390 }
2391 }
2392
Jeff Brownc6d282b2010-10-14 21:42:15 -07002393 out.haveToolSizeLinearScale = in.tryGetProperty(String8("touch.toolSize.linearScale"),
2394 out.toolSizeLinearScale);
2395 out.haveToolSizeLinearBias = in.tryGetProperty(String8("touch.toolSize.linearBias"),
2396 out.toolSizeLinearBias);
2397 out.haveToolSizeAreaScale = in.tryGetProperty(String8("touch.toolSize.areaScale"),
2398 out.toolSizeAreaScale);
2399 out.haveToolSizeAreaBias = in.tryGetProperty(String8("touch.toolSize.areaBias"),
2400 out.toolSizeAreaBias);
2401 out.haveToolSizeIsSummed = in.tryGetProperty(String8("touch.toolSize.isSummed"),
2402 out.toolSizeIsSummed);
Jeff Brown8d608662010-08-30 03:02:23 -07002403
2404 // Pressure
2405 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
2406 String8 pressureCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002407 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002408 if (pressureCalibrationString == "none") {
2409 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2410 } else if (pressureCalibrationString == "physical") {
2411 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
2412 } else if (pressureCalibrationString == "amplitude") {
2413 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2414 } else if (pressureCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002415 LOGW("Invalid value for touch.pressure.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002416 pressureCalibrationString.string());
2417 }
2418 }
2419
2420 out.pressureSource = Calibration::PRESSURE_SOURCE_DEFAULT;
2421 String8 pressureSourceString;
2422 if (in.tryGetProperty(String8("touch.pressure.source"), pressureSourceString)) {
2423 if (pressureSourceString == "pressure") {
2424 out.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2425 } else if (pressureSourceString == "touch") {
2426 out.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2427 } else if (pressureSourceString != "default") {
2428 LOGW("Invalid value for touch.pressure.source: '%s'",
2429 pressureSourceString.string());
2430 }
2431 }
2432
2433 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
2434 out.pressureScale);
2435
2436 // Size
2437 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
2438 String8 sizeCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002439 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002440 if (sizeCalibrationString == "none") {
2441 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2442 } else if (sizeCalibrationString == "normalized") {
2443 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2444 } else if (sizeCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002445 LOGW("Invalid value for touch.size.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002446 sizeCalibrationString.string());
2447 }
2448 }
2449
2450 // Orientation
2451 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
2452 String8 orientationCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002453 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002454 if (orientationCalibrationString == "none") {
2455 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2456 } else if (orientationCalibrationString == "interpolated") {
2457 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002458 } else if (orientationCalibrationString == "vector") {
2459 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002460 } else if (orientationCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002461 LOGW("Invalid value for touch.orientation.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002462 orientationCalibrationString.string());
2463 }
2464 }
2465}
2466
2467void TouchInputMapper::resolveCalibration() {
2468 // Pressure
2469 switch (mCalibration.pressureSource) {
2470 case Calibration::PRESSURE_SOURCE_DEFAULT:
2471 if (mRawAxes.pressure.valid) {
2472 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2473 } else if (mRawAxes.touchMajor.valid) {
2474 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2475 }
2476 break;
2477
2478 case Calibration::PRESSURE_SOURCE_PRESSURE:
2479 if (! mRawAxes.pressure.valid) {
2480 LOGW("Calibration property touch.pressure.source is 'pressure' but "
2481 "the pressure axis is not available.");
2482 }
2483 break;
2484
2485 case Calibration::PRESSURE_SOURCE_TOUCH:
2486 if (! mRawAxes.touchMajor.valid) {
2487 LOGW("Calibration property touch.pressure.source is 'touch' but "
2488 "the touchMajor axis is not available.");
2489 }
2490 break;
2491
2492 default:
2493 break;
2494 }
2495
2496 switch (mCalibration.pressureCalibration) {
2497 case Calibration::PRESSURE_CALIBRATION_DEFAULT:
2498 if (mCalibration.pressureSource != Calibration::PRESSURE_SOURCE_DEFAULT) {
2499 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2500 } else {
2501 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2502 }
2503 break;
2504
2505 default:
2506 break;
2507 }
2508
Jeff Brownc6d282b2010-10-14 21:42:15 -07002509 // Tool Size
2510 switch (mCalibration.toolSizeCalibration) {
2511 case Calibration::TOOL_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002512 if (mRawAxes.toolMajor.valid) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002513 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
Jeff Brown8d608662010-08-30 03:02:23 -07002514 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002515 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002516 }
2517 break;
2518
2519 default:
2520 break;
2521 }
2522
Jeff Brownc6d282b2010-10-14 21:42:15 -07002523 // Touch Size
2524 switch (mCalibration.touchSizeCalibration) {
2525 case Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002526 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE
Jeff Brownc6d282b2010-10-14 21:42:15 -07002527 && mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2528 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
Jeff Brown8d608662010-08-30 03:02:23 -07002529 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002530 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002531 }
2532 break;
2533
2534 default:
2535 break;
2536 }
2537
2538 // Size
2539 switch (mCalibration.sizeCalibration) {
2540 case Calibration::SIZE_CALIBRATION_DEFAULT:
2541 if (mRawAxes.toolMajor.valid) {
2542 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2543 } else {
2544 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2545 }
2546 break;
2547
2548 default:
2549 break;
2550 }
2551
2552 // Orientation
2553 switch (mCalibration.orientationCalibration) {
2554 case Calibration::ORIENTATION_CALIBRATION_DEFAULT:
2555 if (mRawAxes.orientation.valid) {
2556 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
2557 } else {
2558 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2559 }
2560 break;
2561
2562 default:
2563 break;
2564 }
2565}
2566
Jeff Brownef3d7e82010-09-30 14:33:04 -07002567void TouchInputMapper::dumpCalibration(String8& dump) {
2568 dump.append(INDENT3 "Calibration:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002569
Jeff Brownc6d282b2010-10-14 21:42:15 -07002570 // Touch Size
2571 switch (mCalibration.touchSizeCalibration) {
2572 case Calibration::TOUCH_SIZE_CALIBRATION_NONE:
2573 dump.append(INDENT4 "touch.touchSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002574 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002575 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
2576 dump.append(INDENT4 "touch.touchSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002577 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002578 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
2579 dump.append(INDENT4 "touch.touchSize.calibration: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002580 break;
2581 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002582 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002583 }
2584
Jeff Brownc6d282b2010-10-14 21:42:15 -07002585 // Tool Size
2586 switch (mCalibration.toolSizeCalibration) {
2587 case Calibration::TOOL_SIZE_CALIBRATION_NONE:
2588 dump.append(INDENT4 "touch.toolSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002589 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002590 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
2591 dump.append(INDENT4 "touch.toolSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002592 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002593 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
2594 dump.append(INDENT4 "touch.toolSize.calibration: linear\n");
2595 break;
2596 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
2597 dump.append(INDENT4 "touch.toolSize.calibration: area\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002598 break;
2599 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002600 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002601 }
2602
Jeff Brownc6d282b2010-10-14 21:42:15 -07002603 if (mCalibration.haveToolSizeLinearScale) {
2604 dump.appendFormat(INDENT4 "touch.toolSize.linearScale: %0.3f\n",
2605 mCalibration.toolSizeLinearScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002606 }
2607
Jeff Brownc6d282b2010-10-14 21:42:15 -07002608 if (mCalibration.haveToolSizeLinearBias) {
2609 dump.appendFormat(INDENT4 "touch.toolSize.linearBias: %0.3f\n",
2610 mCalibration.toolSizeLinearBias);
Jeff Brown8d608662010-08-30 03:02:23 -07002611 }
2612
Jeff Brownc6d282b2010-10-14 21:42:15 -07002613 if (mCalibration.haveToolSizeAreaScale) {
2614 dump.appendFormat(INDENT4 "touch.toolSize.areaScale: %0.3f\n",
2615 mCalibration.toolSizeAreaScale);
2616 }
2617
2618 if (mCalibration.haveToolSizeAreaBias) {
2619 dump.appendFormat(INDENT4 "touch.toolSize.areaBias: %0.3f\n",
2620 mCalibration.toolSizeAreaBias);
2621 }
2622
2623 if (mCalibration.haveToolSizeIsSummed) {
Jeff Brown1f245102010-11-18 20:53:46 -08002624 dump.appendFormat(INDENT4 "touch.toolSize.isSummed: %s\n",
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002625 toString(mCalibration.toolSizeIsSummed));
Jeff Brown8d608662010-08-30 03:02:23 -07002626 }
2627
2628 // Pressure
2629 switch (mCalibration.pressureCalibration) {
2630 case Calibration::PRESSURE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002631 dump.append(INDENT4 "touch.pressure.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002632 break;
2633 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002634 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002635 break;
2636 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002637 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002638 break;
2639 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002640 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002641 }
2642
2643 switch (mCalibration.pressureSource) {
2644 case Calibration::PRESSURE_SOURCE_PRESSURE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002645 dump.append(INDENT4 "touch.pressure.source: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002646 break;
2647 case Calibration::PRESSURE_SOURCE_TOUCH:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002648 dump.append(INDENT4 "touch.pressure.source: touch\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002649 break;
2650 case Calibration::PRESSURE_SOURCE_DEFAULT:
2651 break;
2652 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002653 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002654 }
2655
2656 if (mCalibration.havePressureScale) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07002657 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
2658 mCalibration.pressureScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002659 }
2660
2661 // Size
2662 switch (mCalibration.sizeCalibration) {
2663 case Calibration::SIZE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002664 dump.append(INDENT4 "touch.size.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002665 break;
2666 case Calibration::SIZE_CALIBRATION_NORMALIZED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002667 dump.append(INDENT4 "touch.size.calibration: normalized\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002668 break;
2669 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002670 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002671 }
2672
2673 // Orientation
2674 switch (mCalibration.orientationCalibration) {
2675 case Calibration::ORIENTATION_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002676 dump.append(INDENT4 "touch.orientation.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002677 break;
2678 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002679 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002680 break;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002681 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
2682 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
2683 break;
Jeff Brown8d608662010-08-30 03:02:23 -07002684 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002685 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002686 }
2687}
2688
Jeff Brown6d0fec22010-07-23 21:28:06 -07002689void TouchInputMapper::reset() {
2690 // Synthesize touch up event if touch is currently down.
2691 // This will also take care of finishing virtual key processing if needed.
2692 if (mLastTouch.pointerCount != 0) {
2693 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
2694 mCurrentTouch.clear();
2695 syncTouch(when, true);
2696 }
2697
Jeff Brown6328cdc2010-07-29 18:18:33 -07002698 { // acquire lock
2699 AutoMutex _l(mLock);
2700 initializeLocked();
Jeff Brown2352b972011-04-12 22:39:53 -07002701
2702 if (mPointerController != NULL
2703 && mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
2704 mPointerController->clearSpots();
2705 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002706 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002707
Jeff Brown6328cdc2010-07-29 18:18:33 -07002708 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002709}
2710
2711void TouchInputMapper::syncTouch(nsecs_t when, bool havePointerIds) {
Jeff Brownaa3855d2011-03-17 01:34:19 -07002712#if DEBUG_RAW_EVENTS
2713 if (!havePointerIds) {
2714 LOGD("syncTouch: pointerCount=%d, no pointer ids", mCurrentTouch.pointerCount);
2715 } else {
2716 LOGD("syncTouch: pointerCount=%d, up=0x%08x, down=0x%08x, move=0x%08x, "
2717 "last=0x%08x, current=0x%08x", mCurrentTouch.pointerCount,
2718 mLastTouch.idBits.value & ~mCurrentTouch.idBits.value,
2719 mCurrentTouch.idBits.value & ~mLastTouch.idBits.value,
2720 mLastTouch.idBits.value & mCurrentTouch.idBits.value,
2721 mLastTouch.idBits.value, mCurrentTouch.idBits.value);
2722 }
2723#endif
2724
Jeff Brown6328cdc2010-07-29 18:18:33 -07002725 // Preprocess pointer data.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002726 if (mParameters.useBadTouchFilter) {
2727 if (applyBadTouchFilter()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002728 havePointerIds = false;
2729 }
2730 }
2731
Jeff Brown6d0fec22010-07-23 21:28:06 -07002732 if (mParameters.useJumpyTouchFilter) {
2733 if (applyJumpyTouchFilter()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002734 havePointerIds = false;
2735 }
2736 }
2737
Jeff Brownaa3855d2011-03-17 01:34:19 -07002738 if (!havePointerIds) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002739 calculatePointerIds();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002740 }
2741
Jeff Brown6d0fec22010-07-23 21:28:06 -07002742 TouchData temp;
2743 TouchData* savedTouch;
2744 if (mParameters.useAveragingTouchFilter) {
2745 temp.copyFrom(mCurrentTouch);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002746 savedTouch = & temp;
2747
Jeff Brown6d0fec22010-07-23 21:28:06 -07002748 applyAveragingTouchFilter();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002749 } else {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002750 savedTouch = & mCurrentTouch;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002751 }
2752
Jeff Brown56194eb2011-03-02 19:23:13 -08002753 uint32_t policyFlags = 0;
Jeff Brown05dc66a2011-03-02 14:41:58 -08002754 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
Jeff Brownefd32662011-03-08 15:13:06 -08002755 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
2756 // If this is a touch screen, hide the pointer on an initial down.
2757 getContext()->fadePointer();
2758 }
Jeff Brown56194eb2011-03-02 19:23:13 -08002759
2760 // Initial downs on external touch devices should wake the device.
2761 // We don't do this for internal touch screens to prevent them from waking
2762 // up in your pocket.
2763 // TODO: Use the input device configuration to control this behavior more finely.
2764 if (getDevice()->isExternal()) {
2765 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
2766 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08002767 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002768
Jeff Brown79ac9692011-04-19 21:20:10 -07002769 TouchResult touchResult;
2770 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount == 0
2771 && mLastTouch.buttonState == mCurrentTouch.buttonState) {
2772 // Drop spurious syncs.
2773 touchResult = DROP_STROKE;
2774 } else {
2775 // Process touches and virtual keys.
2776 touchResult = consumeOffScreenTouches(when, policyFlags);
2777 if (touchResult == DISPATCH_TOUCH) {
2778 suppressSwipeOntoVirtualKeys(when);
2779 if (mPointerController != NULL) {
2780 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2781 }
2782 dispatchTouches(when, policyFlags);
Jeff Brownace13b12011-03-09 17:39:48 -08002783 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002784 }
2785
Jeff Brown6328cdc2010-07-29 18:18:33 -07002786 // Copy current touch to last touch in preparation for the next cycle.
Jeff Brownace13b12011-03-09 17:39:48 -08002787 // Keep the button state so we can track edge-triggered button state changes.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002788 if (touchResult == DROP_STROKE) {
2789 mLastTouch.clear();
Jeff Brownace13b12011-03-09 17:39:48 -08002790 mLastTouch.buttonState = savedTouch->buttonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002791 } else {
2792 mLastTouch.copyFrom(*savedTouch);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002793 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002794}
2795
Jeff Brown79ac9692011-04-19 21:20:10 -07002796void TouchInputMapper::timeoutExpired(nsecs_t when) {
2797 if (mPointerController != NULL) {
2798 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
2799 }
2800}
2801
Jeff Brown6d0fec22010-07-23 21:28:06 -07002802TouchInputMapper::TouchResult TouchInputMapper::consumeOffScreenTouches(
2803 nsecs_t when, uint32_t policyFlags) {
2804 int32_t keyEventAction, keyEventFlags;
2805 int32_t keyCode, scanCode, downTime;
2806 TouchResult touchResult;
Jeff Brown349703e2010-06-22 01:27:15 -07002807
Jeff Brown6328cdc2010-07-29 18:18:33 -07002808 { // acquire lock
2809 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002810
Jeff Brown6328cdc2010-07-29 18:18:33 -07002811 // Update surface size and orientation, including virtual key positions.
2812 if (! configureSurfaceLocked()) {
2813 return DROP_STROKE;
2814 }
2815
2816 // Check for virtual key press.
2817 if (mLocked.currentVirtualKey.down) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002818 if (mCurrentTouch.pointerCount == 0) {
2819 // Pointer went up while virtual key was down.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002820 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002821#if DEBUG_VIRTUAL_KEYS
2822 LOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002823 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002824#endif
2825 keyEventAction = AKEY_EVENT_ACTION_UP;
2826 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2827 touchResult = SKIP_TOUCH;
2828 goto DispatchVirtualKey;
2829 }
2830
2831 if (mCurrentTouch.pointerCount == 1) {
2832 int32_t x = mCurrentTouch.pointers[0].x;
2833 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002834 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
2835 if (virtualKey && virtualKey->keyCode == mLocked.currentVirtualKey.keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002836 // Pointer is still within the space of the virtual key.
2837 return SKIP_TOUCH;
2838 }
2839 }
2840
2841 // Pointer left virtual key area or another pointer also went down.
2842 // Send key cancellation and drop the stroke so subsequent motions will be
2843 // considered fresh downs. This is useful when the user swipes away from the
2844 // virtual key area into the main display surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002845 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002846#if DEBUG_VIRTUAL_KEYS
2847 LOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002848 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002849#endif
2850 keyEventAction = AKEY_EVENT_ACTION_UP;
2851 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
2852 | AKEY_EVENT_FLAG_CANCELED;
Jeff Brownc3db8582010-10-20 15:33:38 -07002853
2854 // Check whether the pointer moved inside the display area where we should
2855 // start a new stroke.
2856 int32_t x = mCurrentTouch.pointers[0].x;
2857 int32_t y = mCurrentTouch.pointers[0].y;
2858 if (isPointInsideSurfaceLocked(x, y)) {
2859 mLastTouch.clear();
2860 touchResult = DISPATCH_TOUCH;
2861 } else {
2862 touchResult = DROP_STROKE;
2863 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002864 } else {
2865 if (mCurrentTouch.pointerCount >= 1 && mLastTouch.pointerCount == 0) {
2866 // Pointer just went down. Handle off-screen touches, if needed.
2867 int32_t x = mCurrentTouch.pointers[0].x;
2868 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002869 if (! isPointInsideSurfaceLocked(x, y)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002870 // If exactly one pointer went down, check for virtual key hit.
2871 // Otherwise we will drop the entire stroke.
2872 if (mCurrentTouch.pointerCount == 1) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002873 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002874 if (virtualKey) {
Jeff Brownfe508922011-01-18 15:10:10 -08002875 if (mContext->shouldDropVirtualKey(when, getDevice(),
2876 virtualKey->keyCode, virtualKey->scanCode)) {
2877 return DROP_STROKE;
2878 }
2879
Jeff Brown6328cdc2010-07-29 18:18:33 -07002880 mLocked.currentVirtualKey.down = true;
2881 mLocked.currentVirtualKey.downTime = when;
2882 mLocked.currentVirtualKey.keyCode = virtualKey->keyCode;
2883 mLocked.currentVirtualKey.scanCode = virtualKey->scanCode;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002884#if DEBUG_VIRTUAL_KEYS
2885 LOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002886 mLocked.currentVirtualKey.keyCode,
2887 mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002888#endif
2889 keyEventAction = AKEY_EVENT_ACTION_DOWN;
2890 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM
2891 | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2892 touchResult = SKIP_TOUCH;
2893 goto DispatchVirtualKey;
2894 }
2895 }
2896 return DROP_STROKE;
2897 }
2898 }
2899 return DISPATCH_TOUCH;
2900 }
2901
2902 DispatchVirtualKey:
2903 // Collect remaining state needed to dispatch virtual key.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002904 keyCode = mLocked.currentVirtualKey.keyCode;
2905 scanCode = mLocked.currentVirtualKey.scanCode;
2906 downTime = mLocked.currentVirtualKey.downTime;
2907 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002908
2909 // Dispatch virtual key.
2910 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown0eaf3932010-10-01 14:55:30 -07002911 policyFlags |= POLICY_FLAG_VIRTUAL;
Jeff Brownb6997262010-10-08 22:31:17 -07002912 getDispatcher()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
2913 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
2914 return touchResult;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002915}
2916
Jeff Brownefd32662011-03-08 15:13:06 -08002917void TouchInputMapper::suppressSwipeOntoVirtualKeys(nsecs_t when) {
Jeff Brownfe508922011-01-18 15:10:10 -08002918 // Disable all virtual key touches that happen within a short time interval of the
2919 // most recent touch. The idea is to filter out stray virtual key presses when
2920 // interacting with the touch screen.
2921 //
2922 // Problems we're trying to solve:
2923 //
2924 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
2925 // virtual key area that is implemented by a separate touch panel and accidentally
2926 // triggers a virtual key.
2927 //
2928 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
2929 // area and accidentally triggers a virtual key. This often happens when virtual keys
2930 // are layed out below the screen near to where the on screen keyboard's space bar
2931 // is displayed.
2932 if (mParameters.virtualKeyQuietTime > 0 && mCurrentTouch.pointerCount != 0) {
2933 mContext->disableVirtualKeysUntil(when + mParameters.virtualKeyQuietTime);
2934 }
2935}
2936
Jeff Brown6d0fec22010-07-23 21:28:06 -07002937void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
2938 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
2939 uint32_t lastPointerCount = mLastTouch.pointerCount;
Jeff Brown46b9ac02010-04-22 18:58:52 -07002940 if (currentPointerCount == 0 && lastPointerCount == 0) {
2941 return; // nothing to do!
2942 }
2943
Jeff Brownace13b12011-03-09 17:39:48 -08002944 // Update current touch coordinates.
2945 int32_t edgeFlags;
2946 float xPrecision, yPrecision;
2947 prepareTouches(&edgeFlags, &xPrecision, &yPrecision);
2948
2949 // Dispatch motions.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002950 BitSet32 currentIdBits = mCurrentTouch.idBits;
2951 BitSet32 lastIdBits = mLastTouch.idBits;
Jeff Brownace13b12011-03-09 17:39:48 -08002952 uint32_t metaState = getContext()->getGlobalMetaState();
Jeff Brown46b9ac02010-04-22 18:58:52 -07002953
2954 if (currentIdBits == lastIdBits) {
2955 // No pointer id changes so this is a move event.
2956 // The dispatcher takes care of batching moves so we don't have to deal with that here.
Jeff Brownace13b12011-03-09 17:39:48 -08002957 dispatchMotion(when, policyFlags, mTouchSource,
2958 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
2959 mCurrentTouchCoords, mCurrentTouch.idToIndex, currentIdBits, -1,
2960 xPrecision, yPrecision, mDownTime);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002961 } else {
Jeff Brownc3db8582010-10-20 15:33:38 -07002962 // There may be pointers going up and pointers going down and pointers moving
2963 // all at the same time.
Jeff Brownace13b12011-03-09 17:39:48 -08002964 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2965 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002966 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
Jeff Brownace13b12011-03-09 17:39:48 -08002967 BitSet32 dispatchedIdBits(lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002968
Jeff Brownace13b12011-03-09 17:39:48 -08002969 // Update last coordinates of pointers that have moved so that we observe the new
2970 // pointer positions at the same time as other pointers that have just gone up.
2971 bool moveNeeded = updateMovedPointerCoords(
2972 mCurrentTouchCoords, mCurrentTouch.idToIndex,
2973 mLastTouchCoords, mLastTouch.idToIndex,
2974 moveIdBits);
Jeff Brownc3db8582010-10-20 15:33:38 -07002975
Jeff Brownace13b12011-03-09 17:39:48 -08002976 // Dispatch pointer up events.
Jeff Brownc3db8582010-10-20 15:33:38 -07002977 while (!upIdBits.isEmpty()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07002978 uint32_t upId = upIdBits.firstMarkedBit();
2979 upIdBits.clearBit(upId);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002980
Jeff Brownace13b12011-03-09 17:39:48 -08002981 dispatchMotion(when, policyFlags, mTouchSource,
2982 AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, 0,
2983 mLastTouchCoords, mLastTouch.idToIndex, dispatchedIdBits, upId,
2984 xPrecision, yPrecision, mDownTime);
2985 dispatchedIdBits.clearBit(upId);
Jeff Brown46b9ac02010-04-22 18:58:52 -07002986 }
2987
Jeff Brownc3db8582010-10-20 15:33:38 -07002988 // Dispatch move events if any of the remaining pointers moved from their old locations.
2989 // Although applications receive new locations as part of individual pointer up
2990 // events, they do not generally handle them except when presented in a move event.
2991 if (moveNeeded) {
Jeff Brownb6110c22011-04-01 16:15:13 -07002992 LOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Jeff Brownace13b12011-03-09 17:39:48 -08002993 dispatchMotion(when, policyFlags, mTouchSource,
2994 AMOTION_EVENT_ACTION_MOVE, 0, metaState, 0,
2995 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, -1,
2996 xPrecision, yPrecision, mDownTime);
Jeff Brownc3db8582010-10-20 15:33:38 -07002997 }
2998
2999 // Dispatch pointer down events using the new pointer locations.
3000 while (!downIdBits.isEmpty()) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07003001 uint32_t downId = downIdBits.firstMarkedBit();
3002 downIdBits.clearBit(downId);
Jeff Brownace13b12011-03-09 17:39:48 -08003003 dispatchedIdBits.markBit(downId);
Jeff Brown46b9ac02010-04-22 18:58:52 -07003004
Jeff Brownace13b12011-03-09 17:39:48 -08003005 if (dispatchedIdBits.count() == 1) {
3006 // First pointer is going down. Set down time.
Jeff Brown6d0fec22010-07-23 21:28:06 -07003007 mDownTime = when;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003008 } else {
Jeff Brownace13b12011-03-09 17:39:48 -08003009 // Only send edge flags with first pointer down.
3010 edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003011 }
3012
Jeff Brownace13b12011-03-09 17:39:48 -08003013 dispatchMotion(when, policyFlags, mTouchSource,
3014 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
3015 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, downId,
3016 xPrecision, yPrecision, mDownTime);
3017 }
3018 }
3019
3020 // Update state for next time.
3021 for (uint32_t i = 0; i < currentPointerCount; i++) {
3022 mLastTouchCoords[i].copyFrom(mCurrentTouchCoords[i]);
3023 }
3024}
3025
3026void TouchInputMapper::prepareTouches(int32_t* outEdgeFlags,
3027 float* outXPrecision, float* outYPrecision) {
3028 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
3029 uint32_t lastPointerCount = mLastTouch.pointerCount;
3030
3031 AutoMutex _l(mLock);
3032
3033 // Walk through the the active pointers and map touch screen coordinates (TouchData) into
3034 // display or surface coordinates (PointerCoords) and adjust for display orientation.
3035 for (uint32_t i = 0; i < currentPointerCount; i++) {
3036 const PointerData& in = mCurrentTouch.pointers[i];
3037
3038 // ToolMajor and ToolMinor
3039 float toolMajor, toolMinor;
3040 switch (mCalibration.toolSizeCalibration) {
3041 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
3042 toolMajor = in.toolMajor * mLocked.geometricScale;
3043 if (mRawAxes.toolMinor.valid) {
3044 toolMinor = in.toolMinor * mLocked.geometricScale;
3045 } else {
3046 toolMinor = toolMajor;
3047 }
3048 break;
3049 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
3050 toolMajor = in.toolMajor != 0
3051 ? in.toolMajor * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias
3052 : 0;
3053 if (mRawAxes.toolMinor.valid) {
3054 toolMinor = in.toolMinor != 0
3055 ? in.toolMinor * mLocked.toolSizeLinearScale
3056 + mLocked.toolSizeLinearBias
3057 : 0;
3058 } else {
3059 toolMinor = toolMajor;
3060 }
3061 break;
3062 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
3063 if (in.toolMajor != 0) {
3064 float diameter = sqrtf(in.toolMajor
3065 * mLocked.toolSizeAreaScale + mLocked.toolSizeAreaBias);
3066 toolMajor = diameter * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias;
3067 } else {
3068 toolMajor = 0;
3069 }
3070 toolMinor = toolMajor;
3071 break;
3072 default:
3073 toolMajor = 0;
3074 toolMinor = 0;
3075 break;
3076 }
3077
3078 if (mCalibration.haveToolSizeIsSummed && mCalibration.toolSizeIsSummed) {
3079 toolMajor /= currentPointerCount;
3080 toolMinor /= currentPointerCount;
3081 }
3082
3083 // Pressure
3084 float rawPressure;
3085 switch (mCalibration.pressureSource) {
3086 case Calibration::PRESSURE_SOURCE_PRESSURE:
3087 rawPressure = in.pressure;
3088 break;
3089 case Calibration::PRESSURE_SOURCE_TOUCH:
3090 rawPressure = in.touchMajor;
3091 break;
3092 default:
3093 rawPressure = 0;
3094 }
3095
3096 float pressure;
3097 switch (mCalibration.pressureCalibration) {
3098 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3099 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3100 pressure = rawPressure * mLocked.pressureScale;
3101 break;
3102 default:
3103 pressure = 1;
3104 break;
3105 }
3106
3107 // TouchMajor and TouchMinor
3108 float touchMajor, touchMinor;
3109 switch (mCalibration.touchSizeCalibration) {
3110 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
3111 touchMajor = in.touchMajor * mLocked.geometricScale;
3112 if (mRawAxes.touchMinor.valid) {
3113 touchMinor = in.touchMinor * mLocked.geometricScale;
3114 } else {
3115 touchMinor = touchMajor;
3116 }
3117 break;
3118 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
3119 touchMajor = toolMajor * pressure;
3120 touchMinor = toolMinor * pressure;
3121 break;
3122 default:
3123 touchMajor = 0;
3124 touchMinor = 0;
3125 break;
3126 }
3127
3128 if (touchMajor > toolMajor) {
3129 touchMajor = toolMajor;
3130 }
3131 if (touchMinor > toolMinor) {
3132 touchMinor = toolMinor;
3133 }
3134
3135 // Size
3136 float size;
3137 switch (mCalibration.sizeCalibration) {
3138 case Calibration::SIZE_CALIBRATION_NORMALIZED: {
3139 float rawSize = mRawAxes.toolMinor.valid
3140 ? avg(in.toolMajor, in.toolMinor)
3141 : in.toolMajor;
3142 size = rawSize * mLocked.sizeScale;
3143 break;
3144 }
3145 default:
3146 size = 0;
3147 break;
3148 }
3149
3150 // Orientation
3151 float orientation;
3152 switch (mCalibration.orientationCalibration) {
3153 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3154 orientation = in.orientation * mLocked.orientationScale;
3155 break;
3156 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
3157 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
3158 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
3159 if (c1 != 0 || c2 != 0) {
3160 orientation = atan2f(c1, c2) * 0.5f;
Jeff Brown2352b972011-04-12 22:39:53 -07003161 float scale = 1.0f + hypotf(c1, c2) / 16.0f;
Jeff Brownace13b12011-03-09 17:39:48 -08003162 touchMajor *= scale;
3163 touchMinor /= scale;
3164 toolMajor *= scale;
3165 toolMinor /= scale;
3166 } else {
3167 orientation = 0;
3168 }
3169 break;
3170 }
3171 default:
3172 orientation = 0;
3173 }
3174
3175 // X and Y
3176 // Adjust coords for surface orientation.
3177 float x, y;
3178 switch (mLocked.surfaceOrientation) {
3179 case DISPLAY_ORIENTATION_90:
3180 x = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3181 y = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3182 orientation -= M_PI_2;
3183 if (orientation < - M_PI_2) {
3184 orientation += M_PI;
3185 }
3186 break;
3187 case DISPLAY_ORIENTATION_180:
3188 x = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3189 y = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3190 break;
3191 case DISPLAY_ORIENTATION_270:
3192 x = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3193 y = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3194 orientation += M_PI_2;
3195 if (orientation > M_PI_2) {
3196 orientation -= M_PI;
3197 }
3198 break;
3199 default:
3200 x = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3201 y = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3202 break;
3203 }
3204
3205 // Write output coords.
3206 PointerCoords& out = mCurrentTouchCoords[i];
3207 out.clear();
3208 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3209 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3210 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
3211 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
3212 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
3213 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
3214 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
3215 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
3216 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
3217 }
3218
3219 // Check edge flags by looking only at the first pointer since the flags are
3220 // global to the event.
3221 *outEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3222 if (lastPointerCount == 0 && currentPointerCount > 0) {
3223 const PointerData& in = mCurrentTouch.pointers[0];
3224
3225 if (in.x <= mRawAxes.x.minValue) {
3226 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_LEFT,
3227 mLocked.surfaceOrientation);
3228 } else if (in.x >= mRawAxes.x.maxValue) {
3229 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_RIGHT,
3230 mLocked.surfaceOrientation);
3231 }
3232 if (in.y <= mRawAxes.y.minValue) {
3233 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_TOP,
3234 mLocked.surfaceOrientation);
3235 } else if (in.y >= mRawAxes.y.maxValue) {
3236 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_BOTTOM,
3237 mLocked.surfaceOrientation);
3238 }
3239 }
3240
3241 *outXPrecision = mLocked.orientedXPrecision;
3242 *outYPrecision = mLocked.orientedYPrecision;
3243}
3244
Jeff Brown79ac9692011-04-19 21:20:10 -07003245void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
3246 bool isTimeout) {
Jeff Brown2352b972011-04-12 22:39:53 -07003247 // Switch pointer presentation.
3248 mPointerController->setPresentation(
3249 mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
3250 ? PointerControllerInterface::PRESENTATION_SPOT
3251 : PointerControllerInterface::PRESENTATION_POINTER);
3252
Jeff Brownace13b12011-03-09 17:39:48 -08003253 // Update current gesture coordinates.
3254 bool cancelPreviousGesture, finishPreviousGesture;
Jeff Brown79ac9692011-04-19 21:20:10 -07003255 bool sendEvents = preparePointerGestures(when,
3256 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
3257 if (!sendEvents) {
3258 return;
3259 }
Jeff Brownace13b12011-03-09 17:39:48 -08003260
Jeff Brown2352b972011-04-12 22:39:53 -07003261 // Show the pointer if needed.
3262 if (mPointerGesture.currentGestureMode != PointerGesture::NEUTRAL
3263 && mPointerGesture.currentGestureMode != PointerGesture::QUIET) {
3264 mPointerController->unfade();
3265 }
3266
Jeff Brownace13b12011-03-09 17:39:48 -08003267 // Send events!
3268 uint32_t metaState = getContext()->getGlobalMetaState();
3269
3270 // Update last coordinates of pointers that have moved so that we observe the new
3271 // pointer positions at the same time as other pointers that have just gone up.
Jeff Brown79ac9692011-04-19 21:20:10 -07003272 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
3273 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
3274 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
Jeff Brown2352b972011-04-12 22:39:53 -07003275 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
Jeff Brownace13b12011-03-09 17:39:48 -08003276 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
3277 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
3278 bool moveNeeded = false;
3279 if (down && !cancelPreviousGesture && !finishPreviousGesture
Jeff Brown2352b972011-04-12 22:39:53 -07003280 && !mPointerGesture.lastGestureIdBits.isEmpty()
3281 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
Jeff Brownace13b12011-03-09 17:39:48 -08003282 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
3283 & mPointerGesture.lastGestureIdBits.value);
3284 moveNeeded = updateMovedPointerCoords(
3285 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3286 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3287 movedGestureIdBits);
3288 }
3289
3290 // Send motion events for all pointers that went up or were canceled.
3291 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
3292 if (!dispatchedGestureIdBits.isEmpty()) {
3293 if (cancelPreviousGesture) {
3294 dispatchMotion(when, policyFlags, mPointerSource,
3295 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3296 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3297 dispatchedGestureIdBits, -1,
3298 0, 0, mPointerGesture.downTime);
3299
3300 dispatchedGestureIdBits.clear();
3301 } else {
3302 BitSet32 upGestureIdBits;
3303 if (finishPreviousGesture) {
3304 upGestureIdBits = dispatchedGestureIdBits;
3305 } else {
3306 upGestureIdBits.value = dispatchedGestureIdBits.value
3307 & ~mPointerGesture.currentGestureIdBits.value;
3308 }
3309 while (!upGestureIdBits.isEmpty()) {
3310 uint32_t id = upGestureIdBits.firstMarkedBit();
3311 upGestureIdBits.clearBit(id);
3312
3313 dispatchMotion(when, policyFlags, mPointerSource,
3314 AMOTION_EVENT_ACTION_POINTER_UP, 0,
3315 metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3316 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3317 dispatchedGestureIdBits, id,
3318 0, 0, mPointerGesture.downTime);
3319
3320 dispatchedGestureIdBits.clearBit(id);
3321 }
3322 }
3323 }
3324
3325 // Send motion events for all pointers that moved.
3326 if (moveNeeded) {
3327 dispatchMotion(when, policyFlags, mPointerSource,
3328 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3329 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3330 dispatchedGestureIdBits, -1,
3331 0, 0, mPointerGesture.downTime);
3332 }
3333
3334 // Send motion events for all pointers that went down.
3335 if (down) {
3336 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
3337 & ~dispatchedGestureIdBits.value);
3338 while (!downGestureIdBits.isEmpty()) {
3339 uint32_t id = downGestureIdBits.firstMarkedBit();
3340 downGestureIdBits.clearBit(id);
3341 dispatchedGestureIdBits.markBit(id);
3342
3343 int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3344 if (dispatchedGestureIdBits.count() == 1) {
3345 // First pointer is going down. Calculate edge flags and set down time.
3346 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3347 const PointerCoords& downCoords = mPointerGesture.currentGestureCoords[index];
3348 edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3349 downCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
3350 downCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3351 mPointerGesture.downTime = when;
3352 }
3353
3354 dispatchMotion(when, policyFlags, mPointerSource,
3355 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
3356 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3357 dispatchedGestureIdBits, id,
3358 0, 0, mPointerGesture.downTime);
3359 }
3360 }
3361
Jeff Brownace13b12011-03-09 17:39:48 -08003362 // Send motion events for hover.
3363 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
3364 dispatchMotion(when, policyFlags, mPointerSource,
3365 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3366 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3367 mPointerGesture.currentGestureIdBits, -1,
3368 0, 0, mPointerGesture.downTime);
3369 }
3370
3371 // Update state.
3372 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
3373 if (!down) {
Jeff Brownace13b12011-03-09 17:39:48 -08003374 mPointerGesture.lastGestureIdBits.clear();
3375 } else {
Jeff Brownace13b12011-03-09 17:39:48 -08003376 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
3377 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
3378 uint32_t id = idBits.firstMarkedBit();
3379 idBits.clearBit(id);
3380 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3381 mPointerGesture.lastGestureCoords[index].copyFrom(
3382 mPointerGesture.currentGestureCoords[index]);
3383 mPointerGesture.lastGestureIdToIndex[id] = index;
Jeff Brown46b9ac02010-04-22 18:58:52 -07003384 }
3385 }
3386}
3387
Jeff Brown79ac9692011-04-19 21:20:10 -07003388bool TouchInputMapper::preparePointerGestures(nsecs_t when,
3389 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
Jeff Brownace13b12011-03-09 17:39:48 -08003390 *outCancelPreviousGesture = false;
3391 *outFinishPreviousGesture = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003392
Jeff Brownace13b12011-03-09 17:39:48 -08003393 AutoMutex _l(mLock);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003394
Jeff Brown79ac9692011-04-19 21:20:10 -07003395 // Handle TAP timeout.
3396 if (isTimeout) {
3397#if DEBUG_GESTURES
3398 LOGD("Gestures: Processing timeout");
3399#endif
3400
3401 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
3402 if (when <= mPointerGesture.tapUpTime + TAP_DRAG_INTERVAL) {
3403 // The tap/drag timeout has not yet expired.
3404 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime + TAP_DRAG_INTERVAL);
3405 } else {
3406 // The tap is finished.
3407#if DEBUG_GESTURES
3408 LOGD("Gestures: TAP finished");
3409#endif
3410 *outFinishPreviousGesture = true;
3411
3412 mPointerGesture.activeGestureId = -1;
3413 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
3414 mPointerGesture.currentGestureIdBits.clear();
3415
3416 mPointerController->setButtonState(0);
3417
3418 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3419 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_NEUTRAL;
3420 mPointerGesture.spotIdBits.clear();
3421 moveSpotsLocked();
3422 }
3423 return true;
3424 }
3425 }
3426
3427 // We did not handle this timeout.
3428 return false;
3429 }
3430
Jeff Brownace13b12011-03-09 17:39:48 -08003431 // Update the velocity tracker.
3432 {
3433 VelocityTracker::Position positions[MAX_POINTERS];
3434 uint32_t count = 0;
3435 for (BitSet32 idBits(mCurrentTouch.idBits); !idBits.isEmpty(); count++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07003436 uint32_t id = idBits.firstMarkedBit();
3437 idBits.clearBit(id);
Jeff Brownace13b12011-03-09 17:39:48 -08003438 uint32_t index = mCurrentTouch.idToIndex[id];
3439 positions[count].x = mCurrentTouch.pointers[index].x
3440 * mLocked.pointerGestureXMovementScale;
3441 positions[count].y = mCurrentTouch.pointers[index].y
3442 * mLocked.pointerGestureYMovementScale;
3443 }
3444 mPointerGesture.velocityTracker.addMovement(when, mCurrentTouch.idBits, positions);
3445 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003446
Jeff Brownace13b12011-03-09 17:39:48 -08003447 // Pick a new active touch id if needed.
3448 // Choose an arbitrary pointer that just went down, if there is one.
3449 // Otherwise choose an arbitrary remaining pointer.
3450 // This guarantees we always have an active touch id when there is at least one pointer.
Jeff Brown2352b972011-04-12 22:39:53 -07003451 // We keep the same active touch id for as long as possible.
3452 bool activeTouchChanged = false;
3453 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
3454 int32_t activeTouchId = lastActiveTouchId;
3455 if (activeTouchId < 0) {
3456 if (!mCurrentTouch.idBits.isEmpty()) {
3457 activeTouchChanged = true;
3458 activeTouchId = mPointerGesture.activeTouchId = mCurrentTouch.idBits.firstMarkedBit();
3459 mPointerGesture.firstTouchTime = when;
Jeff Brownace13b12011-03-09 17:39:48 -08003460 }
Jeff Brown2352b972011-04-12 22:39:53 -07003461 } else if (!mCurrentTouch.idBits.hasBit(activeTouchId)) {
3462 activeTouchChanged = true;
3463 if (!mCurrentTouch.idBits.isEmpty()) {
3464 activeTouchId = mPointerGesture.activeTouchId = mCurrentTouch.idBits.firstMarkedBit();
3465 } else {
3466 activeTouchId = mPointerGesture.activeTouchId = -1;
Jeff Brownace13b12011-03-09 17:39:48 -08003467 }
3468 }
3469
3470 // Determine whether we are in quiet time.
Jeff Brown2352b972011-04-12 22:39:53 -07003471 bool isQuietTime = false;
3472 if (activeTouchId < 0) {
3473 mPointerGesture.resetQuietTime();
3474 } else {
3475 isQuietTime = when < mPointerGesture.quietTime + QUIET_INTERVAL;
3476 if (!isQuietTime) {
3477 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
3478 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
3479 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
3480 && mCurrentTouch.pointerCount < 2) {
3481 // Enter quiet time when exiting swipe or freeform state.
3482 // This is to prevent accidentally entering the hover state and flinging the
3483 // pointer when finishing a swipe and there is still one pointer left onscreen.
3484 isQuietTime = true;
Jeff Brown79ac9692011-04-19 21:20:10 -07003485 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
Jeff Brown2352b972011-04-12 22:39:53 -07003486 && mCurrentTouch.pointerCount >= 2
3487 && !isPointerDown(mCurrentTouch.buttonState)) {
3488 // Enter quiet time when releasing the button and there are still two or more
3489 // fingers down. This may indicate that one finger was used to press the button
3490 // but it has not gone up yet.
3491 isQuietTime = true;
3492 }
3493 if (isQuietTime) {
3494 mPointerGesture.quietTime = when;
3495 }
Jeff Brownace13b12011-03-09 17:39:48 -08003496 }
3497 }
3498
3499 // Switch states based on button and pointer state.
3500 if (isQuietTime) {
3501 // Case 1: Quiet time. (QUIET)
3502#if DEBUG_GESTURES
3503 LOGD("Gestures: QUIET for next %0.3fms",
3504 (mPointerGesture.quietTime + QUIET_INTERVAL - when) * 0.000001f);
3505#endif
3506 *outFinishPreviousGesture = true;
3507
3508 mPointerGesture.activeGestureId = -1;
3509 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
Jeff Brownace13b12011-03-09 17:39:48 -08003510 mPointerGesture.currentGestureIdBits.clear();
Jeff Brown2352b972011-04-12 22:39:53 -07003511
3512 mPointerController->setButtonState(0);
3513
3514 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3515 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_NEUTRAL;
3516 mPointerGesture.spotIdBits.clear();
3517 moveSpotsLocked();
3518 }
Jeff Brownace13b12011-03-09 17:39:48 -08003519 } else if (isPointerDown(mCurrentTouch.buttonState)) {
Jeff Brown79ac9692011-04-19 21:20:10 -07003520 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
Jeff Brownace13b12011-03-09 17:39:48 -08003521 // The pointer follows the active touch point.
3522 // Emit DOWN, MOVE, UP events at the pointer location.
3523 //
3524 // Only the active touch matters; other fingers are ignored. This policy helps
3525 // to handle the case where the user places a second finger on the touch pad
3526 // to apply the necessary force to depress an integrated button below the surface.
3527 // We don't want the second finger to be delivered to applications.
3528 //
3529 // For this to work well, we need to make sure to track the pointer that is really
3530 // active. If the user first puts one finger down to click then adds another
3531 // finger to drag then the active pointer should switch to the finger that is
3532 // being dragged.
3533#if DEBUG_GESTURES
Jeff Brown79ac9692011-04-19 21:20:10 -07003534 LOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
Jeff Brownace13b12011-03-09 17:39:48 -08003535 "currentTouchPointerCount=%d", activeTouchId, mCurrentTouch.pointerCount);
3536#endif
3537 // Reset state when just starting.
Jeff Brown79ac9692011-04-19 21:20:10 -07003538 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
Jeff Brownace13b12011-03-09 17:39:48 -08003539 *outFinishPreviousGesture = true;
3540 mPointerGesture.activeGestureId = 0;
3541 }
3542
3543 // Switch pointers if needed.
3544 // Find the fastest pointer and follow it.
3545 if (activeTouchId >= 0) {
3546 if (mCurrentTouch.pointerCount > 1) {
3547 int32_t bestId = -1;
3548 float bestSpeed = DRAG_MIN_SWITCH_SPEED;
3549 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3550 uint32_t id = mCurrentTouch.pointers[i].id;
3551 float vx, vy;
3552 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
Jeff Brown2352b972011-04-12 22:39:53 -07003553 float speed = hypotf(vx, vy);
Jeff Brownace13b12011-03-09 17:39:48 -08003554 if (speed > bestSpeed) {
3555 bestId = id;
3556 bestSpeed = speed;
3557 }
3558 }
Jeff Brown8d608662010-08-30 03:02:23 -07003559 }
Jeff Brownace13b12011-03-09 17:39:48 -08003560 if (bestId >= 0 && bestId != activeTouchId) {
3561 mPointerGesture.activeTouchId = activeTouchId = bestId;
Jeff Brown2352b972011-04-12 22:39:53 -07003562 activeTouchChanged = true;
Jeff Brownace13b12011-03-09 17:39:48 -08003563#if DEBUG_GESTURES
Jeff Brown79ac9692011-04-19 21:20:10 -07003564 LOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
Jeff Brownace13b12011-03-09 17:39:48 -08003565 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
3566#endif
Jeff Brown8d608662010-08-30 03:02:23 -07003567 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003568 }
3569
Jeff Brownace13b12011-03-09 17:39:48 -08003570 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3571 const PointerData& currentPointer =
3572 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3573 const PointerData& lastPointer =
3574 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3575 float deltaX = (currentPointer.x - lastPointer.x)
3576 * mLocked.pointerGestureXMovementScale;
3577 float deltaY = (currentPointer.y - lastPointer.y)
3578 * mLocked.pointerGestureYMovementScale;
Jeff Brown2352b972011-04-12 22:39:53 -07003579
3580 // Move the pointer using a relative motion.
3581 // When using spots, the click will occur at the position of the anchor
3582 // spot and all other spots will move there.
Jeff Brownace13b12011-03-09 17:39:48 -08003583 mPointerController->move(deltaX, deltaY);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003584 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003585 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003586
Jeff Brownace13b12011-03-09 17:39:48 -08003587 float x, y;
3588 mPointerController->getPosition(&x, &y);
Jeff Brown91c69ab2011-02-14 17:03:18 -08003589
Jeff Brown79ac9692011-04-19 21:20:10 -07003590 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
Jeff Brownace13b12011-03-09 17:39:48 -08003591 mPointerGesture.currentGestureIdBits.clear();
3592 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3593 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3594 mPointerGesture.currentGestureCoords[0].clear();
3595 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3596 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3597 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown2352b972011-04-12 22:39:53 -07003598
3599 mPointerController->setButtonState(BUTTON_STATE_PRIMARY);
3600
3601 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3602 if (activeTouchId >= 0) {
3603 // Collapse all spots into one point at the pointer location.
3604 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_BUTTON_DRAG;
3605 mPointerGesture.spotIdBits.clear();
3606 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3607 uint32_t id = mCurrentTouch.pointers[i].id;
3608 mPointerGesture.spotIdBits.markBit(id);
3609 mPointerGesture.spotIdToIndex[id] = i;
3610 mPointerGesture.spotCoords[i] = mPointerGesture.currentGestureCoords[0];
3611 }
3612 } else {
3613 // No fingers. Generate a spot at the pointer location so the
3614 // anchor appears to be pressed.
3615 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_BUTTON_CLICK;
3616 mPointerGesture.spotIdBits.clear();
3617 mPointerGesture.spotIdBits.markBit(0);
3618 mPointerGesture.spotIdToIndex[0] = 0;
3619 mPointerGesture.spotCoords[0] = mPointerGesture.currentGestureCoords[0];
3620 }
3621 moveSpotsLocked();
3622 }
Jeff Brownace13b12011-03-09 17:39:48 -08003623 } else if (mCurrentTouch.pointerCount == 0) {
3624 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
3625 *outFinishPreviousGesture = true;
3626
Jeff Brown79ac9692011-04-19 21:20:10 -07003627 // Watch for taps coming out of HOVER or TAP_DRAG mode.
Jeff Brownace13b12011-03-09 17:39:48 -08003628 bool tapped = false;
Jeff Brown79ac9692011-04-19 21:20:10 -07003629 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
3630 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
Jeff Brown2352b972011-04-12 22:39:53 -07003631 && mLastTouch.pointerCount == 1) {
Jeff Brown79ac9692011-04-19 21:20:10 -07003632 if (when <= mPointerGesture.tapDownTime + TAP_INTERVAL) {
Jeff Brownace13b12011-03-09 17:39:48 -08003633 float x, y;
3634 mPointerController->getPosition(&x, &y);
Jeff Brown2352b972011-04-12 22:39:53 -07003635 if (fabs(x - mPointerGesture.tapX) <= TAP_SLOP
3636 && fabs(y - mPointerGesture.tapY) <= TAP_SLOP) {
Jeff Brownace13b12011-03-09 17:39:48 -08003637#if DEBUG_GESTURES
3638 LOGD("Gestures: TAP");
3639#endif
Jeff Brown79ac9692011-04-19 21:20:10 -07003640
3641 mPointerGesture.tapUpTime = when;
3642 getContext()->requestTimeoutAtTime(when + TAP_DRAG_INTERVAL);
3643
Jeff Brownace13b12011-03-09 17:39:48 -08003644 mPointerGesture.activeGestureId = 0;
3645 mPointerGesture.currentGestureMode = PointerGesture::TAP;
Jeff Brownace13b12011-03-09 17:39:48 -08003646 mPointerGesture.currentGestureIdBits.clear();
3647 mPointerGesture.currentGestureIdBits.markBit(
3648 mPointerGesture.activeGestureId);
3649 mPointerGesture.currentGestureIdToIndex[
3650 mPointerGesture.activeGestureId] = 0;
3651 mPointerGesture.currentGestureCoords[0].clear();
3652 mPointerGesture.currentGestureCoords[0].setAxisValue(
Jeff Brown2352b972011-04-12 22:39:53 -07003653 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
Jeff Brownace13b12011-03-09 17:39:48 -08003654 mPointerGesture.currentGestureCoords[0].setAxisValue(
Jeff Brown2352b972011-04-12 22:39:53 -07003655 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
Jeff Brownace13b12011-03-09 17:39:48 -08003656 mPointerGesture.currentGestureCoords[0].setAxisValue(
3657 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown2352b972011-04-12 22:39:53 -07003658
3659 mPointerController->setButtonState(BUTTON_STATE_PRIMARY);
Jeff Brown2352b972011-04-12 22:39:53 -07003660
3661 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3662 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_TAP;
3663 mPointerGesture.spotIdBits.clear();
3664 mPointerGesture.spotIdBits.markBit(lastActiveTouchId);
3665 mPointerGesture.spotIdToIndex[lastActiveTouchId] = 0;
3666 mPointerGesture.spotCoords[0] = mPointerGesture.currentGestureCoords[0];
3667 moveSpotsLocked();
3668 }
3669
Jeff Brownace13b12011-03-09 17:39:48 -08003670 tapped = true;
3671 } else {
3672#if DEBUG_GESTURES
3673 LOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
Jeff Brown2352b972011-04-12 22:39:53 -07003674 x - mPointerGesture.tapX,
3675 y - mPointerGesture.tapY);
Jeff Brownace13b12011-03-09 17:39:48 -08003676#endif
3677 }
3678 } else {
3679#if DEBUG_GESTURES
Jeff Brown79ac9692011-04-19 21:20:10 -07003680 LOGD("Gestures: Not a TAP, %0.3fms since down",
3681 (when - mPointerGesture.tapDownTime) * 0.000001f);
Jeff Brownace13b12011-03-09 17:39:48 -08003682#endif
Jeff Brown6328cdc2010-07-29 18:18:33 -07003683 }
Jeff Brownace13b12011-03-09 17:39:48 -08003684 }
Jeff Brown2352b972011-04-12 22:39:53 -07003685
Jeff Brownace13b12011-03-09 17:39:48 -08003686 if (!tapped) {
3687#if DEBUG_GESTURES
3688 LOGD("Gestures: NEUTRAL");
3689#endif
3690 mPointerGesture.activeGestureId = -1;
3691 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
Jeff Brownace13b12011-03-09 17:39:48 -08003692 mPointerGesture.currentGestureIdBits.clear();
Jeff Brown2352b972011-04-12 22:39:53 -07003693
3694 mPointerController->setButtonState(0);
3695
3696 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3697 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_NEUTRAL;
3698 mPointerGesture.spotIdBits.clear();
3699 moveSpotsLocked();
3700 }
Jeff Brownace13b12011-03-09 17:39:48 -08003701 }
3702 } else if (mCurrentTouch.pointerCount == 1) {
Jeff Brown79ac9692011-04-19 21:20:10 -07003703 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
Jeff Brownace13b12011-03-09 17:39:48 -08003704 // The pointer follows the active touch point.
Jeff Brown79ac9692011-04-19 21:20:10 -07003705 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3706 // When in TAP_DRAG, emit MOVE events at the pointer location.
Jeff Brownb6110c22011-04-01 16:15:13 -07003707 LOG_ASSERT(activeTouchId >= 0);
Jeff Brownace13b12011-03-09 17:39:48 -08003708
Jeff Brown79ac9692011-04-19 21:20:10 -07003709 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
3710 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
3711 if (when <= mPointerGesture.tapUpTime + TAP_DRAG_INTERVAL) {
3712 float x, y;
3713 mPointerController->getPosition(&x, &y);
3714 if (fabs(x - mPointerGesture.tapX) <= TAP_SLOP
3715 && fabs(y - mPointerGesture.tapY) <= TAP_SLOP) {
3716 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
3717 } else {
Jeff Brownace13b12011-03-09 17:39:48 -08003718#if DEBUG_GESTURES
Jeff Brown79ac9692011-04-19 21:20:10 -07003719 LOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3720 x - mPointerGesture.tapX,
3721 y - mPointerGesture.tapY);
Jeff Brownace13b12011-03-09 17:39:48 -08003722#endif
Jeff Brown79ac9692011-04-19 21:20:10 -07003723 }
3724 } else {
3725#if DEBUG_GESTURES
3726 LOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
3727 (when - mPointerGesture.tapUpTime) * 0.000001f);
3728#endif
3729 }
3730 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
3731 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
3732 }
Jeff Brownace13b12011-03-09 17:39:48 -08003733
3734 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3735 const PointerData& currentPointer =
3736 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3737 const PointerData& lastPointer =
3738 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3739 float deltaX = (currentPointer.x - lastPointer.x)
3740 * mLocked.pointerGestureXMovementScale;
3741 float deltaY = (currentPointer.y - lastPointer.y)
3742 * mLocked.pointerGestureYMovementScale;
Jeff Brown2352b972011-04-12 22:39:53 -07003743
3744 // Move the pointer using a relative motion.
Jeff Brown79ac9692011-04-19 21:20:10 -07003745 // When using spots, the hover or drag will occur at the position of the anchor spot.
Jeff Brownace13b12011-03-09 17:39:48 -08003746 mPointerController->move(deltaX, deltaY);
3747 }
3748
Jeff Brown79ac9692011-04-19 21:20:10 -07003749 bool down;
3750 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
3751#if DEBUG_GESTURES
3752 LOGD("Gestures: TAP_DRAG");
3753#endif
3754 down = true;
3755 } else {
3756#if DEBUG_GESTURES
3757 LOGD("Gestures: HOVER");
3758#endif
3759 *outFinishPreviousGesture = true;
3760 mPointerGesture.activeGestureId = 0;
3761 down = false;
3762 }
Jeff Brownace13b12011-03-09 17:39:48 -08003763
3764 float x, y;
3765 mPointerController->getPosition(&x, &y);
3766
Jeff Brownace13b12011-03-09 17:39:48 -08003767 mPointerGesture.currentGestureIdBits.clear();
3768 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3769 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3770 mPointerGesture.currentGestureCoords[0].clear();
3771 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3772 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jeff Brown79ac9692011-04-19 21:20:10 -07003773 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3774 down ? 1.0f : 0.0f);
3775
3776 mPointerController->setButtonState(down ? BUTTON_STATE_PRIMARY : 0);
Jeff Brownace13b12011-03-09 17:39:48 -08003777
3778 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
Jeff Brown79ac9692011-04-19 21:20:10 -07003779 mPointerGesture.resetTap();
3780 mPointerGesture.tapDownTime = when;
Jeff Brown2352b972011-04-12 22:39:53 -07003781 mPointerGesture.tapX = x;
3782 mPointerGesture.tapY = y;
3783 }
3784
Jeff Brown2352b972011-04-12 22:39:53 -07003785 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
Jeff Brown79ac9692011-04-19 21:20:10 -07003786 mPointerGesture.spotGesture = down ? PointerControllerInterface::SPOT_GESTURE_DRAG
3787 : PointerControllerInterface::SPOT_GESTURE_HOVER;
Jeff Brown2352b972011-04-12 22:39:53 -07003788 mPointerGesture.spotIdBits.clear();
3789 mPointerGesture.spotIdBits.markBit(activeTouchId);
3790 mPointerGesture.spotIdToIndex[activeTouchId] = 0;
3791 mPointerGesture.spotCoords[0] = mPointerGesture.currentGestureCoords[0];
3792 moveSpotsLocked();
Jeff Brownace13b12011-03-09 17:39:48 -08003793 }
3794 } else {
Jeff Brown2352b972011-04-12 22:39:53 -07003795 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3796 // We need to provide feedback for each finger that goes down so we cannot wait
3797 // for the fingers to move before deciding what to do.
Jeff Brownace13b12011-03-09 17:39:48 -08003798 //
Jeff Brown2352b972011-04-12 22:39:53 -07003799 // The ambiguous case is deciding what to do when there are two fingers down but they
3800 // have not moved enough to determine whether they are part of a drag or part of a
3801 // freeform gesture, or just a press or long-press at the pointer location.
3802 //
3803 // When there are two fingers we start with the PRESS hypothesis and we generate a
3804 // down at the pointer location.
3805 //
3806 // When the two fingers move enough or when additional fingers are added, we make
3807 // a decision to transition into SWIPE or FREEFORM mode accordingly.
Jeff Brownb6110c22011-04-01 16:15:13 -07003808 LOG_ASSERT(activeTouchId >= 0);
Jeff Brownace13b12011-03-09 17:39:48 -08003809
Jeff Brown2352b972011-04-12 22:39:53 -07003810 bool needReference = false;
3811 bool settled = when >= mPointerGesture.firstTouchTime + MULTITOUCH_SETTLE_INTERVAL;
3812 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
Jeff Brownace13b12011-03-09 17:39:48 -08003813 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
3814 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
Jeff Brownace13b12011-03-09 17:39:48 -08003815 *outFinishPreviousGesture = true;
Jeff Brown2352b972011-04-12 22:39:53 -07003816 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
3817 mPointerGesture.activeGestureId = 0;
Jeff Brownace13b12011-03-09 17:39:48 -08003818
Jeff Brown2352b972011-04-12 22:39:53 -07003819 if (settled && mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
3820 && mLastTouch.idBits.hasBit(mPointerGesture.activeTouchId)) {
3821 // The spot is already visible and has settled, use it as the reference point
3822 // for the gesture. Other spots will be positioned relative to this one.
3823#if DEBUG_GESTURES
3824 LOGD("Gestures: Using active spot as reference for MULTITOUCH, "
3825 "settle time expired %0.3fms ago",
3826 (when - mPointerGesture.firstTouchTime - MULTITOUCH_SETTLE_INTERVAL)
3827 * 0.000001f);
3828#endif
3829 const PointerData& d = mLastTouch.pointers[mLastTouch.idToIndex[
3830 mPointerGesture.activeTouchId]];
3831 mPointerGesture.referenceTouchX = d.x;
3832 mPointerGesture.referenceTouchY = d.y;
3833 const PointerCoords& c = mPointerGesture.spotCoords[mPointerGesture.spotIdToIndex[
3834 mPointerGesture.activeTouchId]];
3835 mPointerGesture.referenceGestureX = c.getAxisValue(AMOTION_EVENT_AXIS_X);
3836 mPointerGesture.referenceGestureY = c.getAxisValue(AMOTION_EVENT_AXIS_Y);
3837 } else {
3838#if DEBUG_GESTURES
3839 LOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3840 "settle time remaining %0.3fms",
3841 (mPointerGesture.firstTouchTime + MULTITOUCH_SETTLE_INTERVAL - when)
3842 * 0.000001f);
3843#endif
3844 needReference = true;
Jeff Brownace13b12011-03-09 17:39:48 -08003845 }
Jeff Brown2352b972011-04-12 22:39:53 -07003846 } else if (!settled && mCurrentTouch.pointerCount > mLastTouch.pointerCount) {
3847 // Additional pointers have gone down but not yet settled.
3848 // Reset the gesture.
3849#if DEBUG_GESTURES
3850 LOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3851 "settle time remaining %0.3fms",
3852 (mPointerGesture.firstTouchTime + MULTITOUCH_SETTLE_INTERVAL - when)
3853 * 0.000001f);
3854#endif
3855 *outCancelPreviousGesture = true;
3856 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
3857 mPointerGesture.activeGestureId = 0;
Jeff Brownace13b12011-03-09 17:39:48 -08003858 } else {
Jeff Brown2352b972011-04-12 22:39:53 -07003859 // Continue previous gesture.
Jeff Brownace13b12011-03-09 17:39:48 -08003860 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3861 }
3862
Jeff Brown2352b972011-04-12 22:39:53 -07003863 if (needReference) {
3864 // Use the centroid and pointer location as the reference points for the gesture.
3865 mCurrentTouch.getCentroid(&mPointerGesture.referenceTouchX,
3866 &mPointerGesture.referenceTouchY);
3867 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3868 &mPointerGesture.referenceGestureY);
3869 }
Jeff Brownace13b12011-03-09 17:39:48 -08003870
Jeff Brown2352b972011-04-12 22:39:53 -07003871 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
3872 float d;
3873 if (mCurrentTouch.pointerCount > 2) {
3874 // There are more than two pointers, switch to FREEFORM.
3875#if DEBUG_GESTURES
3876 LOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3877 mCurrentTouch.pointerCount);
3878#endif
3879 *outCancelPreviousGesture = true;
Jeff Brownace13b12011-03-09 17:39:48 -08003880 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown2352b972011-04-12 22:39:53 -07003881 } else if (((d = distance(
3882 mCurrentTouch.pointers[0].x, mCurrentTouch.pointers[0].y,
3883 mCurrentTouch.pointers[1].x, mCurrentTouch.pointers[1].y))
3884 > mLocked.pointerGestureMaxSwipeWidth)) {
3885 // There are two pointers but they are too far apart, switch to FREEFORM.
3886#if DEBUG_GESTURES
3887 LOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3888 d, mLocked.pointerGestureMaxSwipeWidth);
3889#endif
3890 *outCancelPreviousGesture = true;
3891 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
3892 } else {
3893 // There are two pointers. Wait for both pointers to start moving
3894 // before deciding whether this is a SWIPE or FREEFORM gesture.
3895 uint32_t id1 = mCurrentTouch.pointers[0].id;
3896 uint32_t id2 = mCurrentTouch.pointers[1].id;
Jeff Brownace13b12011-03-09 17:39:48 -08003897
Jeff Brown2352b972011-04-12 22:39:53 -07003898 float vx1, vy1, vx2, vy2;
3899 mPointerGesture.velocityTracker.getVelocity(id1, &vx1, &vy1);
3900 mPointerGesture.velocityTracker.getVelocity(id2, &vx2, &vy2);
Jeff Brownace13b12011-03-09 17:39:48 -08003901
Jeff Brown2352b972011-04-12 22:39:53 -07003902 float speed1 = hypotf(vx1, vy1);
3903 float speed2 = hypotf(vx2, vy2);
3904 if (speed1 >= MULTITOUCH_MIN_SPEED && speed2 >= MULTITOUCH_MIN_SPEED) {
3905 // Calculate the dot product of the velocity vectors.
Jeff Brownace13b12011-03-09 17:39:48 -08003906 // When the vectors are oriented in approximately the same direction,
3907 // the angle betweeen them is near zero and the cosine of the angle
3908 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
Jeff Brown2352b972011-04-12 22:39:53 -07003909 float dot = vx1 * vx2 + vy1 * vy2;
3910 float cosine = dot / (speed1 * speed2); // denominator always > 0
3911 if (cosine >= SWIPE_TRANSITION_ANGLE_COSINE) {
3912 // Pointers are moving in the same direction. Switch to SWIPE.
3913#if DEBUG_GESTURES
3914 LOGD("Gestures: PRESS transitioned to SWIPE, "
3915 "speed1 %0.3f >= %0.3f, speed2 %0.3f >= %0.3f, "
3916 "cosine %0.3f >= %0.3f",
3917 speed1, MULTITOUCH_MIN_SPEED, speed2, MULTITOUCH_MIN_SPEED,
3918 cosine, SWIPE_TRANSITION_ANGLE_COSINE);
3919#endif
Jeff Brownace13b12011-03-09 17:39:48 -08003920 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
Jeff Brown2352b972011-04-12 22:39:53 -07003921 } else {
3922 // Pointers are moving in different directions. Switch to FREEFORM.
3923#if DEBUG_GESTURES
3924 LOGD("Gestures: PRESS transitioned to FREEFORM, "
3925 "speed1 %0.3f >= %0.3f, speed2 %0.3f >= %0.3f, "
3926 "cosine %0.3f < %0.3f",
3927 speed1, MULTITOUCH_MIN_SPEED, speed2, MULTITOUCH_MIN_SPEED,
3928 cosine, SWIPE_TRANSITION_ANGLE_COSINE);
3929#endif
3930 *outCancelPreviousGesture = true;
3931 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brownace13b12011-03-09 17:39:48 -08003932 }
3933 }
Jeff Brownace13b12011-03-09 17:39:48 -08003934 }
3935 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
Jeff Brown2352b972011-04-12 22:39:53 -07003936 // Switch from SWIPE to FREEFORM if additional pointers go down.
3937 // Cancel previous gesture.
3938 if (mCurrentTouch.pointerCount > 2) {
3939#if DEBUG_GESTURES
3940 LOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3941 mCurrentTouch.pointerCount);
3942#endif
Jeff Brownace13b12011-03-09 17:39:48 -08003943 *outCancelPreviousGesture = true;
3944 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003945 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07003946 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003947
Jeff Brown2352b972011-04-12 22:39:53 -07003948 // Move the reference points based on the overall group motion of the fingers.
3949 // The objective is to calculate a vector delta that is common to the movement
3950 // of all fingers.
3951 BitSet32 commonIdBits(mLastTouch.idBits.value & mCurrentTouch.idBits.value);
3952 if (!commonIdBits.isEmpty()) {
3953 float commonDeltaX = 0, commonDeltaY = 0;
3954 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
3955 bool first = (idBits == commonIdBits);
3956 uint32_t id = idBits.firstMarkedBit();
3957 idBits.clearBit(id);
3958
3959 const PointerData& cpd = mCurrentTouch.pointers[mCurrentTouch.idToIndex[id]];
3960 const PointerData& lpd = mLastTouch.pointers[mLastTouch.idToIndex[id]];
3961 float deltaX = cpd.x - lpd.x;
3962 float deltaY = cpd.y - lpd.y;
3963
3964 if (first) {
3965 commonDeltaX = deltaX;
3966 commonDeltaY = deltaY;
3967 } else {
3968 commonDeltaX = calculateCommonVector(commonDeltaX, deltaX);
3969 commonDeltaY = calculateCommonVector(commonDeltaY, deltaY);
3970 }
3971 }
3972
3973 mPointerGesture.referenceTouchX += commonDeltaX;
3974 mPointerGesture.referenceTouchY += commonDeltaY;
3975 mPointerGesture.referenceGestureX +=
3976 commonDeltaX * mLocked.pointerGestureXMovementScale;
3977 mPointerGesture.referenceGestureY +=
3978 commonDeltaY * mLocked.pointerGestureYMovementScale;
3979 clampPositionUsingPointerBounds(mPointerController,
3980 &mPointerGesture.referenceGestureX,
3981 &mPointerGesture.referenceGestureY);
3982 }
3983
3984 // Report gestures.
3985 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
3986 // PRESS mode.
Jeff Brownace13b12011-03-09 17:39:48 -08003987#if DEBUG_GESTURES
Jeff Brown2352b972011-04-12 22:39:53 -07003988 LOGD("Gestures: PRESS activeTouchId=%d,"
Jeff Brownace13b12011-03-09 17:39:48 -08003989 "activeGestureId=%d, currentTouchPointerCount=%d",
Jeff Brown2352b972011-04-12 22:39:53 -07003990 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
Jeff Brownace13b12011-03-09 17:39:48 -08003991#endif
Jeff Brownb6110c22011-04-01 16:15:13 -07003992 LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
Jeff Brownace13b12011-03-09 17:39:48 -08003993
Jeff Brownace13b12011-03-09 17:39:48 -08003994 mPointerGesture.currentGestureIdBits.clear();
3995 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3996 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3997 mPointerGesture.currentGestureCoords[0].clear();
Jeff Brown2352b972011-04-12 22:39:53 -07003998 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3999 mPointerGesture.referenceGestureX);
4000 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
4001 mPointerGesture.referenceGestureY);
Jeff Brownace13b12011-03-09 17:39:48 -08004002 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown2352b972011-04-12 22:39:53 -07004003
4004 mPointerController->setButtonState(BUTTON_STATE_PRIMARY);
4005
4006 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4007 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_PRESS;
4008 }
4009 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
4010 // SWIPE mode.
4011#if DEBUG_GESTURES
4012 LOGD("Gestures: SWIPE activeTouchId=%d,"
4013 "activeGestureId=%d, currentTouchPointerCount=%d",
4014 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
4015#endif
4016 LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
4017
4018 mPointerGesture.currentGestureIdBits.clear();
4019 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
4020 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
4021 mPointerGesture.currentGestureCoords[0].clear();
4022 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4023 mPointerGesture.referenceGestureX);
4024 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
4025 mPointerGesture.referenceGestureY);
4026 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4027
4028 mPointerController->setButtonState(0); // touch is not actually following the pointer
4029
4030 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4031 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_SWIPE;
4032 }
Jeff Brownace13b12011-03-09 17:39:48 -08004033 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
4034 // FREEFORM mode.
4035#if DEBUG_GESTURES
4036 LOGD("Gestures: FREEFORM activeTouchId=%d,"
4037 "activeGestureId=%d, currentTouchPointerCount=%d",
Jeff Brown2352b972011-04-12 22:39:53 -07004038 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
Jeff Brownace13b12011-03-09 17:39:48 -08004039#endif
Jeff Brownb6110c22011-04-01 16:15:13 -07004040 LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
Jeff Brownace13b12011-03-09 17:39:48 -08004041
Jeff Brownace13b12011-03-09 17:39:48 -08004042 mPointerGesture.currentGestureIdBits.clear();
4043
4044 BitSet32 mappedTouchIdBits;
4045 BitSet32 usedGestureIdBits;
4046 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
4047 // Initially, assign the active gesture id to the active touch point
4048 // if there is one. No other touch id bits are mapped yet.
4049 if (!*outCancelPreviousGesture) {
4050 mappedTouchIdBits.markBit(activeTouchId);
4051 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
4052 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
4053 mPointerGesture.activeGestureId;
4054 } else {
4055 mPointerGesture.activeGestureId = -1;
4056 }
4057 } else {
4058 // Otherwise, assume we mapped all touches from the previous frame.
4059 // Reuse all mappings that are still applicable.
4060 mappedTouchIdBits.value = mLastTouch.idBits.value & mCurrentTouch.idBits.value;
4061 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
4062
4063 // Check whether we need to choose a new active gesture id because the
4064 // current went went up.
4065 for (BitSet32 upTouchIdBits(mLastTouch.idBits.value & ~mCurrentTouch.idBits.value);
4066 !upTouchIdBits.isEmpty(); ) {
4067 uint32_t upTouchId = upTouchIdBits.firstMarkedBit();
4068 upTouchIdBits.clearBit(upTouchId);
4069 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
4070 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
4071 mPointerGesture.activeGestureId = -1;
4072 break;
4073 }
4074 }
4075 }
4076
4077#if DEBUG_GESTURES
4078 LOGD("Gestures: FREEFORM follow up "
4079 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
4080 "activeGestureId=%d",
4081 mappedTouchIdBits.value, usedGestureIdBits.value,
4082 mPointerGesture.activeGestureId);
4083#endif
4084
Jeff Brown2352b972011-04-12 22:39:53 -07004085 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
Jeff Brownace13b12011-03-09 17:39:48 -08004086 uint32_t touchId = mCurrentTouch.pointers[i].id;
4087 uint32_t gestureId;
4088 if (!mappedTouchIdBits.hasBit(touchId)) {
4089 gestureId = usedGestureIdBits.firstUnmarkedBit();
4090 usedGestureIdBits.markBit(gestureId);
4091 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
4092#if DEBUG_GESTURES
4093 LOGD("Gestures: FREEFORM "
4094 "new mapping for touch id %d -> gesture id %d",
4095 touchId, gestureId);
4096#endif
4097 } else {
4098 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
4099#if DEBUG_GESTURES
4100 LOGD("Gestures: FREEFORM "
4101 "existing mapping for touch id %d -> gesture id %d",
4102 touchId, gestureId);
4103#endif
4104 }
4105 mPointerGesture.currentGestureIdBits.markBit(gestureId);
4106 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
4107
Jeff Brown2352b972011-04-12 22:39:53 -07004108 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.referenceTouchX)
4109 * mLocked.pointerGestureXZoomScale + mPointerGesture.referenceGestureX;
4110 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.referenceTouchY)
4111 * mLocked.pointerGestureYZoomScale + mPointerGesture.referenceGestureY;
Jeff Brownace13b12011-03-09 17:39:48 -08004112
4113 mPointerGesture.currentGestureCoords[i].clear();
4114 mPointerGesture.currentGestureCoords[i].setAxisValue(
4115 AMOTION_EVENT_AXIS_X, x);
4116 mPointerGesture.currentGestureCoords[i].setAxisValue(
4117 AMOTION_EVENT_AXIS_Y, y);
4118 mPointerGesture.currentGestureCoords[i].setAxisValue(
4119 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4120 }
4121
4122 if (mPointerGesture.activeGestureId < 0) {
4123 mPointerGesture.activeGestureId =
4124 mPointerGesture.currentGestureIdBits.firstMarkedBit();
4125#if DEBUG_GESTURES
4126 LOGD("Gestures: FREEFORM new "
4127 "activeGestureId=%d", mPointerGesture.activeGestureId);
4128#endif
4129 }
Jeff Brownace13b12011-03-09 17:39:48 -08004130
Jeff Brown2352b972011-04-12 22:39:53 -07004131 mPointerController->setButtonState(0); // touch is not actually following the pointer
4132
4133 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4134 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_FREEFORM;
4135 }
4136 }
4137
4138 // Update spot locations for PRESS, SWIPE and FREEFORM.
4139 // We use the same calculation as we do to calculate the gesture pointers
4140 // for FREEFORM so that the spots smoothly track gestures.
4141 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4142 mPointerGesture.spotIdBits.clear();
4143 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
4144 uint32_t id = mCurrentTouch.pointers[i].id;
4145 mPointerGesture.spotIdBits.markBit(id);
4146 mPointerGesture.spotIdToIndex[id] = i;
4147
4148 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.referenceTouchX)
4149 * mLocked.pointerGestureXZoomScale + mPointerGesture.referenceGestureX;
4150 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.referenceTouchY)
4151 * mLocked.pointerGestureYZoomScale + mPointerGesture.referenceGestureY;
4152
4153 mPointerGesture.spotCoords[i].clear();
4154 mPointerGesture.spotCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4155 mPointerGesture.spotCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4156 mPointerGesture.spotCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4157 }
4158 moveSpotsLocked();
4159 }
Jeff Brownace13b12011-03-09 17:39:48 -08004160 }
4161
4162#if DEBUG_GESTURES
4163 LOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
Jeff Brown2352b972011-04-12 22:39:53 -07004164 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
4165 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
Jeff Brownace13b12011-03-09 17:39:48 -08004166 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
Jeff Brown2352b972011-04-12 22:39:53 -07004167 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
4168 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
Jeff Brownace13b12011-03-09 17:39:48 -08004169 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
4170 uint32_t id = idBits.firstMarkedBit();
4171 idBits.clearBit(id);
4172 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
4173 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
4174 LOGD(" currentGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
4175 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
4176 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
4177 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
4178 }
4179 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
4180 uint32_t id = idBits.firstMarkedBit();
4181 idBits.clearBit(id);
4182 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
4183 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
4184 LOGD(" lastGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
4185 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
4186 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
4187 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
4188 }
4189#endif
Jeff Brown79ac9692011-04-19 21:20:10 -07004190 return true;
Jeff Brownace13b12011-03-09 17:39:48 -08004191}
4192
Jeff Brown2352b972011-04-12 22:39:53 -07004193void TouchInputMapper::moveSpotsLocked() {
4194 mPointerController->setSpots(mPointerGesture.spotGesture,
4195 mPointerGesture.spotCoords, mPointerGesture.spotIdToIndex, mPointerGesture.spotIdBits);
4196}
4197
Jeff Brownace13b12011-03-09 17:39:48 -08004198void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
4199 int32_t action, int32_t flags, uint32_t metaState, int32_t edgeFlags,
4200 const PointerCoords* coords, const uint32_t* idToIndex, BitSet32 idBits,
4201 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
4202 PointerCoords pointerCoords[MAX_POINTERS];
4203 int32_t pointerIds[MAX_POINTERS];
4204 uint32_t pointerCount = 0;
4205 while (!idBits.isEmpty()) {
4206 uint32_t id = idBits.firstMarkedBit();
4207 idBits.clearBit(id);
4208 uint32_t index = idToIndex[id];
4209 pointerIds[pointerCount] = id;
4210 pointerCoords[pointerCount].copyFrom(coords[index]);
4211
4212 if (changedId >= 0 && id == uint32_t(changedId)) {
4213 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
4214 }
4215
4216 pointerCount += 1;
4217 }
4218
Jeff Brownb6110c22011-04-01 16:15:13 -07004219 LOG_ASSERT(pointerCount != 0);
Jeff Brownace13b12011-03-09 17:39:48 -08004220
4221 if (changedId >= 0 && pointerCount == 1) {
4222 // Replace initial down and final up action.
4223 // We can compare the action without masking off the changed pointer index
4224 // because we know the index is 0.
4225 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
4226 action = AMOTION_EVENT_ACTION_DOWN;
4227 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
4228 action = AMOTION_EVENT_ACTION_UP;
4229 } else {
4230 // Can't happen.
Jeff Brownb6110c22011-04-01 16:15:13 -07004231 LOG_ASSERT(false);
Jeff Brownace13b12011-03-09 17:39:48 -08004232 }
4233 }
4234
4235 getDispatcher()->notifyMotion(when, getDeviceId(), source, policyFlags,
4236 action, flags, metaState, edgeFlags,
4237 pointerCount, pointerIds, pointerCoords, xPrecision, yPrecision, downTime);
4238}
4239
4240bool TouchInputMapper::updateMovedPointerCoords(
4241 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
4242 PointerCoords* outCoords, const uint32_t* outIdToIndex, BitSet32 idBits) const {
4243 bool changed = false;
4244 while (!idBits.isEmpty()) {
4245 uint32_t id = idBits.firstMarkedBit();
4246 idBits.clearBit(id);
4247
4248 uint32_t inIndex = inIdToIndex[id];
4249 uint32_t outIndex = outIdToIndex[id];
4250 const PointerCoords& curInCoords = inCoords[inIndex];
4251 PointerCoords& curOutCoords = outCoords[outIndex];
4252
4253 if (curInCoords != curOutCoords) {
4254 curOutCoords.copyFrom(curInCoords);
4255 changed = true;
4256 }
4257 }
4258 return changed;
4259}
4260
4261void TouchInputMapper::fadePointer() {
4262 { // acquire lock
4263 AutoMutex _l(mLock);
4264 if (mPointerController != NULL) {
4265 mPointerController->fade();
4266 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004267 } // release lock
Jeff Brown46b9ac02010-04-22 18:58:52 -07004268}
4269
Jeff Brown6328cdc2010-07-29 18:18:33 -07004270bool TouchInputMapper::isPointInsideSurfaceLocked(int32_t x, int32_t y) {
Jeff Brown9626b142011-03-03 02:09:54 -08004271 return x >= mRawAxes.x.minValue && x <= mRawAxes.x.maxValue
4272 && y >= mRawAxes.y.minValue && y <= mRawAxes.y.maxValue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004273}
4274
Jeff Brown6328cdc2010-07-29 18:18:33 -07004275const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHitLocked(
4276 int32_t x, int32_t y) {
4277 size_t numVirtualKeys = mLocked.virtualKeys.size();
4278 for (size_t i = 0; i < numVirtualKeys; i++) {
4279 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004280
4281#if DEBUG_VIRTUAL_KEYS
4282 LOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
4283 "left=%d, top=%d, right=%d, bottom=%d",
4284 x, y,
4285 virtualKey.keyCode, virtualKey.scanCode,
4286 virtualKey.hitLeft, virtualKey.hitTop,
4287 virtualKey.hitRight, virtualKey.hitBottom);
4288#endif
4289
4290 if (virtualKey.isHit(x, y)) {
4291 return & virtualKey;
4292 }
4293 }
4294
4295 return NULL;
4296}
4297
4298void TouchInputMapper::calculatePointerIds() {
4299 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
4300 uint32_t lastPointerCount = mLastTouch.pointerCount;
4301
4302 if (currentPointerCount == 0) {
4303 // No pointers to assign.
4304 mCurrentTouch.idBits.clear();
4305 } else if (lastPointerCount == 0) {
4306 // All pointers are new.
4307 mCurrentTouch.idBits.clear();
4308 for (uint32_t i = 0; i < currentPointerCount; i++) {
4309 mCurrentTouch.pointers[i].id = i;
4310 mCurrentTouch.idToIndex[i] = i;
4311 mCurrentTouch.idBits.markBit(i);
4312 }
4313 } else if (currentPointerCount == 1 && lastPointerCount == 1) {
4314 // Only one pointer and no change in count so it must have the same id as before.
4315 uint32_t id = mLastTouch.pointers[0].id;
4316 mCurrentTouch.pointers[0].id = id;
4317 mCurrentTouch.idToIndex[id] = 0;
4318 mCurrentTouch.idBits.value = BitSet32::valueForBit(id);
4319 } else {
4320 // General case.
4321 // We build a heap of squared euclidean distances between current and last pointers
4322 // associated with the current and last pointer indices. Then, we find the best
4323 // match (by distance) for each current pointer.
4324 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
4325
4326 uint32_t heapSize = 0;
4327 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
4328 currentPointerIndex++) {
4329 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
4330 lastPointerIndex++) {
4331 int64_t deltaX = mCurrentTouch.pointers[currentPointerIndex].x
4332 - mLastTouch.pointers[lastPointerIndex].x;
4333 int64_t deltaY = mCurrentTouch.pointers[currentPointerIndex].y
4334 - mLastTouch.pointers[lastPointerIndex].y;
4335
4336 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4337
4338 // Insert new element into the heap (sift up).
4339 heap[heapSize].currentPointerIndex = currentPointerIndex;
4340 heap[heapSize].lastPointerIndex = lastPointerIndex;
4341 heap[heapSize].distance = distance;
4342 heapSize += 1;
4343 }
4344 }
4345
4346 // Heapify
4347 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
4348 startIndex -= 1;
4349 for (uint32_t parentIndex = startIndex; ;) {
4350 uint32_t childIndex = parentIndex * 2 + 1;
4351 if (childIndex >= heapSize) {
4352 break;
4353 }
4354
4355 if (childIndex + 1 < heapSize
4356 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4357 childIndex += 1;
4358 }
4359
4360 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4361 break;
4362 }
4363
4364 swap(heap[parentIndex], heap[childIndex]);
4365 parentIndex = childIndex;
4366 }
4367 }
4368
4369#if DEBUG_POINTER_ASSIGNMENT
4370 LOGD("calculatePointerIds - initial distance min-heap: size=%d", heapSize);
4371 for (size_t i = 0; i < heapSize; i++) {
4372 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4373 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4374 heap[i].distance);
4375 }
4376#endif
4377
4378 // Pull matches out by increasing order of distance.
4379 // To avoid reassigning pointers that have already been matched, the loop keeps track
4380 // of which last and current pointers have been matched using the matchedXXXBits variables.
4381 // It also tracks the used pointer id bits.
4382 BitSet32 matchedLastBits(0);
4383 BitSet32 matchedCurrentBits(0);
4384 BitSet32 usedIdBits(0);
4385 bool first = true;
4386 for (uint32_t i = min(currentPointerCount, lastPointerCount); i > 0; i--) {
4387 for (;;) {
4388 if (first) {
4389 // The first time through the loop, we just consume the root element of
4390 // the heap (the one with smallest distance).
4391 first = false;
4392 } else {
4393 // Previous iterations consumed the root element of the heap.
4394 // Pop root element off of the heap (sift down).
4395 heapSize -= 1;
Jeff Brownb6110c22011-04-01 16:15:13 -07004396 LOG_ASSERT(heapSize > 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004397
4398 // Sift down.
4399 heap[0] = heap[heapSize];
4400 for (uint32_t parentIndex = 0; ;) {
4401 uint32_t childIndex = parentIndex * 2 + 1;
4402 if (childIndex >= heapSize) {
4403 break;
4404 }
4405
4406 if (childIndex + 1 < heapSize
4407 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4408 childIndex += 1;
4409 }
4410
4411 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4412 break;
4413 }
4414
4415 swap(heap[parentIndex], heap[childIndex]);
4416 parentIndex = childIndex;
4417 }
4418
4419#if DEBUG_POINTER_ASSIGNMENT
4420 LOGD("calculatePointerIds - reduced distance min-heap: size=%d", heapSize);
4421 for (size_t i = 0; i < heapSize; i++) {
4422 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4423 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4424 heap[i].distance);
4425 }
4426#endif
4427 }
4428
4429 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4430 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4431
4432 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4433 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4434
4435 matchedCurrentBits.markBit(currentPointerIndex);
4436 matchedLastBits.markBit(lastPointerIndex);
4437
4438 uint32_t id = mLastTouch.pointers[lastPointerIndex].id;
4439 mCurrentTouch.pointers[currentPointerIndex].id = id;
4440 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4441 usedIdBits.markBit(id);
4442
4443#if DEBUG_POINTER_ASSIGNMENT
4444 LOGD("calculatePointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
4445 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
4446#endif
4447 break;
4448 }
4449 }
4450
4451 // Assign fresh ids to new pointers.
4452 if (currentPointerCount > lastPointerCount) {
4453 for (uint32_t i = currentPointerCount - lastPointerCount; ;) {
4454 uint32_t currentPointerIndex = matchedCurrentBits.firstUnmarkedBit();
4455 uint32_t id = usedIdBits.firstUnmarkedBit();
4456
4457 mCurrentTouch.pointers[currentPointerIndex].id = id;
4458 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4459 usedIdBits.markBit(id);
4460
4461#if DEBUG_POINTER_ASSIGNMENT
4462 LOGD("calculatePointerIds - assigned: cur=%d, id=%d",
4463 currentPointerIndex, id);
4464#endif
4465
4466 if (--i == 0) break; // done
4467 matchedCurrentBits.markBit(currentPointerIndex);
4468 }
4469 }
4470
4471 // Fix id bits.
4472 mCurrentTouch.idBits = usedIdBits;
4473 }
4474}
4475
4476/* Special hack for devices that have bad screen data: if one of the
4477 * points has moved more than a screen height from the last position,
4478 * then drop it. */
4479bool TouchInputMapper::applyBadTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004480 uint32_t pointerCount = mCurrentTouch.pointerCount;
4481
4482 // Nothing to do if there are no points.
4483 if (pointerCount == 0) {
4484 return false;
4485 }
4486
4487 // Don't do anything if a finger is going down or up. We run
4488 // here before assigning pointer IDs, so there isn't a good
4489 // way to do per-finger matching.
4490 if (pointerCount != mLastTouch.pointerCount) {
4491 return false;
4492 }
4493
4494 // We consider a single movement across more than a 7/16 of
4495 // the long size of the screen to be bad. This was a magic value
4496 // determined by looking at the maximum distance it is feasible
4497 // to actually move in one sample.
Jeff Brown9626b142011-03-03 02:09:54 -08004498 int32_t maxDeltaY = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) * 7 / 16;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004499
4500 // XXX The original code in InputDevice.java included commented out
4501 // code for testing the X axis. Note that when we drop a point
4502 // we don't actually restore the old X either. Strange.
4503 // The old code also tries to track when bad points were previously
4504 // detected but it turns out that due to the placement of a "break"
4505 // at the end of the loop, we never set mDroppedBadPoint to true
4506 // so it is effectively dead code.
4507 // Need to figure out if the old code is busted or just overcomplicated
4508 // but working as intended.
4509
4510 // Look through all new points and see if any are farther than
4511 // acceptable from all previous points.
4512 for (uint32_t i = pointerCount; i-- > 0; ) {
4513 int32_t y = mCurrentTouch.pointers[i].y;
4514 int32_t closestY = INT_MAX;
4515 int32_t closestDeltaY = 0;
4516
4517#if DEBUG_HACKS
4518 LOGD("BadTouchFilter: Looking at next point #%d: y=%d", i, y);
4519#endif
4520
4521 for (uint32_t j = pointerCount; j-- > 0; ) {
4522 int32_t lastY = mLastTouch.pointers[j].y;
4523 int32_t deltaY = abs(y - lastY);
4524
4525#if DEBUG_HACKS
4526 LOGD("BadTouchFilter: Comparing with last point #%d: y=%d deltaY=%d",
4527 j, lastY, deltaY);
4528#endif
4529
4530 if (deltaY < maxDeltaY) {
4531 goto SkipSufficientlyClosePoint;
4532 }
4533 if (deltaY < closestDeltaY) {
4534 closestDeltaY = deltaY;
4535 closestY = lastY;
4536 }
4537 }
4538
4539 // Must not have found a close enough match.
4540#if DEBUG_HACKS
4541 LOGD("BadTouchFilter: Dropping bad point #%d: newY=%d oldY=%d deltaY=%d maxDeltaY=%d",
4542 i, y, closestY, closestDeltaY, maxDeltaY);
4543#endif
4544
4545 mCurrentTouch.pointers[i].y = closestY;
4546 return true; // XXX original code only corrects one point
4547
4548 SkipSufficientlyClosePoint: ;
4549 }
4550
4551 // No change.
4552 return false;
4553}
4554
4555/* Special hack for devices that have bad screen data: drop points where
4556 * the coordinate value for one axis has jumped to the other pointer's location.
4557 */
4558bool TouchInputMapper::applyJumpyTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004559 uint32_t pointerCount = mCurrentTouch.pointerCount;
4560 if (mLastTouch.pointerCount != pointerCount) {
4561#if DEBUG_HACKS
4562 LOGD("JumpyTouchFilter: Different pointer count %d -> %d",
4563 mLastTouch.pointerCount, pointerCount);
4564 for (uint32_t i = 0; i < pointerCount; i++) {
4565 LOGD(" Pointer %d (%d, %d)", i,
4566 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4567 }
4568#endif
4569
4570 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_TRANSITION_DROPS) {
4571 if (mLastTouch.pointerCount == 1 && pointerCount == 2) {
4572 // Just drop the first few events going from 1 to 2 pointers.
4573 // They're bad often enough that they're not worth considering.
4574 mCurrentTouch.pointerCount = 1;
4575 mJumpyTouchFilter.jumpyPointsDropped += 1;
4576
4577#if DEBUG_HACKS
4578 LOGD("JumpyTouchFilter: Pointer 2 dropped");
4579#endif
4580 return true;
4581 } else if (mLastTouch.pointerCount == 2 && pointerCount == 1) {
4582 // The event when we go from 2 -> 1 tends to be messed up too
4583 mCurrentTouch.pointerCount = 2;
4584 mCurrentTouch.pointers[0] = mLastTouch.pointers[0];
4585 mCurrentTouch.pointers[1] = mLastTouch.pointers[1];
4586 mJumpyTouchFilter.jumpyPointsDropped += 1;
4587
4588#if DEBUG_HACKS
4589 for (int32_t i = 0; i < 2; i++) {
4590 LOGD("JumpyTouchFilter: Pointer %d replaced (%d, %d)", i,
4591 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4592 }
4593#endif
4594 return true;
4595 }
4596 }
4597 // Reset jumpy points dropped on other transitions or if limit exceeded.
4598 mJumpyTouchFilter.jumpyPointsDropped = 0;
4599
4600#if DEBUG_HACKS
4601 LOGD("JumpyTouchFilter: Transition - drop limit reset");
4602#endif
4603 return false;
4604 }
4605
4606 // We have the same number of pointers as last time.
4607 // A 'jumpy' point is one where the coordinate value for one axis
4608 // has jumped to the other pointer's location. No need to do anything
4609 // else if we only have one pointer.
4610 if (pointerCount < 2) {
4611 return false;
4612 }
4613
4614 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_DROP_LIMIT) {
Jeff Brown9626b142011-03-03 02:09:54 -08004615 int jumpyEpsilon = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) / JUMPY_EPSILON_DIVISOR;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004616
4617 // We only replace the single worst jumpy point as characterized by pointer distance
4618 // in a single axis.
4619 int32_t badPointerIndex = -1;
4620 int32_t badPointerReplacementIndex = -1;
4621 int32_t badPointerDistance = INT_MIN; // distance to be corrected
4622
4623 for (uint32_t i = pointerCount; i-- > 0; ) {
4624 int32_t x = mCurrentTouch.pointers[i].x;
4625 int32_t y = mCurrentTouch.pointers[i].y;
4626
4627#if DEBUG_HACKS
4628 LOGD("JumpyTouchFilter: Point %d (%d, %d)", i, x, y);
4629#endif
4630
4631 // Check if a touch point is too close to another's coordinates
4632 bool dropX = false, dropY = false;
4633 for (uint32_t j = 0; j < pointerCount; j++) {
4634 if (i == j) {
4635 continue;
4636 }
4637
4638 if (abs(x - mCurrentTouch.pointers[j].x) <= jumpyEpsilon) {
4639 dropX = true;
4640 break;
4641 }
4642
4643 if (abs(y - mCurrentTouch.pointers[j].y) <= jumpyEpsilon) {
4644 dropY = true;
4645 break;
4646 }
4647 }
4648 if (! dropX && ! dropY) {
4649 continue; // not jumpy
4650 }
4651
4652 // Find a replacement candidate by comparing with older points on the
4653 // complementary (non-jumpy) axis.
4654 int32_t distance = INT_MIN; // distance to be corrected
4655 int32_t replacementIndex = -1;
4656
4657 if (dropX) {
4658 // X looks too close. Find an older replacement point with a close Y.
4659 int32_t smallestDeltaY = INT_MAX;
4660 for (uint32_t j = 0; j < pointerCount; j++) {
4661 int32_t deltaY = abs(y - mLastTouch.pointers[j].y);
4662 if (deltaY < smallestDeltaY) {
4663 smallestDeltaY = deltaY;
4664 replacementIndex = j;
4665 }
4666 }
4667 distance = abs(x - mLastTouch.pointers[replacementIndex].x);
4668 } else {
4669 // Y looks too close. Find an older replacement point with a close X.
4670 int32_t smallestDeltaX = INT_MAX;
4671 for (uint32_t j = 0; j < pointerCount; j++) {
4672 int32_t deltaX = abs(x - mLastTouch.pointers[j].x);
4673 if (deltaX < smallestDeltaX) {
4674 smallestDeltaX = deltaX;
4675 replacementIndex = j;
4676 }
4677 }
4678 distance = abs(y - mLastTouch.pointers[replacementIndex].y);
4679 }
4680
4681 // If replacing this pointer would correct a worse error than the previous ones
4682 // considered, then use this replacement instead.
4683 if (distance > badPointerDistance) {
4684 badPointerIndex = i;
4685 badPointerReplacementIndex = replacementIndex;
4686 badPointerDistance = distance;
4687 }
4688 }
4689
4690 // Correct the jumpy pointer if one was found.
4691 if (badPointerIndex >= 0) {
4692#if DEBUG_HACKS
4693 LOGD("JumpyTouchFilter: Replacing bad pointer %d with (%d, %d)",
4694 badPointerIndex,
4695 mLastTouch.pointers[badPointerReplacementIndex].x,
4696 mLastTouch.pointers[badPointerReplacementIndex].y);
4697#endif
4698
4699 mCurrentTouch.pointers[badPointerIndex].x =
4700 mLastTouch.pointers[badPointerReplacementIndex].x;
4701 mCurrentTouch.pointers[badPointerIndex].y =
4702 mLastTouch.pointers[badPointerReplacementIndex].y;
4703 mJumpyTouchFilter.jumpyPointsDropped += 1;
4704 return true;
4705 }
4706 }
4707
4708 mJumpyTouchFilter.jumpyPointsDropped = 0;
4709 return false;
4710}
4711
4712/* Special hack for devices that have bad screen data: aggregate and
4713 * compute averages of the coordinate data, to reduce the amount of
4714 * jitter seen by applications. */
4715void TouchInputMapper::applyAveragingTouchFilter() {
4716 for (uint32_t currentIndex = 0; currentIndex < mCurrentTouch.pointerCount; currentIndex++) {
4717 uint32_t id = mCurrentTouch.pointers[currentIndex].id;
4718 int32_t x = mCurrentTouch.pointers[currentIndex].x;
4719 int32_t y = mCurrentTouch.pointers[currentIndex].y;
Jeff Brown8d608662010-08-30 03:02:23 -07004720 int32_t pressure;
4721 switch (mCalibration.pressureSource) {
4722 case Calibration::PRESSURE_SOURCE_PRESSURE:
4723 pressure = mCurrentTouch.pointers[currentIndex].pressure;
4724 break;
4725 case Calibration::PRESSURE_SOURCE_TOUCH:
4726 pressure = mCurrentTouch.pointers[currentIndex].touchMajor;
4727 break;
4728 default:
4729 pressure = 1;
4730 break;
4731 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004732
4733 if (mLastTouch.idBits.hasBit(id)) {
4734 // Pointer was down before and is still down now.
4735 // Compute average over history trace.
4736 uint32_t start = mAveragingTouchFilter.historyStart[id];
4737 uint32_t end = mAveragingTouchFilter.historyEnd[id];
4738
4739 int64_t deltaX = x - mAveragingTouchFilter.historyData[end].pointers[id].x;
4740 int64_t deltaY = y - mAveragingTouchFilter.historyData[end].pointers[id].y;
4741 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4742
4743#if DEBUG_HACKS
4744 LOGD("AveragingTouchFilter: Pointer id %d - Distance from last sample: %lld",
4745 id, distance);
4746#endif
4747
4748 if (distance < AVERAGING_DISTANCE_LIMIT) {
4749 // Increment end index in preparation for recording new historical data.
4750 end += 1;
4751 if (end > AVERAGING_HISTORY_SIZE) {
4752 end = 0;
4753 }
4754
4755 // If the end index has looped back to the start index then we have filled
4756 // the historical trace up to the desired size so we drop the historical
4757 // data at the start of the trace.
4758 if (end == start) {
4759 start += 1;
4760 if (start > AVERAGING_HISTORY_SIZE) {
4761 start = 0;
4762 }
4763 }
4764
4765 // Add the raw data to the historical trace.
4766 mAveragingTouchFilter.historyStart[id] = start;
4767 mAveragingTouchFilter.historyEnd[id] = end;
4768 mAveragingTouchFilter.historyData[end].pointers[id].x = x;
4769 mAveragingTouchFilter.historyData[end].pointers[id].y = y;
4770 mAveragingTouchFilter.historyData[end].pointers[id].pressure = pressure;
4771
4772 // Average over all historical positions in the trace by total pressure.
4773 int32_t averagedX = 0;
4774 int32_t averagedY = 0;
4775 int32_t totalPressure = 0;
4776 for (;;) {
4777 int32_t historicalX = mAveragingTouchFilter.historyData[start].pointers[id].x;
4778 int32_t historicalY = mAveragingTouchFilter.historyData[start].pointers[id].y;
4779 int32_t historicalPressure = mAveragingTouchFilter.historyData[start]
4780 .pointers[id].pressure;
4781
4782 averagedX += historicalX * historicalPressure;
4783 averagedY += historicalY * historicalPressure;
4784 totalPressure += historicalPressure;
4785
4786 if (start == end) {
4787 break;
4788 }
4789
4790 start += 1;
4791 if (start > AVERAGING_HISTORY_SIZE) {
4792 start = 0;
4793 }
4794 }
4795
Jeff Brown8d608662010-08-30 03:02:23 -07004796 if (totalPressure != 0) {
4797 averagedX /= totalPressure;
4798 averagedY /= totalPressure;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004799
4800#if DEBUG_HACKS
Jeff Brown8d608662010-08-30 03:02:23 -07004801 LOGD("AveragingTouchFilter: Pointer id %d - "
4802 "totalPressure=%d, averagedX=%d, averagedY=%d", id, totalPressure,
4803 averagedX, averagedY);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004804#endif
4805
Jeff Brown8d608662010-08-30 03:02:23 -07004806 mCurrentTouch.pointers[currentIndex].x = averagedX;
4807 mCurrentTouch.pointers[currentIndex].y = averagedY;
4808 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004809 } else {
4810#if DEBUG_HACKS
4811 LOGD("AveragingTouchFilter: Pointer id %d - Exceeded max distance", id);
4812#endif
4813 }
4814 } else {
4815#if DEBUG_HACKS
4816 LOGD("AveragingTouchFilter: Pointer id %d - Pointer went up", id);
4817#endif
4818 }
4819
4820 // Reset pointer history.
4821 mAveragingTouchFilter.historyStart[id] = 0;
4822 mAveragingTouchFilter.historyEnd[id] = 0;
4823 mAveragingTouchFilter.historyData[0].pointers[id].x = x;
4824 mAveragingTouchFilter.historyData[0].pointers[id].y = y;
4825 mAveragingTouchFilter.historyData[0].pointers[id].pressure = pressure;
4826 }
4827}
4828
4829int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004830 { // acquire lock
4831 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004832
Jeff Brown6328cdc2010-07-29 18:18:33 -07004833 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.keyCode == keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004834 return AKEY_STATE_VIRTUAL;
4835 }
4836
Jeff Brown6328cdc2010-07-29 18:18:33 -07004837 size_t numVirtualKeys = mLocked.virtualKeys.size();
4838 for (size_t i = 0; i < numVirtualKeys; i++) {
4839 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004840 if (virtualKey.keyCode == keyCode) {
4841 return AKEY_STATE_UP;
4842 }
4843 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004844 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004845
4846 return AKEY_STATE_UNKNOWN;
4847}
4848
4849int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004850 { // acquire lock
4851 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004852
Jeff Brown6328cdc2010-07-29 18:18:33 -07004853 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004854 return AKEY_STATE_VIRTUAL;
4855 }
4856
Jeff Brown6328cdc2010-07-29 18:18:33 -07004857 size_t numVirtualKeys = mLocked.virtualKeys.size();
4858 for (size_t i = 0; i < numVirtualKeys; i++) {
4859 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004860 if (virtualKey.scanCode == scanCode) {
4861 return AKEY_STATE_UP;
4862 }
4863 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004864 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004865
4866 return AKEY_STATE_UNKNOWN;
4867}
4868
4869bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4870 const int32_t* keyCodes, uint8_t* outFlags) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004871 { // acquire lock
4872 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004873
Jeff Brown6328cdc2010-07-29 18:18:33 -07004874 size_t numVirtualKeys = mLocked.virtualKeys.size();
4875 for (size_t i = 0; i < numVirtualKeys; i++) {
4876 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004877
4878 for (size_t i = 0; i < numCodes; i++) {
4879 if (virtualKey.keyCode == keyCodes[i]) {
4880 outFlags[i] = 1;
4881 }
4882 }
4883 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004884 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004885
4886 return true;
4887}
4888
4889
4890// --- SingleTouchInputMapper ---
4891
Jeff Brown47e6b1b2010-11-29 17:37:49 -08004892SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
4893 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004894 initialize();
4895}
4896
4897SingleTouchInputMapper::~SingleTouchInputMapper() {
4898}
4899
4900void SingleTouchInputMapper::initialize() {
4901 mAccumulator.clear();
4902
4903 mDown = false;
4904 mX = 0;
4905 mY = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07004906 mPressure = 0; // default to 0 for devices that don't report pressure
4907 mToolWidth = 0; // default to 0 for devices that don't report tool width
Jeff Brownace13b12011-03-09 17:39:48 -08004908 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004909}
4910
4911void SingleTouchInputMapper::reset() {
4912 TouchInputMapper::reset();
4913
Jeff Brown6d0fec22010-07-23 21:28:06 -07004914 initialize();
4915 }
4916
4917void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
4918 switch (rawEvent->type) {
4919 case EV_KEY:
4920 switch (rawEvent->scanCode) {
4921 case BTN_TOUCH:
4922 mAccumulator.fields |= Accumulator::FIELD_BTN_TOUCH;
4923 mAccumulator.btnTouch = rawEvent->value != 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004924 // Don't sync immediately. Wait until the next SYN_REPORT since we might
4925 // not have received valid position information yet. This logic assumes that
4926 // BTN_TOUCH is always followed by SYN_REPORT as part of a complete packet.
Jeff Brown6d0fec22010-07-23 21:28:06 -07004927 break;
Jeff Brownace13b12011-03-09 17:39:48 -08004928 default:
4929 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
4930 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
4931 if (buttonState) {
4932 if (rawEvent->value) {
4933 mAccumulator.buttonDown |= buttonState;
4934 } else {
4935 mAccumulator.buttonUp |= buttonState;
4936 }
4937 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
4938 }
4939 }
4940 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004941 }
4942 break;
4943
4944 case EV_ABS:
4945 switch (rawEvent->scanCode) {
4946 case ABS_X:
4947 mAccumulator.fields |= Accumulator::FIELD_ABS_X;
4948 mAccumulator.absX = rawEvent->value;
4949 break;
4950 case ABS_Y:
4951 mAccumulator.fields |= Accumulator::FIELD_ABS_Y;
4952 mAccumulator.absY = rawEvent->value;
4953 break;
4954 case ABS_PRESSURE:
4955 mAccumulator.fields |= Accumulator::FIELD_ABS_PRESSURE;
4956 mAccumulator.absPressure = rawEvent->value;
4957 break;
4958 case ABS_TOOL_WIDTH:
4959 mAccumulator.fields |= Accumulator::FIELD_ABS_TOOL_WIDTH;
4960 mAccumulator.absToolWidth = rawEvent->value;
4961 break;
4962 }
4963 break;
4964
4965 case EV_SYN:
4966 switch (rawEvent->scanCode) {
4967 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004968 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004969 break;
4970 }
4971 break;
4972 }
4973}
4974
4975void SingleTouchInputMapper::sync(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004976 uint32_t fields = mAccumulator.fields;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004977 if (fields == 0) {
4978 return; // no new state changes, so nothing to do
4979 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004980
4981 if (fields & Accumulator::FIELD_BTN_TOUCH) {
4982 mDown = mAccumulator.btnTouch;
4983 }
4984
4985 if (fields & Accumulator::FIELD_ABS_X) {
4986 mX = mAccumulator.absX;
4987 }
4988
4989 if (fields & Accumulator::FIELD_ABS_Y) {
4990 mY = mAccumulator.absY;
4991 }
4992
4993 if (fields & Accumulator::FIELD_ABS_PRESSURE) {
4994 mPressure = mAccumulator.absPressure;
4995 }
4996
4997 if (fields & Accumulator::FIELD_ABS_TOOL_WIDTH) {
Jeff Brown8d608662010-08-30 03:02:23 -07004998 mToolWidth = mAccumulator.absToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004999 }
5000
Jeff Brownace13b12011-03-09 17:39:48 -08005001 if (fields & Accumulator::FIELD_BUTTONS) {
5002 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
5003 }
5004
Jeff Brown6d0fec22010-07-23 21:28:06 -07005005 mCurrentTouch.clear();
5006
5007 if (mDown) {
5008 mCurrentTouch.pointerCount = 1;
5009 mCurrentTouch.pointers[0].id = 0;
5010 mCurrentTouch.pointers[0].x = mX;
5011 mCurrentTouch.pointers[0].y = mY;
5012 mCurrentTouch.pointers[0].pressure = mPressure;
Jeff Brown8d608662010-08-30 03:02:23 -07005013 mCurrentTouch.pointers[0].touchMajor = 0;
5014 mCurrentTouch.pointers[0].touchMinor = 0;
5015 mCurrentTouch.pointers[0].toolMajor = mToolWidth;
5016 mCurrentTouch.pointers[0].toolMinor = mToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005017 mCurrentTouch.pointers[0].orientation = 0;
5018 mCurrentTouch.idToIndex[0] = 0;
5019 mCurrentTouch.idBits.markBit(0);
Jeff Brownace13b12011-03-09 17:39:48 -08005020 mCurrentTouch.buttonState = mButtonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005021 }
5022
5023 syncTouch(when, true);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005024
5025 mAccumulator.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07005026}
5027
Jeff Brown8d608662010-08-30 03:02:23 -07005028void SingleTouchInputMapper::configureRawAxes() {
5029 TouchInputMapper::configureRawAxes();
Jeff Brown6d0fec22010-07-23 21:28:06 -07005030
Jeff Brown8d608662010-08-30 03:02:23 -07005031 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_X, & mRawAxes.x);
5032 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_Y, & mRawAxes.y);
5033 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_PRESSURE, & mRawAxes.pressure);
5034 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_TOOL_WIDTH, & mRawAxes.toolMajor);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005035}
5036
5037
5038// --- MultiTouchInputMapper ---
5039
Jeff Brown47e6b1b2010-11-29 17:37:49 -08005040MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
5041 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07005042 initialize();
5043}
5044
5045MultiTouchInputMapper::~MultiTouchInputMapper() {
5046}
5047
5048void MultiTouchInputMapper::initialize() {
5049 mAccumulator.clear();
Jeff Brownace13b12011-03-09 17:39:48 -08005050 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005051}
5052
5053void MultiTouchInputMapper::reset() {
5054 TouchInputMapper::reset();
5055
Jeff Brown6d0fec22010-07-23 21:28:06 -07005056 initialize();
5057}
5058
5059void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
5060 switch (rawEvent->type) {
Jeff Brownace13b12011-03-09 17:39:48 -08005061 case EV_KEY: {
5062 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
5063 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
5064 if (buttonState) {
5065 if (rawEvent->value) {
5066 mAccumulator.buttonDown |= buttonState;
5067 } else {
5068 mAccumulator.buttonUp |= buttonState;
5069 }
5070 }
5071 }
5072 break;
5073 }
5074
Jeff Brown6d0fec22010-07-23 21:28:06 -07005075 case EV_ABS: {
5076 uint32_t pointerIndex = mAccumulator.pointerCount;
5077 Accumulator::Pointer* pointer = & mAccumulator.pointers[pointerIndex];
5078
5079 switch (rawEvent->scanCode) {
5080 case ABS_MT_POSITION_X:
5081 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_X;
5082 pointer->absMTPositionX = rawEvent->value;
5083 break;
5084 case ABS_MT_POSITION_Y:
5085 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_Y;
5086 pointer->absMTPositionY = rawEvent->value;
5087 break;
5088 case ABS_MT_TOUCH_MAJOR:
5089 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MAJOR;
5090 pointer->absMTTouchMajor = rawEvent->value;
5091 break;
5092 case ABS_MT_TOUCH_MINOR:
5093 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MINOR;
5094 pointer->absMTTouchMinor = rawEvent->value;
5095 break;
5096 case ABS_MT_WIDTH_MAJOR:
5097 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MAJOR;
5098 pointer->absMTWidthMajor = rawEvent->value;
5099 break;
5100 case ABS_MT_WIDTH_MINOR:
5101 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MINOR;
5102 pointer->absMTWidthMinor = rawEvent->value;
5103 break;
5104 case ABS_MT_ORIENTATION:
5105 pointer->fields |= Accumulator::FIELD_ABS_MT_ORIENTATION;
5106 pointer->absMTOrientation = rawEvent->value;
5107 break;
5108 case ABS_MT_TRACKING_ID:
5109 pointer->fields |= Accumulator::FIELD_ABS_MT_TRACKING_ID;
5110 pointer->absMTTrackingId = rawEvent->value;
5111 break;
Jeff Brown8d608662010-08-30 03:02:23 -07005112 case ABS_MT_PRESSURE:
5113 pointer->fields |= Accumulator::FIELD_ABS_MT_PRESSURE;
5114 pointer->absMTPressure = rawEvent->value;
5115 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005116 }
5117 break;
5118 }
5119
5120 case EV_SYN:
5121 switch (rawEvent->scanCode) {
5122 case SYN_MT_REPORT: {
5123 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
5124 uint32_t pointerIndex = mAccumulator.pointerCount;
5125
5126 if (mAccumulator.pointers[pointerIndex].fields) {
5127 if (pointerIndex == MAX_POINTERS) {
5128 LOGW("MultiTouch device driver returned more than maximum of %d pointers.",
5129 MAX_POINTERS);
5130 } else {
5131 pointerIndex += 1;
5132 mAccumulator.pointerCount = pointerIndex;
5133 }
5134 }
5135
5136 mAccumulator.pointers[pointerIndex].clear();
5137 break;
5138 }
5139
5140 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005141 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005142 break;
5143 }
5144 break;
5145 }
5146}
5147
5148void MultiTouchInputMapper::sync(nsecs_t when) {
5149 static const uint32_t REQUIRED_FIELDS =
Jeff Brown8d608662010-08-30 03:02:23 -07005150 Accumulator::FIELD_ABS_MT_POSITION_X | Accumulator::FIELD_ABS_MT_POSITION_Y;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005151
Jeff Brown6d0fec22010-07-23 21:28:06 -07005152 uint32_t inCount = mAccumulator.pointerCount;
5153 uint32_t outCount = 0;
5154 bool havePointerIds = true;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005155
Jeff Brown6d0fec22010-07-23 21:28:06 -07005156 mCurrentTouch.clear();
Jeff Brown46b9ac02010-04-22 18:58:52 -07005157
Jeff Brown6d0fec22010-07-23 21:28:06 -07005158 for (uint32_t inIndex = 0; inIndex < inCount; inIndex++) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005159 const Accumulator::Pointer& inPointer = mAccumulator.pointers[inIndex];
5160 uint32_t fields = inPointer.fields;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005161
Jeff Brown6d0fec22010-07-23 21:28:06 -07005162 if ((fields & REQUIRED_FIELDS) != REQUIRED_FIELDS) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005163 // Some drivers send empty MT sync packets without X / Y to indicate a pointer up.
5164 // Drop this finger.
Jeff Brown46b9ac02010-04-22 18:58:52 -07005165 continue;
5166 }
5167
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005168 PointerData& outPointer = mCurrentTouch.pointers[outCount];
5169 outPointer.x = inPointer.absMTPositionX;
5170 outPointer.y = inPointer.absMTPositionY;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005171
Jeff Brown8d608662010-08-30 03:02:23 -07005172 if (fields & Accumulator::FIELD_ABS_MT_PRESSURE) {
5173 if (inPointer.absMTPressure <= 0) {
Jeff Brownc3db8582010-10-20 15:33:38 -07005174 // Some devices send sync packets with X / Y but with a 0 pressure to indicate
5175 // a pointer going up. Drop this finger.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005176 continue;
5177 }
Jeff Brown8d608662010-08-30 03:02:23 -07005178 outPointer.pressure = inPointer.absMTPressure;
5179 } else {
5180 // Default pressure to 0 if absent.
5181 outPointer.pressure = 0;
5182 }
5183
5184 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MAJOR) {
5185 if (inPointer.absMTTouchMajor <= 0) {
5186 // Some devices send sync packets with X / Y but with a 0 touch major to indicate
5187 // a pointer going up. Drop this finger.
5188 continue;
5189 }
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005190 outPointer.touchMajor = inPointer.absMTTouchMajor;
5191 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005192 // Default touch area to 0 if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005193 outPointer.touchMajor = 0;
5194 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07005195
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005196 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MINOR) {
5197 outPointer.touchMinor = inPointer.absMTTouchMinor;
5198 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005199 // Assume touch area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005200 outPointer.touchMinor = outPointer.touchMajor;
5201 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07005202
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005203 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MAJOR) {
5204 outPointer.toolMajor = inPointer.absMTWidthMajor;
5205 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005206 // Default tool area to 0 if absent.
5207 outPointer.toolMajor = 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005208 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07005209
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005210 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MINOR) {
5211 outPointer.toolMinor = inPointer.absMTWidthMinor;
5212 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005213 // Assume tool area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005214 outPointer.toolMinor = outPointer.toolMajor;
5215 }
5216
5217 if (fields & Accumulator::FIELD_ABS_MT_ORIENTATION) {
5218 outPointer.orientation = inPointer.absMTOrientation;
5219 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005220 // Default orientation to vertical if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005221 outPointer.orientation = 0;
5222 }
5223
Jeff Brown8d608662010-08-30 03:02:23 -07005224 // Assign pointer id using tracking id if available.
Jeff Brown6d0fec22010-07-23 21:28:06 -07005225 if (havePointerIds) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005226 if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) {
5227 uint32_t id = uint32_t(inPointer.absMTTrackingId);
Jeff Brown46b9ac02010-04-22 18:58:52 -07005228
Jeff Brown6d0fec22010-07-23 21:28:06 -07005229 if (id > MAX_POINTER_ID) {
5230#if DEBUG_POINTERS
5231 LOGD("Pointers: Ignoring driver provided pointer id %d because "
Jeff Brown01ce2e92010-09-26 22:20:12 -07005232 "it is larger than max supported id %d",
Jeff Brown6d0fec22010-07-23 21:28:06 -07005233 id, MAX_POINTER_ID);
5234#endif
5235 havePointerIds = false;
5236 }
5237 else {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005238 outPointer.id = id;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005239 mCurrentTouch.idToIndex[id] = outCount;
5240 mCurrentTouch.idBits.markBit(id);
5241 }
5242 } else {
5243 havePointerIds = false;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005244 }
5245 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07005246
Jeff Brown6d0fec22010-07-23 21:28:06 -07005247 outCount += 1;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005248 }
5249
Jeff Brown6d0fec22010-07-23 21:28:06 -07005250 mCurrentTouch.pointerCount = outCount;
Jeff Brown46b9ac02010-04-22 18:58:52 -07005251
Jeff Brownace13b12011-03-09 17:39:48 -08005252 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
5253 mCurrentTouch.buttonState = mButtonState;
5254
Jeff Brown6d0fec22010-07-23 21:28:06 -07005255 syncTouch(when, havePointerIds);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005256
5257 mAccumulator.clear();
Jeff Brown46b9ac02010-04-22 18:58:52 -07005258}
5259
Jeff Brown8d608662010-08-30 03:02:23 -07005260void MultiTouchInputMapper::configureRawAxes() {
5261 TouchInputMapper::configureRawAxes();
Jeff Brown46b9ac02010-04-22 18:58:52 -07005262
Jeff Brown8d608662010-08-30 03:02:23 -07005263 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_X, & mRawAxes.x);
5264 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_Y, & mRawAxes.y);
5265 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MAJOR, & mRawAxes.touchMajor);
5266 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MINOR, & mRawAxes.touchMinor);
5267 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MAJOR, & mRawAxes.toolMajor);
5268 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MINOR, & mRawAxes.toolMinor);
5269 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_ORIENTATION, & mRawAxes.orientation);
5270 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_PRESSURE, & mRawAxes.pressure);
Jeff Brown9c3cda02010-06-15 01:31:58 -07005271}
5272
Jeff Brown46b9ac02010-04-22 18:58:52 -07005273
Jeff Browncb1404e2011-01-15 18:14:15 -08005274// --- JoystickInputMapper ---
5275
5276JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
5277 InputMapper(device) {
Jeff Browncb1404e2011-01-15 18:14:15 -08005278}
5279
5280JoystickInputMapper::~JoystickInputMapper() {
5281}
5282
5283uint32_t JoystickInputMapper::getSources() {
5284 return AINPUT_SOURCE_JOYSTICK;
5285}
5286
5287void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
5288 InputMapper::populateDeviceInfo(info);
5289
Jeff Brown6f2fba42011-02-19 01:08:02 -08005290 for (size_t i = 0; i < mAxes.size(); i++) {
5291 const Axis& axis = mAxes.valueAt(i);
Jeff Brownefd32662011-03-08 15:13:06 -08005292 info->addMotionRange(axis.axisInfo.axis, AINPUT_SOURCE_JOYSTICK,
5293 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08005294 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
Jeff Brownefd32662011-03-08 15:13:06 -08005295 info->addMotionRange(axis.axisInfo.highAxis, AINPUT_SOURCE_JOYSTICK,
5296 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08005297 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005298 }
5299}
5300
5301void JoystickInputMapper::dump(String8& dump) {
5302 dump.append(INDENT2 "Joystick Input Mapper:\n");
5303
Jeff Brown6f2fba42011-02-19 01:08:02 -08005304 dump.append(INDENT3 "Axes:\n");
5305 size_t numAxes = mAxes.size();
5306 for (size_t i = 0; i < numAxes; i++) {
5307 const Axis& axis = mAxes.valueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005308 const char* label = getAxisLabel(axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005309 if (label) {
Jeff Brown85297452011-03-04 13:07:49 -08005310 dump.appendFormat(INDENT4 "%s", label);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005311 } else {
Jeff Brown85297452011-03-04 13:07:49 -08005312 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005313 }
Jeff Brown85297452011-03-04 13:07:49 -08005314 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5315 label = getAxisLabel(axis.axisInfo.highAxis);
5316 if (label) {
5317 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
5318 } else {
5319 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
5320 axis.axisInfo.splitValue);
5321 }
5322 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
5323 dump.append(" (invert)");
5324 }
5325
5326 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f\n",
5327 axis.min, axis.max, axis.flat, axis.fuzz);
5328 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
5329 "highScale=%0.5f, highOffset=%0.5f\n",
5330 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005331 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, rawFlat=%d, rawFuzz=%d\n",
5332 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
5333 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz);
Jeff Browncb1404e2011-01-15 18:14:15 -08005334 }
5335}
5336
5337void JoystickInputMapper::configure() {
5338 InputMapper::configure();
5339
Jeff Brown6f2fba42011-02-19 01:08:02 -08005340 // Collect all axes.
5341 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
5342 RawAbsoluteAxisInfo rawAxisInfo;
5343 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), abs, &rawAxisInfo);
5344 if (rawAxisInfo.valid) {
Jeff Brown85297452011-03-04 13:07:49 -08005345 // Map axis.
5346 AxisInfo axisInfo;
5347 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005348 if (!explicitlyMapped) {
5349 // Axis is not explicitly mapped, will choose a generic axis later.
Jeff Brown85297452011-03-04 13:07:49 -08005350 axisInfo.mode = AxisInfo::MODE_NORMAL;
5351 axisInfo.axis = -1;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005352 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005353
Jeff Brown85297452011-03-04 13:07:49 -08005354 // Apply flat override.
5355 int32_t rawFlat = axisInfo.flatOverride < 0
5356 ? rawAxisInfo.flat : axisInfo.flatOverride;
5357
5358 // Calculate scaling factors and limits.
Jeff Brown6f2fba42011-02-19 01:08:02 -08005359 Axis axis;
Jeff Brown85297452011-03-04 13:07:49 -08005360 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
5361 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
5362 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
5363 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5364 scale, 0.0f, highScale, 0.0f,
5365 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
5366 } else if (isCenteredAxis(axisInfo.axis)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005367 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
5368 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
Jeff Brown85297452011-03-04 13:07:49 -08005369 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5370 scale, offset, scale, offset,
5371 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005372 } else {
5373 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
Jeff Brown85297452011-03-04 13:07:49 -08005374 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5375 scale, 0.0f, scale, 0.0f,
5376 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005377 }
5378
5379 // To eliminate noise while the joystick is at rest, filter out small variations
5380 // in axis values up front.
5381 axis.filter = axis.flat * 0.25f;
5382
5383 mAxes.add(abs, axis);
5384 }
5385 }
5386
5387 // If there are too many axes, start dropping them.
5388 // Prefer to keep explicitly mapped axes.
5389 if (mAxes.size() > PointerCoords::MAX_AXES) {
5390 LOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.",
5391 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
5392 pruneAxes(true);
5393 pruneAxes(false);
5394 }
5395
5396 // Assign generic axis ids to remaining axes.
5397 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
5398 size_t numAxes = mAxes.size();
5399 for (size_t i = 0; i < numAxes; i++) {
5400 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005401 if (axis.axisInfo.axis < 0) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005402 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
5403 && haveAxis(nextGenericAxisId)) {
5404 nextGenericAxisId += 1;
5405 }
5406
5407 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
Jeff Brown85297452011-03-04 13:07:49 -08005408 axis.axisInfo.axis = nextGenericAxisId;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005409 nextGenericAxisId += 1;
5410 } else {
5411 LOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
5412 "have already been assigned to other axes.",
5413 getDeviceName().string(), mAxes.keyAt(i));
5414 mAxes.removeItemsAt(i--);
5415 numAxes -= 1;
5416 }
5417 }
5418 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005419}
5420
Jeff Brown85297452011-03-04 13:07:49 -08005421bool JoystickInputMapper::haveAxis(int32_t axisId) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005422 size_t numAxes = mAxes.size();
5423 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005424 const Axis& axis = mAxes.valueAt(i);
5425 if (axis.axisInfo.axis == axisId
5426 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
5427 && axis.axisInfo.highAxis == axisId)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005428 return true;
5429 }
5430 }
5431 return false;
5432}
Jeff Browncb1404e2011-01-15 18:14:15 -08005433
Jeff Brown6f2fba42011-02-19 01:08:02 -08005434void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
5435 size_t i = mAxes.size();
5436 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
5437 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
5438 continue;
5439 }
5440 LOGI("Discarding joystick '%s' axis %d because there are too many axes.",
5441 getDeviceName().string(), mAxes.keyAt(i));
5442 mAxes.removeItemsAt(i);
5443 }
5444}
5445
5446bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
5447 switch (axis) {
5448 case AMOTION_EVENT_AXIS_X:
5449 case AMOTION_EVENT_AXIS_Y:
5450 case AMOTION_EVENT_AXIS_Z:
5451 case AMOTION_EVENT_AXIS_RX:
5452 case AMOTION_EVENT_AXIS_RY:
5453 case AMOTION_EVENT_AXIS_RZ:
5454 case AMOTION_EVENT_AXIS_HAT_X:
5455 case AMOTION_EVENT_AXIS_HAT_Y:
5456 case AMOTION_EVENT_AXIS_ORIENTATION:
Jeff Brown85297452011-03-04 13:07:49 -08005457 case AMOTION_EVENT_AXIS_RUDDER:
5458 case AMOTION_EVENT_AXIS_WHEEL:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005459 return true;
5460 default:
5461 return false;
5462 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005463}
5464
5465void JoystickInputMapper::reset() {
5466 // Recenter all axes.
5467 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Browncb1404e2011-01-15 18:14:15 -08005468
Jeff Brown6f2fba42011-02-19 01:08:02 -08005469 size_t numAxes = mAxes.size();
5470 for (size_t i = 0; i < numAxes; i++) {
5471 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005472 axis.resetValue();
Jeff Brown6f2fba42011-02-19 01:08:02 -08005473 }
5474
5475 sync(when, true /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005476
5477 InputMapper::reset();
5478}
5479
5480void JoystickInputMapper::process(const RawEvent* rawEvent) {
5481 switch (rawEvent->type) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005482 case EV_ABS: {
5483 ssize_t index = mAxes.indexOfKey(rawEvent->scanCode);
5484 if (index >= 0) {
5485 Axis& axis = mAxes.editValueAt(index);
Jeff Brown85297452011-03-04 13:07:49 -08005486 float newValue, highNewValue;
5487 switch (axis.axisInfo.mode) {
5488 case AxisInfo::MODE_INVERT:
5489 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
5490 * axis.scale + axis.offset;
5491 highNewValue = 0.0f;
5492 break;
5493 case AxisInfo::MODE_SPLIT:
5494 if (rawEvent->value < axis.axisInfo.splitValue) {
5495 newValue = (axis.axisInfo.splitValue - rawEvent->value)
5496 * axis.scale + axis.offset;
5497 highNewValue = 0.0f;
5498 } else if (rawEvent->value > axis.axisInfo.splitValue) {
5499 newValue = 0.0f;
5500 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
5501 * axis.highScale + axis.highOffset;
5502 } else {
5503 newValue = 0.0f;
5504 highNewValue = 0.0f;
5505 }
5506 break;
5507 default:
5508 newValue = rawEvent->value * axis.scale + axis.offset;
5509 highNewValue = 0.0f;
5510 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005511 }
Jeff Brown85297452011-03-04 13:07:49 -08005512 axis.newValue = newValue;
5513 axis.highNewValue = highNewValue;
Jeff Browncb1404e2011-01-15 18:14:15 -08005514 }
5515 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005516 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005517
5518 case EV_SYN:
5519 switch (rawEvent->scanCode) {
5520 case SYN_REPORT:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005521 sync(rawEvent->when, false /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005522 break;
5523 }
5524 break;
5525 }
5526}
5527
Jeff Brown6f2fba42011-02-19 01:08:02 -08005528void JoystickInputMapper::sync(nsecs_t when, bool force) {
Jeff Brown85297452011-03-04 13:07:49 -08005529 if (!filterAxes(force)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005530 return;
Jeff Browncb1404e2011-01-15 18:14:15 -08005531 }
5532
5533 int32_t metaState = mContext->getGlobalMetaState();
5534
Jeff Brown6f2fba42011-02-19 01:08:02 -08005535 PointerCoords pointerCoords;
5536 pointerCoords.clear();
5537
5538 size_t numAxes = mAxes.size();
5539 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005540 const Axis& axis = mAxes.valueAt(i);
5541 pointerCoords.setAxisValue(axis.axisInfo.axis, axis.currentValue);
5542 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5543 pointerCoords.setAxisValue(axis.axisInfo.highAxis, axis.highCurrentValue);
5544 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005545 }
5546
Jeff Brown56194eb2011-03-02 19:23:13 -08005547 // Moving a joystick axis should not wake the devide because joysticks can
5548 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
5549 // button will likely wake the device.
5550 // TODO: Use the input device configuration to control this behavior more finely.
5551 uint32_t policyFlags = 0;
5552
Jeff Brown6f2fba42011-02-19 01:08:02 -08005553 int32_t pointerId = 0;
Jeff Brown56194eb2011-03-02 19:23:13 -08005554 getDispatcher()->notifyMotion(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Jeff Brown6f2fba42011-02-19 01:08:02 -08005555 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
5556 1, &pointerId, &pointerCoords, 0, 0, 0);
Jeff Browncb1404e2011-01-15 18:14:15 -08005557}
5558
Jeff Brown85297452011-03-04 13:07:49 -08005559bool JoystickInputMapper::filterAxes(bool force) {
5560 bool atLeastOneSignificantChange = force;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005561 size_t numAxes = mAxes.size();
5562 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005563 Axis& axis = mAxes.editValueAt(i);
5564 if (force || hasValueChangedSignificantly(axis.filter,
5565 axis.newValue, axis.currentValue, axis.min, axis.max)) {
5566 axis.currentValue = axis.newValue;
5567 atLeastOneSignificantChange = true;
5568 }
5569 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5570 if (force || hasValueChangedSignificantly(axis.filter,
5571 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
5572 axis.highCurrentValue = axis.highNewValue;
5573 atLeastOneSignificantChange = true;
5574 }
5575 }
5576 }
5577 return atLeastOneSignificantChange;
5578}
5579
5580bool JoystickInputMapper::hasValueChangedSignificantly(
5581 float filter, float newValue, float currentValue, float min, float max) {
5582 if (newValue != currentValue) {
5583 // Filter out small changes in value unless the value is converging on the axis
5584 // bounds or center point. This is intended to reduce the amount of information
5585 // sent to applications by particularly noisy joysticks (such as PS3).
5586 if (fabs(newValue - currentValue) > filter
5587 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
5588 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
5589 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
5590 return true;
5591 }
5592 }
5593 return false;
5594}
5595
5596bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
5597 float filter, float newValue, float currentValue, float thresholdValue) {
5598 float newDistance = fabs(newValue - thresholdValue);
5599 if (newDistance < filter) {
5600 float oldDistance = fabs(currentValue - thresholdValue);
5601 if (newDistance < oldDistance) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005602 return true;
5603 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005604 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08005605 return false;
Jeff Browncb1404e2011-01-15 18:14:15 -08005606}
5607
Jeff Brown46b9ac02010-04-22 18:58:52 -07005608} // namespace android