blob: cb690087231217ec2d62aca2b846825fda5bf17d [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070017#define LOG_TAG "InputReader"
18
19//#define LOG_NDEBUG 0
20
21// Log debug messages for each raw event received from the EventHub.
22#define DEBUG_RAW_EVENTS 0
23
24// Log debug messages about touch screen filtering hacks.
Jeff Brown349703e2010-06-22 01:27:15 -070025#define DEBUG_HACKS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070026
27// Log debug messages about virtual key processing.
Jeff Brown349703e2010-06-22 01:27:15 -070028#define DEBUG_VIRTUAL_KEYS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070029
30// Log debug messages about pointers.
Jeff Brown349703e2010-06-22 01:27:15 -070031#define DEBUG_POINTERS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070032
Jeff Brown5c225b12010-06-16 01:53:36 -070033// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
Jeff Brown96ad3972011-03-09 17:39:48 -080036// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
Jeff Brownb4ff35d2011-01-02 16:37:43 -080039#include "InputReader.h"
40
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070041#include <cutils/log.h>
Jeff Brown6b53e8d2010-11-10 16:03:06 -080042#include <ui/Keyboard.h>
Jeff Brown90655042010-12-02 13:50:46 -080043#include <ui/VirtualKeyMap.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070044
45#include <stddef.h>
Jeff Brown8d608662010-08-30 03:02:23 -070046#include <stdlib.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070047#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070048#include <errno.h>
49#include <limits.h>
Jeff Brownc5ed5912010-07-14 18:48:53 -070050#include <math.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070051
Jeff Brown8d608662010-08-30 03:02:23 -070052#define INDENT " "
Jeff Brownef3d7e82010-09-30 14:33:04 -070053#define INDENT2 " "
54#define INDENT3 " "
55#define INDENT4 " "
Jeff Brown8d608662010-08-30 03:02:23 -070056
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070057namespace android {
58
Jeff Brown96ad3972011-03-09 17:39:48 -080059// --- Constants ---
60
61// Quiet time between certain gesture transitions.
62// Time to allow for all fingers or buttons to settle into a stable state before
63// starting a new gesture.
64static const nsecs_t QUIET_INTERVAL = 100 * 1000000; // 100 ms
65
66// The minimum speed that a pointer must travel for us to consider switching the active
67// touch pointer to it during a drag. This threshold is set to avoid switching due
68// to noise from a finger resting on the touch pad (perhaps just pressing it down).
69static const float DRAG_MIN_SWITCH_SPEED = 50.0f; // pixels per second
70
71// Tap gesture delay time.
72// The time between down and up must be less than this to be considered a tap.
Jeff Brown86ea1f52011-04-12 22:39:53 -070073static const nsecs_t TAP_INTERVAL = 150 * 1000000; // 150 ms
Jeff Brown96ad3972011-03-09 17:39:48 -080074
Jeff Brown325bd072011-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 Brown96ad3972011-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 Brown325bd072011-04-19 21:20:10 -070082static const float TAP_SLOP = 10.0f; // 10 pixels
Jeff Brown96ad3972011-03-09 17:39:48 -080083
Jeff Brown86ea1f52011-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 Brown96ad3972011-03-09 17:39:48 -080088
Jeff Brown86ea1f52011-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 Brown96ad3972011-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 Brown86ea1f52011-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 Brown96ad3972011-03-09 17:39:48 -0800119
Jeff Brown46b9ac0a2010-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 Brown86ea1f52011-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 Brown96ad3972011-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 Brown46b9ac0a2010-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 Brownfd0358292010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700174};
Jeff Brown9626b142011-03-03 02:09:54 -0800175static const size_t keyCodeRotationMapSize =
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown86ea1f52011-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 Brown46b9ac0a2010-04-22 18:58:52 -0700276
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown68d60752011-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 Brown46b9ac0a2010-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 Brown68d60752011-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 Browndbf8d272011-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 Brown68d60752011-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 Brown46b9ac0a2010-04-22 18:58:52 -0700314}
315
Jeff Browndbf8d272011-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:
345 assert(false); // can't happen
346 break;
347 }
348 }
349 count -= batchSize;
350 rawEvent += batchSize;
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700382 return;
383 }
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Browndbf8d272011-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 Browndbf8d272011-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 Brown68d60752011-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 Brown46b9ac0a2010-04-22 18:58:52 -0700576 }
577 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700578 } // release device registry reader lock
Jeff Brown46b9ac0a2010-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 Brown68d60752011-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brownf2f487182010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -0700849
Jeff Browndbf8d272011-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 Browndbf8d272011-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 Brown46b9ac0a2010-04-22 18:58:52 -0700871
Jeff Brown68d60752011-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 Brown68d60752011-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 Brownfd0358292010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown51e7fe752010-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 Brown51e7fe752010-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 Brown51e7fe752010-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:
1430 assert(false);
1431 }
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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -07001487 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001488 break;
Jeff Brownefd32662011-03-08 15:13:06 -08001489 }
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -07001509 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001510 break;
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-04-22 18:58:52 -07001517 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001518 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001519 }
Jeff Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown46b9ac0a2010-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 Brown86ea1f52011-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 Brown86ea1f52011-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
Jeff Brown538881e2011-05-25 18:23:38 -07001630 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
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
1665 mAccumulator.clear();
Jeff Brown33bbfd22011-02-24 20:55:35 -08001666
1667 if (vscroll != 0 || hscroll != 0) {
1668 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
1669 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
1670
Jeff Brownefd32662011-03-08 15:13:06 -08001671 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brown33bbfd22011-02-24 20:55:35 -08001672 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
1673 1, &pointerId, &pointerCoords, mXPrecision, mYPrecision, downTime);
1674 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001675}
1676
Jeff Brown83c09682010-12-23 17:50:18 -08001677int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brownc3fc2d02010-08-10 15:47:53 -07001678 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
1679 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1680 } else {
1681 return AKEY_STATE_UNKNOWN;
1682 }
1683}
1684
Jeff Brown05dc66a2011-03-02 14:41:58 -08001685void CursorInputMapper::fadePointer() {
1686 { // acquire lock
1687 AutoMutex _l(mLock);
Jeff Brownefd32662011-03-08 15:13:06 -08001688 if (mPointerController != NULL) {
Jeff Brown538881e2011-05-25 18:23:38 -07001689 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
Jeff Brownefd32662011-03-08 15:13:06 -08001690 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001691 } // release lock
1692}
1693
Jeff Brown6d0fec22010-07-23 21:28:06 -07001694
1695// --- TouchInputMapper ---
1696
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001697TouchInputMapper::TouchInputMapper(InputDevice* device) :
1698 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001699 mLocked.surfaceOrientation = -1;
1700 mLocked.surfaceWidth = -1;
1701 mLocked.surfaceHeight = -1;
1702
1703 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001704}
1705
1706TouchInputMapper::~TouchInputMapper() {
1707}
1708
1709uint32_t TouchInputMapper::getSources() {
Jeff Brown96ad3972011-03-09 17:39:48 -08001710 return mTouchSource | mPointerSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001711}
1712
1713void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1714 InputMapper::populateDeviceInfo(info);
1715
Jeff Brown6328cdc2010-07-29 18:18:33 -07001716 { // acquire lock
1717 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001718
Jeff Brown6328cdc2010-07-29 18:18:33 -07001719 // Ensure surface information is up to date so that orientation changes are
1720 // noticed immediately.
Jeff Brownefd32662011-03-08 15:13:06 -08001721 if (!configureSurfaceLocked()) {
1722 return;
1723 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001724
Jeff Brownefd32662011-03-08 15:13:06 -08001725 info->addMotionRange(mLocked.orientedRanges.x);
1726 info->addMotionRange(mLocked.orientedRanges.y);
Jeff Brown8d608662010-08-30 03:02:23 -07001727
1728 if (mLocked.orientedRanges.havePressure) {
Jeff Brownefd32662011-03-08 15:13:06 -08001729 info->addMotionRange(mLocked.orientedRanges.pressure);
Jeff Brown8d608662010-08-30 03:02:23 -07001730 }
1731
1732 if (mLocked.orientedRanges.haveSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001733 info->addMotionRange(mLocked.orientedRanges.size);
Jeff Brown8d608662010-08-30 03:02:23 -07001734 }
1735
Jeff Brownc6d282b2010-10-14 21:42:15 -07001736 if (mLocked.orientedRanges.haveTouchSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001737 info->addMotionRange(mLocked.orientedRanges.touchMajor);
1738 info->addMotionRange(mLocked.orientedRanges.touchMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001739 }
1740
Jeff Brownc6d282b2010-10-14 21:42:15 -07001741 if (mLocked.orientedRanges.haveToolSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001742 info->addMotionRange(mLocked.orientedRanges.toolMajor);
1743 info->addMotionRange(mLocked.orientedRanges.toolMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001744 }
1745
1746 if (mLocked.orientedRanges.haveOrientation) {
Jeff Brownefd32662011-03-08 15:13:06 -08001747 info->addMotionRange(mLocked.orientedRanges.orientation);
Jeff Brown8d608662010-08-30 03:02:23 -07001748 }
Jeff Brown96ad3972011-03-09 17:39:48 -08001749
1750 if (mPointerController != NULL) {
1751 float minX, minY, maxX, maxY;
1752 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
1753 info->addMotionRange(AMOTION_EVENT_AXIS_X, mPointerSource,
1754 minX, maxX, 0.0f, 0.0f);
1755 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mPointerSource,
1756 minY, maxY, 0.0f, 0.0f);
1757 }
1758 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mPointerSource,
1759 0.0f, 1.0f, 0.0f, 0.0f);
1760 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001761 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001762}
1763
Jeff Brownef3d7e82010-09-30 14:33:04 -07001764void TouchInputMapper::dump(String8& dump) {
1765 { // acquire lock
1766 AutoMutex _l(mLock);
1767 dump.append(INDENT2 "Touch Input Mapper:\n");
Jeff Brownef3d7e82010-09-30 14:33:04 -07001768 dumpParameters(dump);
1769 dumpVirtualKeysLocked(dump);
1770 dumpRawAxes(dump);
1771 dumpCalibration(dump);
1772 dumpSurfaceLocked(dump);
Jeff Brownefd32662011-03-08 15:13:06 -08001773
Jeff Brown511ee5f2010-10-18 13:32:20 -07001774 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
Jeff Brownc6d282b2010-10-14 21:42:15 -07001775 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mLocked.xScale);
1776 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mLocked.yScale);
1777 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mLocked.xPrecision);
1778 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mLocked.yPrecision);
1779 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mLocked.geometricScale);
1780 dump.appendFormat(INDENT4 "ToolSizeLinearScale: %0.3f\n", mLocked.toolSizeLinearScale);
1781 dump.appendFormat(INDENT4 "ToolSizeLinearBias: %0.3f\n", mLocked.toolSizeLinearBias);
1782 dump.appendFormat(INDENT4 "ToolSizeAreaScale: %0.3f\n", mLocked.toolSizeAreaScale);
1783 dump.appendFormat(INDENT4 "ToolSizeAreaBias: %0.3f\n", mLocked.toolSizeAreaBias);
1784 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mLocked.pressureScale);
1785 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mLocked.sizeScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001786 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mLocked.orientationScale);
1787
1788 dump.appendFormat(INDENT3 "Last Touch:\n");
1789 dump.appendFormat(INDENT4 "Pointer Count: %d\n", mLastTouch.pointerCount);
Jeff Brown96ad3972011-03-09 17:39:48 -08001790 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", mLastTouch.buttonState);
1791
1792 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
1793 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
1794 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
1795 mLocked.pointerGestureXMovementScale);
1796 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
1797 mLocked.pointerGestureYMovementScale);
1798 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
1799 mLocked.pointerGestureXZoomScale);
1800 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
1801 mLocked.pointerGestureYZoomScale);
Jeff Brown86ea1f52011-04-12 22:39:53 -07001802 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
1803 mLocked.pointerGestureMaxSwipeWidth);
Jeff Brown96ad3972011-03-09 17:39:48 -08001804 }
Jeff Brownef3d7e82010-09-30 14:33:04 -07001805 } // release lock
1806}
1807
Jeff Brown6328cdc2010-07-29 18:18:33 -07001808void TouchInputMapper::initializeLocked() {
1809 mCurrentTouch.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001810 mLastTouch.clear();
1811 mDownTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001812
1813 for (uint32_t i = 0; i < MAX_POINTERS; i++) {
1814 mAveragingTouchFilter.historyStart[i] = 0;
1815 mAveragingTouchFilter.historyEnd[i] = 0;
1816 }
1817
1818 mJumpyTouchFilter.jumpyPointsDropped = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001819
1820 mLocked.currentVirtualKey.down = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001821
1822 mLocked.orientedRanges.havePressure = false;
1823 mLocked.orientedRanges.haveSize = false;
Jeff Brownc6d282b2010-10-14 21:42:15 -07001824 mLocked.orientedRanges.haveTouchSize = false;
1825 mLocked.orientedRanges.haveToolSize = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001826 mLocked.orientedRanges.haveOrientation = false;
Jeff Brown96ad3972011-03-09 17:39:48 -08001827
1828 mPointerGesture.reset();
Jeff Brown8d608662010-08-30 03:02:23 -07001829}
1830
Jeff Brown6d0fec22010-07-23 21:28:06 -07001831void TouchInputMapper::configure() {
1832 InputMapper::configure();
1833
1834 // Configure basic parameters.
Jeff Brown8d608662010-08-30 03:02:23 -07001835 configureParameters();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001836
Jeff Brown83c09682010-12-23 17:50:18 -08001837 // Configure sources.
1838 switch (mParameters.deviceType) {
1839 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Jeff Brownefd32662011-03-08 15:13:06 -08001840 mTouchSource = AINPUT_SOURCE_TOUCHSCREEN;
Jeff Brown96ad3972011-03-09 17:39:48 -08001841 mPointerSource = 0;
Jeff Brown83c09682010-12-23 17:50:18 -08001842 break;
1843 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Jeff Brownefd32662011-03-08 15:13:06 -08001844 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
Jeff Brown96ad3972011-03-09 17:39:48 -08001845 mPointerSource = 0;
1846 break;
1847 case Parameters::DEVICE_TYPE_POINTER:
1848 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
1849 mPointerSource = AINPUT_SOURCE_MOUSE;
Jeff Brown83c09682010-12-23 17:50:18 -08001850 break;
1851 default:
1852 assert(false);
1853 }
1854
Jeff Brown6d0fec22010-07-23 21:28:06 -07001855 // Configure absolute axis information.
Jeff Brown8d608662010-08-30 03:02:23 -07001856 configureRawAxes();
Jeff Brown8d608662010-08-30 03:02:23 -07001857
1858 // Prepare input device calibration.
1859 parseCalibration();
1860 resolveCalibration();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001861
Jeff Brown6328cdc2010-07-29 18:18:33 -07001862 { // acquire lock
1863 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001864
Jeff Brown8d608662010-08-30 03:02:23 -07001865 // Configure surface dimensions and orientation.
Jeff Brown6328cdc2010-07-29 18:18:33 -07001866 configureSurfaceLocked();
1867 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001868}
1869
Jeff Brown8d608662010-08-30 03:02:23 -07001870void TouchInputMapper::configureParameters() {
1871 mParameters.useBadTouchFilter = getPolicy()->filterTouchEvents();
1872 mParameters.useAveragingTouchFilter = getPolicy()->filterTouchEvents();
1873 mParameters.useJumpyTouchFilter = getPolicy()->filterJumpyTouchEvents();
Jeff Brownfe508922011-01-18 15:10:10 -08001874 mParameters.virtualKeyQuietTime = getPolicy()->getVirtualKeyQuietTime();
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001875
Jeff Brown538881e2011-05-25 18:23:38 -07001876 // TODO: select the default gesture mode based on whether the device supports
1877 // distinct multitouch
Jeff Brown86ea1f52011-04-12 22:39:53 -07001878 mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
1879
Jeff Brown538881e2011-05-25 18:23:38 -07001880 String8 gestureModeString;
1881 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
1882 gestureModeString)) {
1883 if (gestureModeString == "pointer") {
1884 mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER;
1885 } else if (gestureModeString == "spots") {
1886 mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
1887 } else if (gestureModeString != "default") {
1888 LOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
1889 }
1890 }
1891
Jeff Brown96ad3972011-03-09 17:39:48 -08001892 if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
1893 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
1894 // The device is a cursor device with a touch pad attached.
1895 // By default don't use the touch pad to move the pointer.
1896 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
1897 } else {
1898 // The device is just a touch pad.
1899 // By default use the touch pad to move the pointer and to perform related gestures.
1900 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
1901 }
1902
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001903 String8 deviceTypeString;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001904 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
1905 deviceTypeString)) {
Jeff Brown58a2da82011-01-25 16:02:22 -08001906 if (deviceTypeString == "touchScreen") {
1907 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brownefd32662011-03-08 15:13:06 -08001908 } else if (deviceTypeString == "touchPad") {
1909 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
Jeff Brown96ad3972011-03-09 17:39:48 -08001910 } else if (deviceTypeString == "pointer") {
1911 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
Jeff Brown538881e2011-05-25 18:23:38 -07001912 } else if (deviceTypeString != "default") {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001913 LOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
1914 }
1915 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001916
Jeff Brownefd32662011-03-08 15:13:06 -08001917 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001918 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
1919 mParameters.orientationAware);
1920
Jeff Brownefd32662011-03-08 15:13:06 -08001921 mParameters.associatedDisplayId = mParameters.orientationAware
1922 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
Jeff Brown96ad3972011-03-09 17:39:48 -08001923 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
Jeff Brownefd32662011-03-08 15:13:06 -08001924 ? 0 : -1;
Jeff Brown8d608662010-08-30 03:02:23 -07001925}
1926
Jeff Brownef3d7e82010-09-30 14:33:04 -07001927void TouchInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001928 dump.append(INDENT3 "Parameters:\n");
1929
Jeff Brown538881e2011-05-25 18:23:38 -07001930 switch (mParameters.gestureMode) {
1931 case Parameters::GESTURE_MODE_POINTER:
1932 dump.append(INDENT4 "GestureMode: pointer\n");
1933 break;
1934 case Parameters::GESTURE_MODE_SPOTS:
1935 dump.append(INDENT4 "GestureMode: spots\n");
1936 break;
1937 default:
1938 assert(false);
1939 }
1940
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001941 switch (mParameters.deviceType) {
1942 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
1943 dump.append(INDENT4 "DeviceType: touchScreen\n");
1944 break;
1945 case Parameters::DEVICE_TYPE_TOUCH_PAD:
1946 dump.append(INDENT4 "DeviceType: touchPad\n");
1947 break;
Jeff Brown96ad3972011-03-09 17:39:48 -08001948 case Parameters::DEVICE_TYPE_POINTER:
1949 dump.append(INDENT4 "DeviceType: pointer\n");
1950 break;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001951 default:
1952 assert(false);
1953 }
1954
1955 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1956 mParameters.associatedDisplayId);
1957 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1958 toString(mParameters.orientationAware));
1959
1960 dump.appendFormat(INDENT4 "UseBadTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001961 toString(mParameters.useBadTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001962 dump.appendFormat(INDENT4 "UseAveragingTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001963 toString(mParameters.useAveragingTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001964 dump.appendFormat(INDENT4 "UseJumpyTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07001965 toString(mParameters.useJumpyTouchFilter));
Jeff Brownb88102f2010-09-08 11:49:43 -07001966}
1967
Jeff Brown8d608662010-08-30 03:02:23 -07001968void TouchInputMapper::configureRawAxes() {
1969 mRawAxes.x.clear();
1970 mRawAxes.y.clear();
1971 mRawAxes.pressure.clear();
1972 mRawAxes.touchMajor.clear();
1973 mRawAxes.touchMinor.clear();
1974 mRawAxes.toolMajor.clear();
1975 mRawAxes.toolMinor.clear();
1976 mRawAxes.orientation.clear();
1977}
1978
Jeff Brownef3d7e82010-09-30 14:33:04 -07001979void TouchInputMapper::dumpRawAxes(String8& dump) {
1980 dump.append(INDENT3 "Raw Axes:\n");
Jeff Browncb1404e2011-01-15 18:14:15 -08001981 dumpRawAbsoluteAxisInfo(dump, mRawAxes.x, "X");
1982 dumpRawAbsoluteAxisInfo(dump, mRawAxes.y, "Y");
1983 dumpRawAbsoluteAxisInfo(dump, mRawAxes.pressure, "Pressure");
1984 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMajor, "TouchMajor");
1985 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMinor, "TouchMinor");
1986 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMajor, "ToolMajor");
1987 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMinor, "ToolMinor");
1988 dumpRawAbsoluteAxisInfo(dump, mRawAxes.orientation, "Orientation");
Jeff Brown6d0fec22010-07-23 21:28:06 -07001989}
1990
Jeff Brown6328cdc2010-07-29 18:18:33 -07001991bool TouchInputMapper::configureSurfaceLocked() {
Jeff Brown9626b142011-03-03 02:09:54 -08001992 // Ensure we have valid X and Y axes.
1993 if (!mRawAxes.x.valid || !mRawAxes.y.valid) {
1994 LOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
1995 "The device will be inoperable.", getDeviceName().string());
1996 return false;
1997 }
1998
Jeff Brown6d0fec22010-07-23 21:28:06 -07001999 // Update orientation and dimensions if needed.
Jeff Brownb4ff35d2011-01-02 16:37:43 -08002000 int32_t orientation = DISPLAY_ORIENTATION_0;
Jeff Brown9626b142011-03-03 02:09:54 -08002001 int32_t width = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2002 int32_t height = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002003
2004 if (mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002005 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002006 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
Jeff Brownefd32662011-03-08 15:13:06 -08002007 &mLocked.associatedDisplayWidth, &mLocked.associatedDisplayHeight,
2008 &mLocked.associatedDisplayOrientation)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002009 return false;
2010 }
Jeff Brownefd32662011-03-08 15:13:06 -08002011
2012 // A touch screen inherits the dimensions of the display.
2013 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
2014 width = mLocked.associatedDisplayWidth;
2015 height = mLocked.associatedDisplayHeight;
2016 }
2017
2018 // The device inherits the orientation of the display if it is orientation aware.
2019 if (mParameters.orientationAware) {
2020 orientation = mLocked.associatedDisplayOrientation;
2021 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002022 }
2023
Jeff Brown96ad3972011-03-09 17:39:48 -08002024 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
2025 && mPointerController == NULL) {
2026 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2027 }
2028
Jeff Brown6328cdc2010-07-29 18:18:33 -07002029 bool orientationChanged = mLocked.surfaceOrientation != orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002030 if (orientationChanged) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002031 mLocked.surfaceOrientation = orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002032 }
2033
Jeff Brown6328cdc2010-07-29 18:18:33 -07002034 bool sizeChanged = mLocked.surfaceWidth != width || mLocked.surfaceHeight != height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002035 if (sizeChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08002036 LOGI("Device reconfigured: id=%d, name='%s', surface size is now %dx%d",
Jeff Brownef3d7e82010-09-30 14:33:04 -07002037 getDeviceId(), getDeviceName().string(), width, height);
Jeff Brown8d608662010-08-30 03:02:23 -07002038
Jeff Brown6328cdc2010-07-29 18:18:33 -07002039 mLocked.surfaceWidth = width;
2040 mLocked.surfaceHeight = height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002041
Jeff Brown8d608662010-08-30 03:02:23 -07002042 // Configure X and Y factors.
Jeff Brown9626b142011-03-03 02:09:54 -08002043 mLocked.xScale = float(width) / (mRawAxes.x.maxValue - mRawAxes.x.minValue + 1);
2044 mLocked.yScale = float(height) / (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1);
2045 mLocked.xPrecision = 1.0f / mLocked.xScale;
2046 mLocked.yPrecision = 1.0f / mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002047
Jeff Brownefd32662011-03-08 15:13:06 -08002048 mLocked.orientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
2049 mLocked.orientedRanges.x.source = mTouchSource;
2050 mLocked.orientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
2051 mLocked.orientedRanges.y.source = mTouchSource;
2052
Jeff Brown9626b142011-03-03 02:09:54 -08002053 configureVirtualKeysLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002054
Jeff Brown8d608662010-08-30 03:02:23 -07002055 // Scale factor for terms that are not oriented in a particular axis.
2056 // If the pixels are square then xScale == yScale otherwise we fake it
2057 // by choosing an average.
2058 mLocked.geometricScale = avg(mLocked.xScale, mLocked.yScale);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002059
Jeff Brown8d608662010-08-30 03:02:23 -07002060 // Size of diagonal axis.
Jeff Brown86ea1f52011-04-12 22:39:53 -07002061 float diagonalSize = hypotf(width, height);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002062
Jeff Brown8d608662010-08-30 03:02:23 -07002063 // TouchMajor and TouchMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002064 if (mCalibration.touchSizeCalibration != Calibration::TOUCH_SIZE_CALIBRATION_NONE) {
2065 mLocked.orientedRanges.haveTouchSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002066
2067 mLocked.orientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
2068 mLocked.orientedRanges.touchMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002069 mLocked.orientedRanges.touchMajor.min = 0;
2070 mLocked.orientedRanges.touchMajor.max = diagonalSize;
2071 mLocked.orientedRanges.touchMajor.flat = 0;
2072 mLocked.orientedRanges.touchMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08002073
Jeff Brown8d608662010-08-30 03:02:23 -07002074 mLocked.orientedRanges.touchMinor = mLocked.orientedRanges.touchMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08002075 mLocked.orientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002076 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002077
Jeff Brown8d608662010-08-30 03:02:23 -07002078 // ToolMajor and ToolMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002079 mLocked.toolSizeLinearScale = 0;
2080 mLocked.toolSizeLinearBias = 0;
2081 mLocked.toolSizeAreaScale = 0;
2082 mLocked.toolSizeAreaBias = 0;
2083 if (mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2084 if (mCalibration.toolSizeCalibration == Calibration::TOOL_SIZE_CALIBRATION_LINEAR) {
2085 if (mCalibration.haveToolSizeLinearScale) {
2086 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
Jeff Brown8d608662010-08-30 03:02:23 -07002087 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002088 mLocked.toolSizeLinearScale = float(min(width, height))
Jeff Brown8d608662010-08-30 03:02:23 -07002089 / mRawAxes.toolMajor.maxValue;
2090 }
2091
Jeff Brownc6d282b2010-10-14 21:42:15 -07002092 if (mCalibration.haveToolSizeLinearBias) {
2093 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2094 }
2095 } else if (mCalibration.toolSizeCalibration ==
2096 Calibration::TOOL_SIZE_CALIBRATION_AREA) {
2097 if (mCalibration.haveToolSizeLinearScale) {
2098 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
2099 } else {
2100 mLocked.toolSizeLinearScale = min(width, height);
2101 }
2102
2103 if (mCalibration.haveToolSizeLinearBias) {
2104 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2105 }
2106
2107 if (mCalibration.haveToolSizeAreaScale) {
2108 mLocked.toolSizeAreaScale = mCalibration.toolSizeAreaScale;
2109 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2110 mLocked.toolSizeAreaScale = 1.0f / mRawAxes.toolMajor.maxValue;
2111 }
2112
2113 if (mCalibration.haveToolSizeAreaBias) {
2114 mLocked.toolSizeAreaBias = mCalibration.toolSizeAreaBias;
Jeff Brown8d608662010-08-30 03:02:23 -07002115 }
2116 }
2117
Jeff Brownc6d282b2010-10-14 21:42:15 -07002118 mLocked.orientedRanges.haveToolSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002119
2120 mLocked.orientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
2121 mLocked.orientedRanges.toolMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002122 mLocked.orientedRanges.toolMajor.min = 0;
2123 mLocked.orientedRanges.toolMajor.max = diagonalSize;
2124 mLocked.orientedRanges.toolMajor.flat = 0;
2125 mLocked.orientedRanges.toolMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08002126
Jeff Brown8d608662010-08-30 03:02:23 -07002127 mLocked.orientedRanges.toolMinor = mLocked.orientedRanges.toolMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08002128 mLocked.orientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002129 }
2130
2131 // Pressure factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002132 mLocked.pressureScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002133 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE) {
2134 RawAbsoluteAxisInfo rawPressureAxis;
2135 switch (mCalibration.pressureSource) {
2136 case Calibration::PRESSURE_SOURCE_PRESSURE:
2137 rawPressureAxis = mRawAxes.pressure;
2138 break;
2139 case Calibration::PRESSURE_SOURCE_TOUCH:
2140 rawPressureAxis = mRawAxes.touchMajor;
2141 break;
2142 default:
2143 rawPressureAxis.clear();
2144 }
2145
Jeff Brown8d608662010-08-30 03:02:23 -07002146 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
2147 || mCalibration.pressureCalibration
2148 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
2149 if (mCalibration.havePressureScale) {
2150 mLocked.pressureScale = mCalibration.pressureScale;
2151 } else if (rawPressureAxis.valid && rawPressureAxis.maxValue != 0) {
2152 mLocked.pressureScale = 1.0f / rawPressureAxis.maxValue;
2153 }
2154 }
2155
2156 mLocked.orientedRanges.havePressure = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002157
2158 mLocked.orientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
2159 mLocked.orientedRanges.pressure.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002160 mLocked.orientedRanges.pressure.min = 0;
2161 mLocked.orientedRanges.pressure.max = 1.0;
2162 mLocked.orientedRanges.pressure.flat = 0;
2163 mLocked.orientedRanges.pressure.fuzz = 0;
2164 }
2165
2166 // Size factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002167 mLocked.sizeScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002168 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002169 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_NORMALIZED) {
2170 if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2171 mLocked.sizeScale = 1.0f / mRawAxes.toolMajor.maxValue;
2172 }
2173 }
2174
2175 mLocked.orientedRanges.haveSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002176
2177 mLocked.orientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
2178 mLocked.orientedRanges.size.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002179 mLocked.orientedRanges.size.min = 0;
2180 mLocked.orientedRanges.size.max = 1.0;
2181 mLocked.orientedRanges.size.flat = 0;
2182 mLocked.orientedRanges.size.fuzz = 0;
2183 }
2184
2185 // Orientation
Jeff Brownc6d282b2010-10-14 21:42:15 -07002186 mLocked.orientationScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002187 if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002188 if (mCalibration.orientationCalibration
2189 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
2190 if (mRawAxes.orientation.valid && mRawAxes.orientation.maxValue != 0) {
2191 mLocked.orientationScale = float(M_PI_2) / mRawAxes.orientation.maxValue;
2192 }
2193 }
2194
Jeff Brownb416e242011-05-24 15:17:57 -07002195 mLocked.orientedRanges.haveOrientation = true;
2196
Jeff Brownefd32662011-03-08 15:13:06 -08002197 mLocked.orientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
2198 mLocked.orientedRanges.orientation.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002199 mLocked.orientedRanges.orientation.min = - M_PI_2;
2200 mLocked.orientedRanges.orientation.max = M_PI_2;
2201 mLocked.orientedRanges.orientation.flat = 0;
2202 mLocked.orientedRanges.orientation.fuzz = 0;
2203 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002204 }
2205
2206 if (orientationChanged || sizeChanged) {
Jeff Brown9626b142011-03-03 02:09:54 -08002207 // Compute oriented surface dimensions, precision, scales and ranges.
2208 // Note that the maximum value reported is an inclusive maximum value so it is one
2209 // unit less than the total width or height of surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002210 switch (mLocked.surfaceOrientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08002211 case DISPLAY_ORIENTATION_90:
2212 case DISPLAY_ORIENTATION_270:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002213 mLocked.orientedSurfaceWidth = mLocked.surfaceHeight;
2214 mLocked.orientedSurfaceHeight = mLocked.surfaceWidth;
Jeff Brown9626b142011-03-03 02:09:54 -08002215
Jeff Brown6328cdc2010-07-29 18:18:33 -07002216 mLocked.orientedXPrecision = mLocked.yPrecision;
2217 mLocked.orientedYPrecision = mLocked.xPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002218
2219 mLocked.orientedRanges.x.min = 0;
2220 mLocked.orientedRanges.x.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2221 * mLocked.yScale;
2222 mLocked.orientedRanges.x.flat = 0;
2223 mLocked.orientedRanges.x.fuzz = mLocked.yScale;
2224
2225 mLocked.orientedRanges.y.min = 0;
2226 mLocked.orientedRanges.y.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2227 * mLocked.xScale;
2228 mLocked.orientedRanges.y.flat = 0;
2229 mLocked.orientedRanges.y.fuzz = mLocked.xScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002230 break;
Jeff Brown9626b142011-03-03 02:09:54 -08002231
Jeff Brown6d0fec22010-07-23 21:28:06 -07002232 default:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002233 mLocked.orientedSurfaceWidth = mLocked.surfaceWidth;
2234 mLocked.orientedSurfaceHeight = mLocked.surfaceHeight;
Jeff Brown9626b142011-03-03 02:09:54 -08002235
Jeff Brown6328cdc2010-07-29 18:18:33 -07002236 mLocked.orientedXPrecision = mLocked.xPrecision;
2237 mLocked.orientedYPrecision = mLocked.yPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002238
2239 mLocked.orientedRanges.x.min = 0;
2240 mLocked.orientedRanges.x.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2241 * mLocked.xScale;
2242 mLocked.orientedRanges.x.flat = 0;
2243 mLocked.orientedRanges.x.fuzz = mLocked.xScale;
2244
2245 mLocked.orientedRanges.y.min = 0;
2246 mLocked.orientedRanges.y.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2247 * mLocked.yScale;
2248 mLocked.orientedRanges.y.flat = 0;
2249 mLocked.orientedRanges.y.fuzz = mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002250 break;
2251 }
Jeff Brown96ad3972011-03-09 17:39:48 -08002252
2253 // Compute pointer gesture detection parameters.
2254 // TODO: These factors should not be hardcoded.
2255 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
2256 int32_t rawWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2257 int32_t rawHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown86ea1f52011-04-12 22:39:53 -07002258 float rawDiagonal = hypotf(rawWidth, rawHeight);
2259 float displayDiagonal = hypotf(mLocked.associatedDisplayWidth,
2260 mLocked.associatedDisplayHeight);
Jeff Brown96ad3972011-03-09 17:39:48 -08002261
Jeff Brown86ea1f52011-04-12 22:39:53 -07002262 // Scale movements such that one whole swipe of the touch pad covers a
2263 // given area relative to the diagonal size of the display.
Jeff Brown96ad3972011-03-09 17:39:48 -08002264 // Assume that the touch pad has a square aspect ratio such that movements in
2265 // X and Y of the same number of raw units cover the same physical distance.
2266 const float scaleFactor = 0.8f;
2267
Jeff Brown86ea1f52011-04-12 22:39:53 -07002268 mLocked.pointerGestureXMovementScale = GESTURE_MOVEMENT_SPEED_RATIO
2269 * displayDiagonal / rawDiagonal;
Jeff Brown96ad3972011-03-09 17:39:48 -08002270 mLocked.pointerGestureYMovementScale = mLocked.pointerGestureXMovementScale;
2271
2272 // Scale zooms to cover a smaller range of the display than movements do.
2273 // This value determines the area around the pointer that is affected by freeform
2274 // pointer gestures.
Jeff Brown86ea1f52011-04-12 22:39:53 -07002275 mLocked.pointerGestureXZoomScale = GESTURE_ZOOM_SPEED_RATIO
2276 * displayDiagonal / rawDiagonal;
2277 mLocked.pointerGestureYZoomScale = mLocked.pointerGestureXZoomScale;
Jeff Brown96ad3972011-03-09 17:39:48 -08002278
Jeff Brown86ea1f52011-04-12 22:39:53 -07002279 // Max width between pointers to detect a swipe gesture is more than some fraction
2280 // of the diagonal axis of the touch pad. Touches that are wider than this are
2281 // translated into freeform gestures.
2282 mLocked.pointerGestureMaxSwipeWidth = SWIPE_MAX_WIDTH_RATIO * rawDiagonal;
2283
2284 // Reset the current pointer gesture.
2285 mPointerGesture.reset();
2286
2287 // Remove any current spots.
2288 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
2289 mPointerController->clearSpots();
2290 }
Jeff Brown96ad3972011-03-09 17:39:48 -08002291 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002292 }
2293
2294 return true;
2295}
2296
Jeff Brownef3d7e82010-09-30 14:33:04 -07002297void TouchInputMapper::dumpSurfaceLocked(String8& dump) {
2298 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mLocked.surfaceWidth);
2299 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mLocked.surfaceHeight);
2300 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mLocked.surfaceOrientation);
Jeff Brownb88102f2010-09-08 11:49:43 -07002301}
2302
Jeff Brown6328cdc2010-07-29 18:18:33 -07002303void TouchInputMapper::configureVirtualKeysLocked() {
Jeff Brown8d608662010-08-30 03:02:23 -07002304 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
Jeff Brown90655042010-12-02 13:50:46 -08002305 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002306
Jeff Brown6328cdc2010-07-29 18:18:33 -07002307 mLocked.virtualKeys.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002308
Jeff Brown6328cdc2010-07-29 18:18:33 -07002309 if (virtualKeyDefinitions.size() == 0) {
2310 return;
2311 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002312
Jeff Brown6328cdc2010-07-29 18:18:33 -07002313 mLocked.virtualKeys.setCapacity(virtualKeyDefinitions.size());
2314
Jeff Brown8d608662010-08-30 03:02:23 -07002315 int32_t touchScreenLeft = mRawAxes.x.minValue;
2316 int32_t touchScreenTop = mRawAxes.y.minValue;
Jeff Brown9626b142011-03-03 02:09:54 -08002317 int32_t touchScreenWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2318 int32_t touchScreenHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002319
2320 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002321 const VirtualKeyDefinition& virtualKeyDefinition =
Jeff Brown6328cdc2010-07-29 18:18:33 -07002322 virtualKeyDefinitions[i];
2323
2324 mLocked.virtualKeys.add();
2325 VirtualKey& virtualKey = mLocked.virtualKeys.editTop();
2326
2327 virtualKey.scanCode = virtualKeyDefinition.scanCode;
2328 int32_t keyCode;
2329 uint32_t flags;
Jeff Brown6f2fba42011-02-19 01:08:02 -08002330 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode,
Jeff Brown6328cdc2010-07-29 18:18:33 -07002331 & keyCode, & flags)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002332 LOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
2333 virtualKey.scanCode);
Jeff Brown6328cdc2010-07-29 18:18:33 -07002334 mLocked.virtualKeys.pop(); // drop the key
2335 continue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002336 }
2337
Jeff Brown6328cdc2010-07-29 18:18:33 -07002338 virtualKey.keyCode = keyCode;
2339 virtualKey.flags = flags;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002340
Jeff Brown6328cdc2010-07-29 18:18:33 -07002341 // convert the key definition's display coordinates into touch coordinates for a hit box
2342 int32_t halfWidth = virtualKeyDefinition.width / 2;
2343 int32_t halfHeight = virtualKeyDefinition.height / 2;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002344
Jeff Brown6328cdc2010-07-29 18:18:33 -07002345 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
2346 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2347 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
2348 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2349 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
2350 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
2351 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
2352 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
Jeff Brownef3d7e82010-09-30 14:33:04 -07002353 }
2354}
2355
2356void TouchInputMapper::dumpVirtualKeysLocked(String8& dump) {
2357 if (!mLocked.virtualKeys.isEmpty()) {
2358 dump.append(INDENT3 "Virtual Keys:\n");
2359
2360 for (size_t i = 0; i < mLocked.virtualKeys.size(); i++) {
2361 const VirtualKey& virtualKey = mLocked.virtualKeys.itemAt(i);
2362 dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, "
2363 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
2364 i, virtualKey.scanCode, virtualKey.keyCode,
2365 virtualKey.hitLeft, virtualKey.hitRight,
2366 virtualKey.hitTop, virtualKey.hitBottom);
2367 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002368 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002369}
2370
Jeff Brown8d608662010-08-30 03:02:23 -07002371void TouchInputMapper::parseCalibration() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002372 const PropertyMap& in = getDevice()->getConfiguration();
Jeff Brown8d608662010-08-30 03:02:23 -07002373 Calibration& out = mCalibration;
2374
Jeff Brownc6d282b2010-10-14 21:42:15 -07002375 // Touch Size
2376 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT;
2377 String8 touchSizeCalibrationString;
2378 if (in.tryGetProperty(String8("touch.touchSize.calibration"), touchSizeCalibrationString)) {
2379 if (touchSizeCalibrationString == "none") {
2380 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
2381 } else if (touchSizeCalibrationString == "geometric") {
2382 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC;
2383 } else if (touchSizeCalibrationString == "pressure") {
2384 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
2385 } else if (touchSizeCalibrationString != "default") {
2386 LOGW("Invalid value for touch.touchSize.calibration: '%s'",
2387 touchSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002388 }
2389 }
2390
Jeff Brownc6d282b2010-10-14 21:42:15 -07002391 // Tool Size
2392 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_DEFAULT;
2393 String8 toolSizeCalibrationString;
2394 if (in.tryGetProperty(String8("touch.toolSize.calibration"), toolSizeCalibrationString)) {
2395 if (toolSizeCalibrationString == "none") {
2396 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
2397 } else if (toolSizeCalibrationString == "geometric") {
2398 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC;
2399 } else if (toolSizeCalibrationString == "linear") {
2400 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
2401 } else if (toolSizeCalibrationString == "area") {
2402 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_AREA;
2403 } else if (toolSizeCalibrationString != "default") {
2404 LOGW("Invalid value for touch.toolSize.calibration: '%s'",
2405 toolSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002406 }
2407 }
2408
Jeff Brownc6d282b2010-10-14 21:42:15 -07002409 out.haveToolSizeLinearScale = in.tryGetProperty(String8("touch.toolSize.linearScale"),
2410 out.toolSizeLinearScale);
2411 out.haveToolSizeLinearBias = in.tryGetProperty(String8("touch.toolSize.linearBias"),
2412 out.toolSizeLinearBias);
2413 out.haveToolSizeAreaScale = in.tryGetProperty(String8("touch.toolSize.areaScale"),
2414 out.toolSizeAreaScale);
2415 out.haveToolSizeAreaBias = in.tryGetProperty(String8("touch.toolSize.areaBias"),
2416 out.toolSizeAreaBias);
2417 out.haveToolSizeIsSummed = in.tryGetProperty(String8("touch.toolSize.isSummed"),
2418 out.toolSizeIsSummed);
Jeff Brown8d608662010-08-30 03:02:23 -07002419
2420 // Pressure
2421 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
2422 String8 pressureCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002423 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002424 if (pressureCalibrationString == "none") {
2425 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2426 } else if (pressureCalibrationString == "physical") {
2427 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
2428 } else if (pressureCalibrationString == "amplitude") {
2429 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2430 } else if (pressureCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002431 LOGW("Invalid value for touch.pressure.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002432 pressureCalibrationString.string());
2433 }
2434 }
2435
2436 out.pressureSource = Calibration::PRESSURE_SOURCE_DEFAULT;
2437 String8 pressureSourceString;
2438 if (in.tryGetProperty(String8("touch.pressure.source"), pressureSourceString)) {
2439 if (pressureSourceString == "pressure") {
2440 out.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2441 } else if (pressureSourceString == "touch") {
2442 out.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2443 } else if (pressureSourceString != "default") {
2444 LOGW("Invalid value for touch.pressure.source: '%s'",
2445 pressureSourceString.string());
2446 }
2447 }
2448
2449 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
2450 out.pressureScale);
2451
2452 // Size
2453 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
2454 String8 sizeCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002455 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002456 if (sizeCalibrationString == "none") {
2457 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2458 } else if (sizeCalibrationString == "normalized") {
2459 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2460 } else if (sizeCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002461 LOGW("Invalid value for touch.size.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002462 sizeCalibrationString.string());
2463 }
2464 }
2465
2466 // Orientation
2467 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
2468 String8 orientationCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002469 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002470 if (orientationCalibrationString == "none") {
2471 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2472 } else if (orientationCalibrationString == "interpolated") {
2473 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002474 } else if (orientationCalibrationString == "vector") {
2475 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002476 } else if (orientationCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002477 LOGW("Invalid value for touch.orientation.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002478 orientationCalibrationString.string());
2479 }
2480 }
2481}
2482
2483void TouchInputMapper::resolveCalibration() {
2484 // Pressure
2485 switch (mCalibration.pressureSource) {
2486 case Calibration::PRESSURE_SOURCE_DEFAULT:
2487 if (mRawAxes.pressure.valid) {
2488 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2489 } else if (mRawAxes.touchMajor.valid) {
2490 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2491 }
2492 break;
2493
2494 case Calibration::PRESSURE_SOURCE_PRESSURE:
2495 if (! mRawAxes.pressure.valid) {
2496 LOGW("Calibration property touch.pressure.source is 'pressure' but "
2497 "the pressure axis is not available.");
2498 }
2499 break;
2500
2501 case Calibration::PRESSURE_SOURCE_TOUCH:
2502 if (! mRawAxes.touchMajor.valid) {
2503 LOGW("Calibration property touch.pressure.source is 'touch' but "
2504 "the touchMajor axis is not available.");
2505 }
2506 break;
2507
2508 default:
2509 break;
2510 }
2511
2512 switch (mCalibration.pressureCalibration) {
2513 case Calibration::PRESSURE_CALIBRATION_DEFAULT:
2514 if (mCalibration.pressureSource != Calibration::PRESSURE_SOURCE_DEFAULT) {
2515 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2516 } else {
2517 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2518 }
2519 break;
2520
2521 default:
2522 break;
2523 }
2524
Jeff Brownc6d282b2010-10-14 21:42:15 -07002525 // Tool Size
2526 switch (mCalibration.toolSizeCalibration) {
2527 case Calibration::TOOL_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002528 if (mRawAxes.toolMajor.valid) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002529 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
Jeff Brown8d608662010-08-30 03:02:23 -07002530 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002531 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002532 }
2533 break;
2534
2535 default:
2536 break;
2537 }
2538
Jeff Brownc6d282b2010-10-14 21:42:15 -07002539 // Touch Size
2540 switch (mCalibration.touchSizeCalibration) {
2541 case Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002542 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE
Jeff Brownc6d282b2010-10-14 21:42:15 -07002543 && mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2544 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
Jeff Brown8d608662010-08-30 03:02:23 -07002545 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002546 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002547 }
2548 break;
2549
2550 default:
2551 break;
2552 }
2553
2554 // Size
2555 switch (mCalibration.sizeCalibration) {
2556 case Calibration::SIZE_CALIBRATION_DEFAULT:
2557 if (mRawAxes.toolMajor.valid) {
2558 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2559 } else {
2560 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2561 }
2562 break;
2563
2564 default:
2565 break;
2566 }
2567
2568 // Orientation
2569 switch (mCalibration.orientationCalibration) {
2570 case Calibration::ORIENTATION_CALIBRATION_DEFAULT:
2571 if (mRawAxes.orientation.valid) {
2572 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
2573 } else {
2574 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2575 }
2576 break;
2577
2578 default:
2579 break;
2580 }
2581}
2582
Jeff Brownef3d7e82010-09-30 14:33:04 -07002583void TouchInputMapper::dumpCalibration(String8& dump) {
2584 dump.append(INDENT3 "Calibration:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002585
Jeff Brownc6d282b2010-10-14 21:42:15 -07002586 // Touch Size
2587 switch (mCalibration.touchSizeCalibration) {
2588 case Calibration::TOUCH_SIZE_CALIBRATION_NONE:
2589 dump.append(INDENT4 "touch.touchSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002590 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002591 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
2592 dump.append(INDENT4 "touch.touchSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002593 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002594 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
2595 dump.append(INDENT4 "touch.touchSize.calibration: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002596 break;
2597 default:
2598 assert(false);
2599 }
2600
Jeff Brownc6d282b2010-10-14 21:42:15 -07002601 // Tool Size
2602 switch (mCalibration.toolSizeCalibration) {
2603 case Calibration::TOOL_SIZE_CALIBRATION_NONE:
2604 dump.append(INDENT4 "touch.toolSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002605 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002606 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
2607 dump.append(INDENT4 "touch.toolSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002608 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002609 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
2610 dump.append(INDENT4 "touch.toolSize.calibration: linear\n");
2611 break;
2612 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
2613 dump.append(INDENT4 "touch.toolSize.calibration: area\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002614 break;
2615 default:
2616 assert(false);
2617 }
2618
Jeff Brownc6d282b2010-10-14 21:42:15 -07002619 if (mCalibration.haveToolSizeLinearScale) {
2620 dump.appendFormat(INDENT4 "touch.toolSize.linearScale: %0.3f\n",
2621 mCalibration.toolSizeLinearScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002622 }
2623
Jeff Brownc6d282b2010-10-14 21:42:15 -07002624 if (mCalibration.haveToolSizeLinearBias) {
2625 dump.appendFormat(INDENT4 "touch.toolSize.linearBias: %0.3f\n",
2626 mCalibration.toolSizeLinearBias);
Jeff Brown8d608662010-08-30 03:02:23 -07002627 }
2628
Jeff Brownc6d282b2010-10-14 21:42:15 -07002629 if (mCalibration.haveToolSizeAreaScale) {
2630 dump.appendFormat(INDENT4 "touch.toolSize.areaScale: %0.3f\n",
2631 mCalibration.toolSizeAreaScale);
2632 }
2633
2634 if (mCalibration.haveToolSizeAreaBias) {
2635 dump.appendFormat(INDENT4 "touch.toolSize.areaBias: %0.3f\n",
2636 mCalibration.toolSizeAreaBias);
2637 }
2638
2639 if (mCalibration.haveToolSizeIsSummed) {
Jeff Brown1f245102010-11-18 20:53:46 -08002640 dump.appendFormat(INDENT4 "touch.toolSize.isSummed: %s\n",
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002641 toString(mCalibration.toolSizeIsSummed));
Jeff Brown8d608662010-08-30 03:02:23 -07002642 }
2643
2644 // Pressure
2645 switch (mCalibration.pressureCalibration) {
2646 case Calibration::PRESSURE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002647 dump.append(INDENT4 "touch.pressure.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002648 break;
2649 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002650 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002651 break;
2652 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002653 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002654 break;
2655 default:
2656 assert(false);
2657 }
2658
2659 switch (mCalibration.pressureSource) {
2660 case Calibration::PRESSURE_SOURCE_PRESSURE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002661 dump.append(INDENT4 "touch.pressure.source: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002662 break;
2663 case Calibration::PRESSURE_SOURCE_TOUCH:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002664 dump.append(INDENT4 "touch.pressure.source: touch\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002665 break;
2666 case Calibration::PRESSURE_SOURCE_DEFAULT:
2667 break;
2668 default:
2669 assert(false);
2670 }
2671
2672 if (mCalibration.havePressureScale) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07002673 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
2674 mCalibration.pressureScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002675 }
2676
2677 // Size
2678 switch (mCalibration.sizeCalibration) {
2679 case Calibration::SIZE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002680 dump.append(INDENT4 "touch.size.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002681 break;
2682 case Calibration::SIZE_CALIBRATION_NORMALIZED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002683 dump.append(INDENT4 "touch.size.calibration: normalized\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002684 break;
2685 default:
2686 assert(false);
2687 }
2688
2689 // Orientation
2690 switch (mCalibration.orientationCalibration) {
2691 case Calibration::ORIENTATION_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002692 dump.append(INDENT4 "touch.orientation.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002693 break;
2694 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002695 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002696 break;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002697 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
2698 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
2699 break;
Jeff Brown8d608662010-08-30 03:02:23 -07002700 default:
2701 assert(false);
2702 }
2703}
2704
Jeff Brown6d0fec22010-07-23 21:28:06 -07002705void TouchInputMapper::reset() {
2706 // Synthesize touch up event if touch is currently down.
2707 // This will also take care of finishing virtual key processing if needed.
2708 if (mLastTouch.pointerCount != 0) {
2709 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
2710 mCurrentTouch.clear();
2711 syncTouch(when, true);
2712 }
2713
Jeff Brown6328cdc2010-07-29 18:18:33 -07002714 { // acquire lock
2715 AutoMutex _l(mLock);
2716 initializeLocked();
Jeff Brown86ea1f52011-04-12 22:39:53 -07002717
2718 if (mPointerController != NULL
2719 && mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
2720 mPointerController->clearSpots();
2721 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002722 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002723
Jeff Brown6328cdc2010-07-29 18:18:33 -07002724 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002725}
2726
2727void TouchInputMapper::syncTouch(nsecs_t when, bool havePointerIds) {
Jeff Brown68d60752011-03-17 01:34:19 -07002728#if DEBUG_RAW_EVENTS
2729 if (!havePointerIds) {
2730 LOGD("syncTouch: pointerCount=%d, no pointer ids", mCurrentTouch.pointerCount);
2731 } else {
2732 LOGD("syncTouch: pointerCount=%d, up=0x%08x, down=0x%08x, move=0x%08x, "
2733 "last=0x%08x, current=0x%08x", mCurrentTouch.pointerCount,
2734 mLastTouch.idBits.value & ~mCurrentTouch.idBits.value,
2735 mCurrentTouch.idBits.value & ~mLastTouch.idBits.value,
2736 mLastTouch.idBits.value & mCurrentTouch.idBits.value,
2737 mLastTouch.idBits.value, mCurrentTouch.idBits.value);
2738 }
2739#endif
2740
Jeff Brown6328cdc2010-07-29 18:18:33 -07002741 // Preprocess pointer data.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002742 if (mParameters.useBadTouchFilter) {
2743 if (applyBadTouchFilter()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002744 havePointerIds = false;
2745 }
2746 }
2747
Jeff Brown6d0fec22010-07-23 21:28:06 -07002748 if (mParameters.useJumpyTouchFilter) {
2749 if (applyJumpyTouchFilter()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002750 havePointerIds = false;
2751 }
2752 }
2753
Jeff Brown68d60752011-03-17 01:34:19 -07002754 if (!havePointerIds) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002755 calculatePointerIds();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002756 }
2757
Jeff Brown6d0fec22010-07-23 21:28:06 -07002758 TouchData temp;
2759 TouchData* savedTouch;
2760 if (mParameters.useAveragingTouchFilter) {
2761 temp.copyFrom(mCurrentTouch);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002762 savedTouch = & temp;
2763
Jeff Brown6d0fec22010-07-23 21:28:06 -07002764 applyAveragingTouchFilter();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002765 } else {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002766 savedTouch = & mCurrentTouch;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002767 }
2768
Jeff Brown56194eb2011-03-02 19:23:13 -08002769 uint32_t policyFlags = 0;
Jeff Brown05dc66a2011-03-02 14:41:58 -08002770 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
Jeff Brownefd32662011-03-08 15:13:06 -08002771 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
2772 // If this is a touch screen, hide the pointer on an initial down.
2773 getContext()->fadePointer();
2774 }
Jeff Brown56194eb2011-03-02 19:23:13 -08002775
2776 // Initial downs on external touch devices should wake the device.
2777 // We don't do this for internal touch screens to prevent them from waking
2778 // up in your pocket.
2779 // TODO: Use the input device configuration to control this behavior more finely.
2780 if (getDevice()->isExternal()) {
2781 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
2782 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08002783 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002784
Jeff Brown325bd072011-04-19 21:20:10 -07002785 TouchResult touchResult;
2786 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount == 0
2787 && mLastTouch.buttonState == mCurrentTouch.buttonState) {
2788 // Drop spurious syncs.
2789 touchResult = DROP_STROKE;
2790 } else {
2791 // Process touches and virtual keys.
2792 touchResult = consumeOffScreenTouches(when, policyFlags);
2793 if (touchResult == DISPATCH_TOUCH) {
2794 suppressSwipeOntoVirtualKeys(when);
2795 if (mPointerController != NULL) {
2796 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2797 }
2798 dispatchTouches(when, policyFlags);
Jeff Brown96ad3972011-03-09 17:39:48 -08002799 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002800 }
2801
Jeff Brown6328cdc2010-07-29 18:18:33 -07002802 // Copy current touch to last touch in preparation for the next cycle.
Jeff Brown96ad3972011-03-09 17:39:48 -08002803 // Keep the button state so we can track edge-triggered button state changes.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002804 if (touchResult == DROP_STROKE) {
2805 mLastTouch.clear();
Jeff Brown96ad3972011-03-09 17:39:48 -08002806 mLastTouch.buttonState = savedTouch->buttonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002807 } else {
2808 mLastTouch.copyFrom(*savedTouch);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002809 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002810}
2811
Jeff Brown325bd072011-04-19 21:20:10 -07002812void TouchInputMapper::timeoutExpired(nsecs_t when) {
2813 if (mPointerController != NULL) {
2814 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
2815 }
2816}
2817
Jeff Brown6d0fec22010-07-23 21:28:06 -07002818TouchInputMapper::TouchResult TouchInputMapper::consumeOffScreenTouches(
2819 nsecs_t when, uint32_t policyFlags) {
2820 int32_t keyEventAction, keyEventFlags;
2821 int32_t keyCode, scanCode, downTime;
2822 TouchResult touchResult;
Jeff Brown349703e2010-06-22 01:27:15 -07002823
Jeff Brown6328cdc2010-07-29 18:18:33 -07002824 { // acquire lock
2825 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002826
Jeff Brown6328cdc2010-07-29 18:18:33 -07002827 // Update surface size and orientation, including virtual key positions.
2828 if (! configureSurfaceLocked()) {
2829 return DROP_STROKE;
2830 }
2831
2832 // Check for virtual key press.
2833 if (mLocked.currentVirtualKey.down) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002834 if (mCurrentTouch.pointerCount == 0) {
2835 // Pointer went up while virtual key was down.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002836 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002837#if DEBUG_VIRTUAL_KEYS
2838 LOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002839 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002840#endif
2841 keyEventAction = AKEY_EVENT_ACTION_UP;
2842 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2843 touchResult = SKIP_TOUCH;
2844 goto DispatchVirtualKey;
2845 }
2846
2847 if (mCurrentTouch.pointerCount == 1) {
2848 int32_t x = mCurrentTouch.pointers[0].x;
2849 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002850 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
2851 if (virtualKey && virtualKey->keyCode == mLocked.currentVirtualKey.keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002852 // Pointer is still within the space of the virtual key.
2853 return SKIP_TOUCH;
2854 }
2855 }
2856
2857 // Pointer left virtual key area or another pointer also went down.
2858 // Send key cancellation and drop the stroke so subsequent motions will be
2859 // considered fresh downs. This is useful when the user swipes away from the
2860 // virtual key area into the main display surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002861 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002862#if DEBUG_VIRTUAL_KEYS
2863 LOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002864 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002865#endif
2866 keyEventAction = AKEY_EVENT_ACTION_UP;
2867 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
2868 | AKEY_EVENT_FLAG_CANCELED;
Jeff Brownc3db8582010-10-20 15:33:38 -07002869
2870 // Check whether the pointer moved inside the display area where we should
2871 // start a new stroke.
2872 int32_t x = mCurrentTouch.pointers[0].x;
2873 int32_t y = mCurrentTouch.pointers[0].y;
2874 if (isPointInsideSurfaceLocked(x, y)) {
2875 mLastTouch.clear();
2876 touchResult = DISPATCH_TOUCH;
2877 } else {
2878 touchResult = DROP_STROKE;
2879 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002880 } else {
2881 if (mCurrentTouch.pointerCount >= 1 && mLastTouch.pointerCount == 0) {
2882 // Pointer just went down. Handle off-screen touches, if needed.
2883 int32_t x = mCurrentTouch.pointers[0].x;
2884 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002885 if (! isPointInsideSurfaceLocked(x, y)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002886 // If exactly one pointer went down, check for virtual key hit.
2887 // Otherwise we will drop the entire stroke.
2888 if (mCurrentTouch.pointerCount == 1) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002889 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002890 if (virtualKey) {
Jeff Brownfe508922011-01-18 15:10:10 -08002891 if (mContext->shouldDropVirtualKey(when, getDevice(),
2892 virtualKey->keyCode, virtualKey->scanCode)) {
2893 return DROP_STROKE;
2894 }
2895
Jeff Brown6328cdc2010-07-29 18:18:33 -07002896 mLocked.currentVirtualKey.down = true;
2897 mLocked.currentVirtualKey.downTime = when;
2898 mLocked.currentVirtualKey.keyCode = virtualKey->keyCode;
2899 mLocked.currentVirtualKey.scanCode = virtualKey->scanCode;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002900#if DEBUG_VIRTUAL_KEYS
2901 LOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07002902 mLocked.currentVirtualKey.keyCode,
2903 mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002904#endif
2905 keyEventAction = AKEY_EVENT_ACTION_DOWN;
2906 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM
2907 | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
2908 touchResult = SKIP_TOUCH;
2909 goto DispatchVirtualKey;
2910 }
2911 }
2912 return DROP_STROKE;
2913 }
2914 }
2915 return DISPATCH_TOUCH;
2916 }
2917
2918 DispatchVirtualKey:
2919 // Collect remaining state needed to dispatch virtual key.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002920 keyCode = mLocked.currentVirtualKey.keyCode;
2921 scanCode = mLocked.currentVirtualKey.scanCode;
2922 downTime = mLocked.currentVirtualKey.downTime;
2923 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002924
2925 // Dispatch virtual key.
2926 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown0eaf3932010-10-01 14:55:30 -07002927 policyFlags |= POLICY_FLAG_VIRTUAL;
Jeff Brownb6997262010-10-08 22:31:17 -07002928 getDispatcher()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
2929 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
2930 return touchResult;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002931}
2932
Jeff Brownefd32662011-03-08 15:13:06 -08002933void TouchInputMapper::suppressSwipeOntoVirtualKeys(nsecs_t when) {
Jeff Brownfe508922011-01-18 15:10:10 -08002934 // Disable all virtual key touches that happen within a short time interval of the
2935 // most recent touch. The idea is to filter out stray virtual key presses when
2936 // interacting with the touch screen.
2937 //
2938 // Problems we're trying to solve:
2939 //
2940 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
2941 // virtual key area that is implemented by a separate touch panel and accidentally
2942 // triggers a virtual key.
2943 //
2944 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
2945 // area and accidentally triggers a virtual key. This often happens when virtual keys
2946 // are layed out below the screen near to where the on screen keyboard's space bar
2947 // is displayed.
2948 if (mParameters.virtualKeyQuietTime > 0 && mCurrentTouch.pointerCount != 0) {
2949 mContext->disableVirtualKeysUntil(when + mParameters.virtualKeyQuietTime);
2950 }
2951}
2952
Jeff Brown6d0fec22010-07-23 21:28:06 -07002953void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
2954 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
2955 uint32_t lastPointerCount = mLastTouch.pointerCount;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002956 if (currentPointerCount == 0 && lastPointerCount == 0) {
2957 return; // nothing to do!
2958 }
2959
Jeff Brown96ad3972011-03-09 17:39:48 -08002960 // Update current touch coordinates.
2961 int32_t edgeFlags;
2962 float xPrecision, yPrecision;
2963 prepareTouches(&edgeFlags, &xPrecision, &yPrecision);
2964
2965 // Dispatch motions.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002966 BitSet32 currentIdBits = mCurrentTouch.idBits;
2967 BitSet32 lastIdBits = mLastTouch.idBits;
Jeff Brown96ad3972011-03-09 17:39:48 -08002968 uint32_t metaState = getContext()->getGlobalMetaState();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002969
2970 if (currentIdBits == lastIdBits) {
2971 // No pointer id changes so this is a move event.
2972 // The dispatcher takes care of batching moves so we don't have to deal with that here.
Jeff Brown96ad3972011-03-09 17:39:48 -08002973 dispatchMotion(when, policyFlags, mTouchSource,
2974 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
2975 mCurrentTouchCoords, mCurrentTouch.idToIndex, currentIdBits, -1,
2976 xPrecision, yPrecision, mDownTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002977 } else {
Jeff Brownc3db8582010-10-20 15:33:38 -07002978 // There may be pointers going up and pointers going down and pointers moving
2979 // all at the same time.
Jeff Brown96ad3972011-03-09 17:39:48 -08002980 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2981 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002982 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
Jeff Brown96ad3972011-03-09 17:39:48 -08002983 BitSet32 dispatchedIdBits(lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07002984
Jeff Brown96ad3972011-03-09 17:39:48 -08002985 // Update last coordinates of pointers that have moved so that we observe the new
2986 // pointer positions at the same time as other pointers that have just gone up.
2987 bool moveNeeded = updateMovedPointerCoords(
2988 mCurrentTouchCoords, mCurrentTouch.idToIndex,
2989 mLastTouchCoords, mLastTouch.idToIndex,
2990 moveIdBits);
Jeff Brownc3db8582010-10-20 15:33:38 -07002991
Jeff Brown96ad3972011-03-09 17:39:48 -08002992 // Dispatch pointer up events.
Jeff Brownc3db8582010-10-20 15:33:38 -07002993 while (!upIdBits.isEmpty()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002994 uint32_t upId = upIdBits.firstMarkedBit();
2995 upIdBits.clearBit(upId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002996
Jeff Brown96ad3972011-03-09 17:39:48 -08002997 dispatchMotion(when, policyFlags, mTouchSource,
2998 AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, 0,
2999 mLastTouchCoords, mLastTouch.idToIndex, dispatchedIdBits, upId,
3000 xPrecision, yPrecision, mDownTime);
3001 dispatchedIdBits.clearBit(upId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003002 }
3003
Jeff Brownc3db8582010-10-20 15:33:38 -07003004 // Dispatch move events if any of the remaining pointers moved from their old locations.
3005 // Although applications receive new locations as part of individual pointer up
3006 // events, they do not generally handle them except when presented in a move event.
3007 if (moveNeeded) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003008 assert(moveIdBits.value == dispatchedIdBits.value);
3009 dispatchMotion(when, policyFlags, mTouchSource,
3010 AMOTION_EVENT_ACTION_MOVE, 0, metaState, 0,
3011 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, -1,
3012 xPrecision, yPrecision, mDownTime);
Jeff Brownc3db8582010-10-20 15:33:38 -07003013 }
3014
3015 // Dispatch pointer down events using the new pointer locations.
3016 while (!downIdBits.isEmpty()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003017 uint32_t downId = downIdBits.firstMarkedBit();
3018 downIdBits.clearBit(downId);
Jeff Brown96ad3972011-03-09 17:39:48 -08003019 dispatchedIdBits.markBit(downId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003020
Jeff Brown96ad3972011-03-09 17:39:48 -08003021 if (dispatchedIdBits.count() == 1) {
3022 // First pointer is going down. Set down time.
Jeff Brown6d0fec22010-07-23 21:28:06 -07003023 mDownTime = when;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003024 } else {
Jeff Brown96ad3972011-03-09 17:39:48 -08003025 // Only send edge flags with first pointer down.
3026 edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003027 }
3028
Jeff Brown96ad3972011-03-09 17:39:48 -08003029 dispatchMotion(when, policyFlags, mTouchSource,
3030 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
3031 mCurrentTouchCoords, mCurrentTouch.idToIndex, dispatchedIdBits, downId,
3032 xPrecision, yPrecision, mDownTime);
3033 }
3034 }
3035
3036 // Update state for next time.
3037 for (uint32_t i = 0; i < currentPointerCount; i++) {
3038 mLastTouchCoords[i].copyFrom(mCurrentTouchCoords[i]);
3039 }
3040}
3041
3042void TouchInputMapper::prepareTouches(int32_t* outEdgeFlags,
3043 float* outXPrecision, float* outYPrecision) {
3044 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
3045 uint32_t lastPointerCount = mLastTouch.pointerCount;
3046
3047 AutoMutex _l(mLock);
3048
3049 // Walk through the the active pointers and map touch screen coordinates (TouchData) into
3050 // display or surface coordinates (PointerCoords) and adjust for display orientation.
3051 for (uint32_t i = 0; i < currentPointerCount; i++) {
3052 const PointerData& in = mCurrentTouch.pointers[i];
3053
3054 // ToolMajor and ToolMinor
3055 float toolMajor, toolMinor;
3056 switch (mCalibration.toolSizeCalibration) {
3057 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
3058 toolMajor = in.toolMajor * mLocked.geometricScale;
3059 if (mRawAxes.toolMinor.valid) {
3060 toolMinor = in.toolMinor * mLocked.geometricScale;
3061 } else {
3062 toolMinor = toolMajor;
3063 }
3064 break;
3065 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
3066 toolMajor = in.toolMajor != 0
3067 ? in.toolMajor * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias
3068 : 0;
3069 if (mRawAxes.toolMinor.valid) {
3070 toolMinor = in.toolMinor != 0
3071 ? in.toolMinor * mLocked.toolSizeLinearScale
3072 + mLocked.toolSizeLinearBias
3073 : 0;
3074 } else {
3075 toolMinor = toolMajor;
3076 }
3077 break;
3078 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
3079 if (in.toolMajor != 0) {
3080 float diameter = sqrtf(in.toolMajor
3081 * mLocked.toolSizeAreaScale + mLocked.toolSizeAreaBias);
3082 toolMajor = diameter * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias;
3083 } else {
3084 toolMajor = 0;
3085 }
3086 toolMinor = toolMajor;
3087 break;
3088 default:
3089 toolMajor = 0;
3090 toolMinor = 0;
3091 break;
3092 }
3093
3094 if (mCalibration.haveToolSizeIsSummed && mCalibration.toolSizeIsSummed) {
3095 toolMajor /= currentPointerCount;
3096 toolMinor /= currentPointerCount;
3097 }
3098
3099 // Pressure
3100 float rawPressure;
3101 switch (mCalibration.pressureSource) {
3102 case Calibration::PRESSURE_SOURCE_PRESSURE:
3103 rawPressure = in.pressure;
3104 break;
3105 case Calibration::PRESSURE_SOURCE_TOUCH:
3106 rawPressure = in.touchMajor;
3107 break;
3108 default:
3109 rawPressure = 0;
3110 }
3111
3112 float pressure;
3113 switch (mCalibration.pressureCalibration) {
3114 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3115 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3116 pressure = rawPressure * mLocked.pressureScale;
3117 break;
3118 default:
3119 pressure = 1;
3120 break;
3121 }
3122
3123 // TouchMajor and TouchMinor
3124 float touchMajor, touchMinor;
3125 switch (mCalibration.touchSizeCalibration) {
3126 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
3127 touchMajor = in.touchMajor * mLocked.geometricScale;
3128 if (mRawAxes.touchMinor.valid) {
3129 touchMinor = in.touchMinor * mLocked.geometricScale;
3130 } else {
3131 touchMinor = touchMajor;
3132 }
3133 break;
3134 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
3135 touchMajor = toolMajor * pressure;
3136 touchMinor = toolMinor * pressure;
3137 break;
3138 default:
3139 touchMajor = 0;
3140 touchMinor = 0;
3141 break;
3142 }
3143
3144 if (touchMajor > toolMajor) {
3145 touchMajor = toolMajor;
3146 }
3147 if (touchMinor > toolMinor) {
3148 touchMinor = toolMinor;
3149 }
3150
3151 // Size
3152 float size;
3153 switch (mCalibration.sizeCalibration) {
3154 case Calibration::SIZE_CALIBRATION_NORMALIZED: {
3155 float rawSize = mRawAxes.toolMinor.valid
3156 ? avg(in.toolMajor, in.toolMinor)
3157 : in.toolMajor;
3158 size = rawSize * mLocked.sizeScale;
3159 break;
3160 }
3161 default:
3162 size = 0;
3163 break;
3164 }
3165
3166 // Orientation
3167 float orientation;
3168 switch (mCalibration.orientationCalibration) {
3169 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3170 orientation = in.orientation * mLocked.orientationScale;
3171 break;
3172 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
3173 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
3174 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
3175 if (c1 != 0 || c2 != 0) {
3176 orientation = atan2f(c1, c2) * 0.5f;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003177 float scale = 1.0f + hypotf(c1, c2) / 16.0f;
Jeff Brown96ad3972011-03-09 17:39:48 -08003178 touchMajor *= scale;
3179 touchMinor /= scale;
3180 toolMajor *= scale;
3181 toolMinor /= scale;
3182 } else {
3183 orientation = 0;
3184 }
3185 break;
3186 }
3187 default:
3188 orientation = 0;
3189 }
3190
3191 // X and Y
3192 // Adjust coords for surface orientation.
3193 float x, y;
3194 switch (mLocked.surfaceOrientation) {
3195 case DISPLAY_ORIENTATION_90:
3196 x = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3197 y = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3198 orientation -= M_PI_2;
3199 if (orientation < - M_PI_2) {
3200 orientation += M_PI;
3201 }
3202 break;
3203 case DISPLAY_ORIENTATION_180:
3204 x = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3205 y = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3206 break;
3207 case DISPLAY_ORIENTATION_270:
3208 x = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3209 y = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3210 orientation += M_PI_2;
3211 if (orientation > M_PI_2) {
3212 orientation -= M_PI;
3213 }
3214 break;
3215 default:
3216 x = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3217 y = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3218 break;
3219 }
3220
3221 // Write output coords.
3222 PointerCoords& out = mCurrentTouchCoords[i];
3223 out.clear();
3224 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3225 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3226 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
3227 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
3228 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
3229 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
3230 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
3231 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
3232 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
3233 }
3234
3235 // Check edge flags by looking only at the first pointer since the flags are
3236 // global to the event.
3237 *outEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3238 if (lastPointerCount == 0 && currentPointerCount > 0) {
3239 const PointerData& in = mCurrentTouch.pointers[0];
3240
3241 if (in.x <= mRawAxes.x.minValue) {
3242 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_LEFT,
3243 mLocked.surfaceOrientation);
3244 } else if (in.x >= mRawAxes.x.maxValue) {
3245 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_RIGHT,
3246 mLocked.surfaceOrientation);
3247 }
3248 if (in.y <= mRawAxes.y.minValue) {
3249 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_TOP,
3250 mLocked.surfaceOrientation);
3251 } else if (in.y >= mRawAxes.y.maxValue) {
3252 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_BOTTOM,
3253 mLocked.surfaceOrientation);
3254 }
3255 }
3256
3257 *outXPrecision = mLocked.orientedXPrecision;
3258 *outYPrecision = mLocked.orientedYPrecision;
3259}
3260
Jeff Brown325bd072011-04-19 21:20:10 -07003261void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
3262 bool isTimeout) {
Jeff Brown86ea1f52011-04-12 22:39:53 -07003263 // Switch pointer presentation.
3264 mPointerController->setPresentation(
3265 mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
3266 ? PointerControllerInterface::PRESENTATION_SPOT
3267 : PointerControllerInterface::PRESENTATION_POINTER);
3268
Jeff Brown96ad3972011-03-09 17:39:48 -08003269 // Update current gesture coordinates.
3270 bool cancelPreviousGesture, finishPreviousGesture;
Jeff Brown325bd072011-04-19 21:20:10 -07003271 bool sendEvents = preparePointerGestures(when,
3272 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
3273 if (!sendEvents) {
3274 return;
3275 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003276
Jeff Brown538881e2011-05-25 18:23:38 -07003277 // Show or hide the pointer if needed.
3278 switch (mPointerGesture.currentGestureMode) {
3279 case PointerGesture::NEUTRAL:
3280 case PointerGesture::QUIET:
3281 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
3282 && (mPointerGesture.lastGestureMode == PointerGesture::SWIPE
3283 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)) {
3284 // Remind the user of where the pointer is after finishing a gesture with spots.
3285 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
3286 }
3287 break;
3288 case PointerGesture::TAP:
3289 case PointerGesture::TAP_DRAG:
3290 case PointerGesture::BUTTON_CLICK_OR_DRAG:
3291 case PointerGesture::HOVER:
3292 case PointerGesture::PRESS:
3293 // Unfade the pointer when the current gesture manipulates the
3294 // area directly under the pointer.
3295 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
3296 break;
3297 case PointerGesture::SWIPE:
3298 case PointerGesture::FREEFORM:
3299 // Fade the pointer when the current gesture manipulates a different
3300 // area and there are spots to guide the user experience.
3301 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3302 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
3303 } else {
3304 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
3305 }
3306 break;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003307 }
3308
Jeff Brown96ad3972011-03-09 17:39:48 -08003309 // Send events!
3310 uint32_t metaState = getContext()->getGlobalMetaState();
3311
3312 // Update last coordinates of pointers that have moved so that we observe the new
3313 // pointer positions at the same time as other pointers that have just gone up.
Jeff Brown325bd072011-04-19 21:20:10 -07003314 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
3315 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
3316 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
Jeff Brown86ea1f52011-04-12 22:39:53 -07003317 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
Jeff Brown96ad3972011-03-09 17:39:48 -08003318 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
3319 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
3320 bool moveNeeded = false;
3321 if (down && !cancelPreviousGesture && !finishPreviousGesture
Jeff Brown86ea1f52011-04-12 22:39:53 -07003322 && !mPointerGesture.lastGestureIdBits.isEmpty()
3323 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003324 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
3325 & mPointerGesture.lastGestureIdBits.value);
3326 moveNeeded = updateMovedPointerCoords(
3327 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3328 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3329 movedGestureIdBits);
3330 }
3331
3332 // Send motion events for all pointers that went up or were canceled.
3333 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
3334 if (!dispatchedGestureIdBits.isEmpty()) {
3335 if (cancelPreviousGesture) {
3336 dispatchMotion(when, policyFlags, mPointerSource,
3337 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3338 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3339 dispatchedGestureIdBits, -1,
3340 0, 0, mPointerGesture.downTime);
3341
3342 dispatchedGestureIdBits.clear();
3343 } else {
3344 BitSet32 upGestureIdBits;
3345 if (finishPreviousGesture) {
3346 upGestureIdBits = dispatchedGestureIdBits;
3347 } else {
3348 upGestureIdBits.value = dispatchedGestureIdBits.value
3349 & ~mPointerGesture.currentGestureIdBits.value;
3350 }
3351 while (!upGestureIdBits.isEmpty()) {
3352 uint32_t id = upGestureIdBits.firstMarkedBit();
3353 upGestureIdBits.clearBit(id);
3354
3355 dispatchMotion(when, policyFlags, mPointerSource,
3356 AMOTION_EVENT_ACTION_POINTER_UP, 0,
3357 metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3358 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3359 dispatchedGestureIdBits, id,
3360 0, 0, mPointerGesture.downTime);
3361
3362 dispatchedGestureIdBits.clearBit(id);
3363 }
3364 }
3365 }
3366
3367 // Send motion events for all pointers that moved.
3368 if (moveNeeded) {
3369 dispatchMotion(when, policyFlags, mPointerSource,
3370 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3371 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3372 dispatchedGestureIdBits, -1,
3373 0, 0, mPointerGesture.downTime);
3374 }
3375
3376 // Send motion events for all pointers that went down.
3377 if (down) {
3378 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
3379 & ~dispatchedGestureIdBits.value);
3380 while (!downGestureIdBits.isEmpty()) {
3381 uint32_t id = downGestureIdBits.firstMarkedBit();
3382 downGestureIdBits.clearBit(id);
3383 dispatchedGestureIdBits.markBit(id);
3384
3385 int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3386 if (dispatchedGestureIdBits.count() == 1) {
3387 // First pointer is going down. Calculate edge flags and set down time.
3388 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3389 const PointerCoords& downCoords = mPointerGesture.currentGestureCoords[index];
3390 edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3391 downCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
3392 downCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3393 mPointerGesture.downTime = when;
3394 }
3395
3396 dispatchMotion(when, policyFlags, mPointerSource,
3397 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, edgeFlags,
3398 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3399 dispatchedGestureIdBits, id,
3400 0, 0, mPointerGesture.downTime);
3401 }
3402 }
3403
Jeff Brown96ad3972011-03-09 17:39:48 -08003404 // Send motion events for hover.
3405 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
3406 dispatchMotion(when, policyFlags, mPointerSource,
3407 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
3408 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3409 mPointerGesture.currentGestureIdBits, -1,
3410 0, 0, mPointerGesture.downTime);
3411 }
3412
3413 // Update state.
3414 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
3415 if (!down) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003416 mPointerGesture.lastGestureIdBits.clear();
3417 } else {
Jeff Brown96ad3972011-03-09 17:39:48 -08003418 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
3419 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
3420 uint32_t id = idBits.firstMarkedBit();
3421 idBits.clearBit(id);
3422 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3423 mPointerGesture.lastGestureCoords[index].copyFrom(
3424 mPointerGesture.currentGestureCoords[index]);
3425 mPointerGesture.lastGestureIdToIndex[id] = index;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003426 }
3427 }
3428}
3429
Jeff Brown325bd072011-04-19 21:20:10 -07003430bool TouchInputMapper::preparePointerGestures(nsecs_t when,
3431 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003432 *outCancelPreviousGesture = false;
3433 *outFinishPreviousGesture = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003434
Jeff Brown96ad3972011-03-09 17:39:48 -08003435 AutoMutex _l(mLock);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003436
Jeff Brown325bd072011-04-19 21:20:10 -07003437 // Handle TAP timeout.
3438 if (isTimeout) {
3439#if DEBUG_GESTURES
3440 LOGD("Gestures: Processing timeout");
3441#endif
3442
3443 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
3444 if (when <= mPointerGesture.tapUpTime + TAP_DRAG_INTERVAL) {
3445 // The tap/drag timeout has not yet expired.
3446 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime + TAP_DRAG_INTERVAL);
3447 } else {
3448 // The tap is finished.
3449#if DEBUG_GESTURES
3450 LOGD("Gestures: TAP finished");
3451#endif
3452 *outFinishPreviousGesture = true;
3453
3454 mPointerGesture.activeGestureId = -1;
3455 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
3456 mPointerGesture.currentGestureIdBits.clear();
3457
3458 mPointerController->setButtonState(0);
3459
3460 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3461 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_NEUTRAL;
3462 mPointerGesture.spotIdBits.clear();
3463 moveSpotsLocked();
3464 }
3465 return true;
3466 }
3467 }
3468
3469 // We did not handle this timeout.
3470 return false;
3471 }
3472
Jeff Brown96ad3972011-03-09 17:39:48 -08003473 // Update the velocity tracker.
3474 {
3475 VelocityTracker::Position positions[MAX_POINTERS];
3476 uint32_t count = 0;
3477 for (BitSet32 idBits(mCurrentTouch.idBits); !idBits.isEmpty(); count++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07003478 uint32_t id = idBits.firstMarkedBit();
3479 idBits.clearBit(id);
Jeff Brown96ad3972011-03-09 17:39:48 -08003480 uint32_t index = mCurrentTouch.idToIndex[id];
3481 positions[count].x = mCurrentTouch.pointers[index].x
3482 * mLocked.pointerGestureXMovementScale;
3483 positions[count].y = mCurrentTouch.pointers[index].y
3484 * mLocked.pointerGestureYMovementScale;
3485 }
3486 mPointerGesture.velocityTracker.addMovement(when, mCurrentTouch.idBits, positions);
3487 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003488
Jeff Brown96ad3972011-03-09 17:39:48 -08003489 // Pick a new active touch id if needed.
3490 // Choose an arbitrary pointer that just went down, if there is one.
3491 // Otherwise choose an arbitrary remaining pointer.
3492 // This guarantees we always have an active touch id when there is at least one pointer.
Jeff Brown86ea1f52011-04-12 22:39:53 -07003493 // We keep the same active touch id for as long as possible.
3494 bool activeTouchChanged = false;
3495 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
3496 int32_t activeTouchId = lastActiveTouchId;
3497 if (activeTouchId < 0) {
3498 if (!mCurrentTouch.idBits.isEmpty()) {
3499 activeTouchChanged = true;
3500 activeTouchId = mPointerGesture.activeTouchId = mCurrentTouch.idBits.firstMarkedBit();
3501 mPointerGesture.firstTouchTime = when;
Jeff Brown96ad3972011-03-09 17:39:48 -08003502 }
Jeff Brown86ea1f52011-04-12 22:39:53 -07003503 } else if (!mCurrentTouch.idBits.hasBit(activeTouchId)) {
3504 activeTouchChanged = true;
3505 if (!mCurrentTouch.idBits.isEmpty()) {
3506 activeTouchId = mPointerGesture.activeTouchId = mCurrentTouch.idBits.firstMarkedBit();
3507 } else {
3508 activeTouchId = mPointerGesture.activeTouchId = -1;
Jeff Brown96ad3972011-03-09 17:39:48 -08003509 }
3510 }
3511
3512 // Determine whether we are in quiet time.
Jeff Brown86ea1f52011-04-12 22:39:53 -07003513 bool isQuietTime = false;
3514 if (activeTouchId < 0) {
3515 mPointerGesture.resetQuietTime();
3516 } else {
3517 isQuietTime = when < mPointerGesture.quietTime + QUIET_INTERVAL;
3518 if (!isQuietTime) {
3519 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
3520 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
3521 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
3522 && mCurrentTouch.pointerCount < 2) {
3523 // Enter quiet time when exiting swipe or freeform state.
3524 // This is to prevent accidentally entering the hover state and flinging the
3525 // pointer when finishing a swipe and there is still one pointer left onscreen.
3526 isQuietTime = true;
Jeff Brown325bd072011-04-19 21:20:10 -07003527 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
Jeff Brown86ea1f52011-04-12 22:39:53 -07003528 && mCurrentTouch.pointerCount >= 2
3529 && !isPointerDown(mCurrentTouch.buttonState)) {
3530 // Enter quiet time when releasing the button and there are still two or more
3531 // fingers down. This may indicate that one finger was used to press the button
3532 // but it has not gone up yet.
3533 isQuietTime = true;
3534 }
3535 if (isQuietTime) {
3536 mPointerGesture.quietTime = when;
3537 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003538 }
3539 }
3540
3541 // Switch states based on button and pointer state.
3542 if (isQuietTime) {
3543 // Case 1: Quiet time. (QUIET)
3544#if DEBUG_GESTURES
3545 LOGD("Gestures: QUIET for next %0.3fms",
3546 (mPointerGesture.quietTime + QUIET_INTERVAL - when) * 0.000001f);
3547#endif
3548 *outFinishPreviousGesture = true;
3549
3550 mPointerGesture.activeGestureId = -1;
3551 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
Jeff Brown96ad3972011-03-09 17:39:48 -08003552 mPointerGesture.currentGestureIdBits.clear();
Jeff Brown86ea1f52011-04-12 22:39:53 -07003553
3554 mPointerController->setButtonState(0);
3555
3556 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3557 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_NEUTRAL;
3558 mPointerGesture.spotIdBits.clear();
3559 moveSpotsLocked();
3560 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003561 } else if (isPointerDown(mCurrentTouch.buttonState)) {
Jeff Brown325bd072011-04-19 21:20:10 -07003562 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
Jeff Brown96ad3972011-03-09 17:39:48 -08003563 // The pointer follows the active touch point.
3564 // Emit DOWN, MOVE, UP events at the pointer location.
3565 //
3566 // Only the active touch matters; other fingers are ignored. This policy helps
3567 // to handle the case where the user places a second finger on the touch pad
3568 // to apply the necessary force to depress an integrated button below the surface.
3569 // We don't want the second finger to be delivered to applications.
3570 //
3571 // For this to work well, we need to make sure to track the pointer that is really
3572 // active. If the user first puts one finger down to click then adds another
3573 // finger to drag then the active pointer should switch to the finger that is
3574 // being dragged.
3575#if DEBUG_GESTURES
Jeff Brown325bd072011-04-19 21:20:10 -07003576 LOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
Jeff Brown96ad3972011-03-09 17:39:48 -08003577 "currentTouchPointerCount=%d", activeTouchId, mCurrentTouch.pointerCount);
3578#endif
3579 // Reset state when just starting.
Jeff Brown325bd072011-04-19 21:20:10 -07003580 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003581 *outFinishPreviousGesture = true;
3582 mPointerGesture.activeGestureId = 0;
3583 }
3584
3585 // Switch pointers if needed.
3586 // Find the fastest pointer and follow it.
3587 if (activeTouchId >= 0) {
3588 if (mCurrentTouch.pointerCount > 1) {
3589 int32_t bestId = -1;
3590 float bestSpeed = DRAG_MIN_SWITCH_SPEED;
3591 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3592 uint32_t id = mCurrentTouch.pointers[i].id;
3593 float vx, vy;
3594 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
Jeff Brown86ea1f52011-04-12 22:39:53 -07003595 float speed = hypotf(vx, vy);
Jeff Brown96ad3972011-03-09 17:39:48 -08003596 if (speed > bestSpeed) {
3597 bestId = id;
3598 bestSpeed = speed;
3599 }
3600 }
Jeff Brown8d608662010-08-30 03:02:23 -07003601 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003602 if (bestId >= 0 && bestId != activeTouchId) {
3603 mPointerGesture.activeTouchId = activeTouchId = bestId;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003604 activeTouchChanged = true;
Jeff Brown96ad3972011-03-09 17:39:48 -08003605#if DEBUG_GESTURES
Jeff Brown325bd072011-04-19 21:20:10 -07003606 LOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
Jeff Brown96ad3972011-03-09 17:39:48 -08003607 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
3608#endif
Jeff Brown8d608662010-08-30 03:02:23 -07003609 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003610 }
3611
Jeff Brown96ad3972011-03-09 17:39:48 -08003612 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3613 const PointerData& currentPointer =
3614 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3615 const PointerData& lastPointer =
3616 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3617 float deltaX = (currentPointer.x - lastPointer.x)
3618 * mLocked.pointerGestureXMovementScale;
3619 float deltaY = (currentPointer.y - lastPointer.y)
3620 * mLocked.pointerGestureYMovementScale;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003621
3622 // Move the pointer using a relative motion.
3623 // When using spots, the click will occur at the position of the anchor
3624 // spot and all other spots will move there.
Jeff Brown96ad3972011-03-09 17:39:48 -08003625 mPointerController->move(deltaX, deltaY);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003626 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003627 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003628
Jeff Brown96ad3972011-03-09 17:39:48 -08003629 float x, y;
3630 mPointerController->getPosition(&x, &y);
Jeff Brown91c69ab2011-02-14 17:03:18 -08003631
Jeff Brown325bd072011-04-19 21:20:10 -07003632 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
Jeff Brown96ad3972011-03-09 17:39:48 -08003633 mPointerGesture.currentGestureIdBits.clear();
3634 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3635 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3636 mPointerGesture.currentGestureCoords[0].clear();
3637 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3638 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3639 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown86ea1f52011-04-12 22:39:53 -07003640
3641 mPointerController->setButtonState(BUTTON_STATE_PRIMARY);
3642
3643 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3644 if (activeTouchId >= 0) {
3645 // Collapse all spots into one point at the pointer location.
3646 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_BUTTON_DRAG;
3647 mPointerGesture.spotIdBits.clear();
3648 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3649 uint32_t id = mCurrentTouch.pointers[i].id;
3650 mPointerGesture.spotIdBits.markBit(id);
3651 mPointerGesture.spotIdToIndex[id] = i;
3652 mPointerGesture.spotCoords[i] = mPointerGesture.currentGestureCoords[0];
3653 }
3654 } else {
3655 // No fingers. Generate a spot at the pointer location so the
3656 // anchor appears to be pressed.
3657 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_BUTTON_CLICK;
3658 mPointerGesture.spotIdBits.clear();
3659 mPointerGesture.spotIdBits.markBit(0);
3660 mPointerGesture.spotIdToIndex[0] = 0;
3661 mPointerGesture.spotCoords[0] = mPointerGesture.currentGestureCoords[0];
3662 }
3663 moveSpotsLocked();
3664 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003665 } else if (mCurrentTouch.pointerCount == 0) {
3666 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
3667 *outFinishPreviousGesture = true;
3668
Jeff Brown325bd072011-04-19 21:20:10 -07003669 // Watch for taps coming out of HOVER or TAP_DRAG mode.
Jeff Brown96ad3972011-03-09 17:39:48 -08003670 bool tapped = false;
Jeff Brown325bd072011-04-19 21:20:10 -07003671 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
3672 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
Jeff Brown86ea1f52011-04-12 22:39:53 -07003673 && mLastTouch.pointerCount == 1) {
Jeff Brown325bd072011-04-19 21:20:10 -07003674 if (when <= mPointerGesture.tapDownTime + TAP_INTERVAL) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003675 float x, y;
3676 mPointerController->getPosition(&x, &y);
Jeff Brown86ea1f52011-04-12 22:39:53 -07003677 if (fabs(x - mPointerGesture.tapX) <= TAP_SLOP
3678 && fabs(y - mPointerGesture.tapY) <= TAP_SLOP) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003679#if DEBUG_GESTURES
3680 LOGD("Gestures: TAP");
3681#endif
Jeff Brown325bd072011-04-19 21:20:10 -07003682
3683 mPointerGesture.tapUpTime = when;
3684 getContext()->requestTimeoutAtTime(when + TAP_DRAG_INTERVAL);
3685
Jeff Brown96ad3972011-03-09 17:39:48 -08003686 mPointerGesture.activeGestureId = 0;
3687 mPointerGesture.currentGestureMode = PointerGesture::TAP;
Jeff Brown96ad3972011-03-09 17:39:48 -08003688 mPointerGesture.currentGestureIdBits.clear();
3689 mPointerGesture.currentGestureIdBits.markBit(
3690 mPointerGesture.activeGestureId);
3691 mPointerGesture.currentGestureIdToIndex[
3692 mPointerGesture.activeGestureId] = 0;
3693 mPointerGesture.currentGestureCoords[0].clear();
3694 mPointerGesture.currentGestureCoords[0].setAxisValue(
Jeff Brown86ea1f52011-04-12 22:39:53 -07003695 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
Jeff Brown96ad3972011-03-09 17:39:48 -08003696 mPointerGesture.currentGestureCoords[0].setAxisValue(
Jeff Brown86ea1f52011-04-12 22:39:53 -07003697 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
Jeff Brown96ad3972011-03-09 17:39:48 -08003698 mPointerGesture.currentGestureCoords[0].setAxisValue(
3699 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown86ea1f52011-04-12 22:39:53 -07003700
3701 mPointerController->setButtonState(BUTTON_STATE_PRIMARY);
Jeff Brown86ea1f52011-04-12 22:39:53 -07003702
3703 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3704 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_TAP;
3705 mPointerGesture.spotIdBits.clear();
3706 mPointerGesture.spotIdBits.markBit(lastActiveTouchId);
3707 mPointerGesture.spotIdToIndex[lastActiveTouchId] = 0;
3708 mPointerGesture.spotCoords[0] = mPointerGesture.currentGestureCoords[0];
3709 moveSpotsLocked();
3710 }
3711
Jeff Brown96ad3972011-03-09 17:39:48 -08003712 tapped = true;
3713 } else {
3714#if DEBUG_GESTURES
3715 LOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
Jeff Brown86ea1f52011-04-12 22:39:53 -07003716 x - mPointerGesture.tapX,
3717 y - mPointerGesture.tapY);
Jeff Brown96ad3972011-03-09 17:39:48 -08003718#endif
3719 }
3720 } else {
3721#if DEBUG_GESTURES
Jeff Brown325bd072011-04-19 21:20:10 -07003722 LOGD("Gestures: Not a TAP, %0.3fms since down",
3723 (when - mPointerGesture.tapDownTime) * 0.000001f);
Jeff Brown96ad3972011-03-09 17:39:48 -08003724#endif
Jeff Brown6328cdc2010-07-29 18:18:33 -07003725 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003726 }
Jeff Brown86ea1f52011-04-12 22:39:53 -07003727
Jeff Brown96ad3972011-03-09 17:39:48 -08003728 if (!tapped) {
3729#if DEBUG_GESTURES
3730 LOGD("Gestures: NEUTRAL");
3731#endif
3732 mPointerGesture.activeGestureId = -1;
3733 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
Jeff Brown96ad3972011-03-09 17:39:48 -08003734 mPointerGesture.currentGestureIdBits.clear();
Jeff Brown86ea1f52011-04-12 22:39:53 -07003735
3736 mPointerController->setButtonState(0);
3737
3738 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3739 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_NEUTRAL;
3740 mPointerGesture.spotIdBits.clear();
3741 moveSpotsLocked();
3742 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003743 }
3744 } else if (mCurrentTouch.pointerCount == 1) {
Jeff Brown325bd072011-04-19 21:20:10 -07003745 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
Jeff Brown96ad3972011-03-09 17:39:48 -08003746 // The pointer follows the active touch point.
Jeff Brown325bd072011-04-19 21:20:10 -07003747 // When in HOVER, emit HOVER_MOVE events at the pointer location.
3748 // When in TAP_DRAG, emit MOVE events at the pointer location.
3749 LOG_ASSERT(activeTouchId >= 0);
Jeff Brown96ad3972011-03-09 17:39:48 -08003750
Jeff Brown325bd072011-04-19 21:20:10 -07003751 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
3752 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
3753 if (when <= mPointerGesture.tapUpTime + TAP_DRAG_INTERVAL) {
3754 float x, y;
3755 mPointerController->getPosition(&x, &y);
3756 if (fabs(x - mPointerGesture.tapX) <= TAP_SLOP
3757 && fabs(y - mPointerGesture.tapY) <= TAP_SLOP) {
3758 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
3759 } else {
Jeff Brown96ad3972011-03-09 17:39:48 -08003760#if DEBUG_GESTURES
Jeff Brown325bd072011-04-19 21:20:10 -07003761 LOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3762 x - mPointerGesture.tapX,
3763 y - mPointerGesture.tapY);
Jeff Brown96ad3972011-03-09 17:39:48 -08003764#endif
Jeff Brown325bd072011-04-19 21:20:10 -07003765 }
3766 } else {
3767#if DEBUG_GESTURES
3768 LOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
3769 (when - mPointerGesture.tapUpTime) * 0.000001f);
3770#endif
3771 }
3772 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
3773 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
3774 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003775
3776 if (mLastTouch.idBits.hasBit(activeTouchId)) {
3777 const PointerData& currentPointer =
3778 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3779 const PointerData& lastPointer =
3780 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3781 float deltaX = (currentPointer.x - lastPointer.x)
3782 * mLocked.pointerGestureXMovementScale;
3783 float deltaY = (currentPointer.y - lastPointer.y)
3784 * mLocked.pointerGestureYMovementScale;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003785
3786 // Move the pointer using a relative motion.
Jeff Brown325bd072011-04-19 21:20:10 -07003787 // When using spots, the hover or drag will occur at the position of the anchor spot.
Jeff Brown96ad3972011-03-09 17:39:48 -08003788 mPointerController->move(deltaX, deltaY);
3789 }
3790
Jeff Brown325bd072011-04-19 21:20:10 -07003791 bool down;
3792 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
3793#if DEBUG_GESTURES
3794 LOGD("Gestures: TAP_DRAG");
3795#endif
3796 down = true;
3797 } else {
3798#if DEBUG_GESTURES
3799 LOGD("Gestures: HOVER");
3800#endif
3801 *outFinishPreviousGesture = true;
3802 mPointerGesture.activeGestureId = 0;
3803 down = false;
3804 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003805
3806 float x, y;
3807 mPointerController->getPosition(&x, &y);
3808
Jeff Brown96ad3972011-03-09 17:39:48 -08003809 mPointerGesture.currentGestureIdBits.clear();
3810 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3811 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3812 mPointerGesture.currentGestureCoords[0].clear();
3813 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3814 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jeff Brown325bd072011-04-19 21:20:10 -07003815 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3816 down ? 1.0f : 0.0f);
3817
3818 mPointerController->setButtonState(down ? BUTTON_STATE_PRIMARY : 0);
Jeff Brown96ad3972011-03-09 17:39:48 -08003819
3820 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
Jeff Brown325bd072011-04-19 21:20:10 -07003821 mPointerGesture.resetTap();
3822 mPointerGesture.tapDownTime = when;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003823 mPointerGesture.tapX = x;
3824 mPointerGesture.tapY = y;
3825 }
3826
Jeff Brown86ea1f52011-04-12 22:39:53 -07003827 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
Jeff Brown325bd072011-04-19 21:20:10 -07003828 mPointerGesture.spotGesture = down ? PointerControllerInterface::SPOT_GESTURE_DRAG
3829 : PointerControllerInterface::SPOT_GESTURE_HOVER;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003830 mPointerGesture.spotIdBits.clear();
3831 mPointerGesture.spotIdBits.markBit(activeTouchId);
3832 mPointerGesture.spotIdToIndex[activeTouchId] = 0;
3833 mPointerGesture.spotCoords[0] = mPointerGesture.currentGestureCoords[0];
3834 moveSpotsLocked();
Jeff Brown96ad3972011-03-09 17:39:48 -08003835 }
3836 } else {
Jeff Brown86ea1f52011-04-12 22:39:53 -07003837 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3838 // We need to provide feedback for each finger that goes down so we cannot wait
3839 // for the fingers to move before deciding what to do.
Jeff Brown96ad3972011-03-09 17:39:48 -08003840 //
Jeff Brown86ea1f52011-04-12 22:39:53 -07003841 // The ambiguous case is deciding what to do when there are two fingers down but they
3842 // have not moved enough to determine whether they are part of a drag or part of a
3843 // freeform gesture, or just a press or long-press at the pointer location.
3844 //
3845 // When there are two fingers we start with the PRESS hypothesis and we generate a
3846 // down at the pointer location.
3847 //
3848 // When the two fingers move enough or when additional fingers are added, we make
3849 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3850 LOG_ASSERT(activeTouchId >= 0);
Jeff Brown96ad3972011-03-09 17:39:48 -08003851
Jeff Brown86ea1f52011-04-12 22:39:53 -07003852 bool needReference = false;
3853 bool settled = when >= mPointerGesture.firstTouchTime + MULTITOUCH_SETTLE_INTERVAL;
3854 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
Jeff Brown96ad3972011-03-09 17:39:48 -08003855 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
3856 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
Jeff Brown96ad3972011-03-09 17:39:48 -08003857 *outFinishPreviousGesture = true;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003858 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
3859 mPointerGesture.activeGestureId = 0;
Jeff Brown538881e2011-05-25 18:23:38 -07003860 mPointerGesture.referenceIdBits.clear();
Jeff Brown96ad3972011-03-09 17:39:48 -08003861
Jeff Brown86ea1f52011-04-12 22:39:53 -07003862 if (settled && mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
3863 && mLastTouch.idBits.hasBit(mPointerGesture.activeTouchId)) {
3864 // The spot is already visible and has settled, use it as the reference point
3865 // for the gesture. Other spots will be positioned relative to this one.
3866#if DEBUG_GESTURES
3867 LOGD("Gestures: Using active spot as reference for MULTITOUCH, "
3868 "settle time expired %0.3fms ago",
3869 (when - mPointerGesture.firstTouchTime - MULTITOUCH_SETTLE_INTERVAL)
3870 * 0.000001f);
3871#endif
3872 const PointerData& d = mLastTouch.pointers[mLastTouch.idToIndex[
3873 mPointerGesture.activeTouchId]];
3874 mPointerGesture.referenceTouchX = d.x;
3875 mPointerGesture.referenceTouchY = d.y;
3876 const PointerCoords& c = mPointerGesture.spotCoords[mPointerGesture.spotIdToIndex[
3877 mPointerGesture.activeTouchId]];
3878 mPointerGesture.referenceGestureX = c.getAxisValue(AMOTION_EVENT_AXIS_X);
3879 mPointerGesture.referenceGestureY = c.getAxisValue(AMOTION_EVENT_AXIS_Y);
3880 } else {
3881#if DEBUG_GESTURES
3882 LOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3883 "settle time remaining %0.3fms",
3884 (mPointerGesture.firstTouchTime + MULTITOUCH_SETTLE_INTERVAL - when)
3885 * 0.000001f);
3886#endif
3887 needReference = true;
Jeff Brown96ad3972011-03-09 17:39:48 -08003888 }
Jeff Brown86ea1f52011-04-12 22:39:53 -07003889 } else if (!settled && mCurrentTouch.pointerCount > mLastTouch.pointerCount) {
3890 // Additional pointers have gone down but not yet settled.
3891 // Reset the gesture.
3892#if DEBUG_GESTURES
3893 LOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3894 "settle time remaining %0.3fms",
3895 (mPointerGesture.firstTouchTime + MULTITOUCH_SETTLE_INTERVAL - when)
3896 * 0.000001f);
3897#endif
3898 *outCancelPreviousGesture = true;
3899 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
3900 mPointerGesture.activeGestureId = 0;
Jeff Brown96ad3972011-03-09 17:39:48 -08003901 } else {
Jeff Brown86ea1f52011-04-12 22:39:53 -07003902 // Continue previous gesture.
Jeff Brown96ad3972011-03-09 17:39:48 -08003903 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3904 }
3905
Jeff Brown86ea1f52011-04-12 22:39:53 -07003906 if (needReference) {
3907 // Use the centroid and pointer location as the reference points for the gesture.
3908 mCurrentTouch.getCentroid(&mPointerGesture.referenceTouchX,
3909 &mPointerGesture.referenceTouchY);
3910 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3911 &mPointerGesture.referenceGestureY);
3912 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003913
Jeff Brown86ea1f52011-04-12 22:39:53 -07003914 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
3915 float d;
3916 if (mCurrentTouch.pointerCount > 2) {
3917 // There are more than two pointers, switch to FREEFORM.
3918#if DEBUG_GESTURES
3919 LOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3920 mCurrentTouch.pointerCount);
3921#endif
3922 *outCancelPreviousGesture = true;
Jeff Brown96ad3972011-03-09 17:39:48 -08003923 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003924 } else if (((d = distance(
3925 mCurrentTouch.pointers[0].x, mCurrentTouch.pointers[0].y,
3926 mCurrentTouch.pointers[1].x, mCurrentTouch.pointers[1].y))
3927 > mLocked.pointerGestureMaxSwipeWidth)) {
3928 // There are two pointers but they are too far apart, switch to FREEFORM.
3929#if DEBUG_GESTURES
3930 LOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3931 d, mLocked.pointerGestureMaxSwipeWidth);
3932#endif
3933 *outCancelPreviousGesture = true;
3934 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
3935 } else {
3936 // There are two pointers. Wait for both pointers to start moving
3937 // before deciding whether this is a SWIPE or FREEFORM gesture.
3938 uint32_t id1 = mCurrentTouch.pointers[0].id;
3939 uint32_t id2 = mCurrentTouch.pointers[1].id;
Jeff Brown96ad3972011-03-09 17:39:48 -08003940
Jeff Brown86ea1f52011-04-12 22:39:53 -07003941 float vx1, vy1, vx2, vy2;
3942 mPointerGesture.velocityTracker.getVelocity(id1, &vx1, &vy1);
3943 mPointerGesture.velocityTracker.getVelocity(id2, &vx2, &vy2);
Jeff Brown96ad3972011-03-09 17:39:48 -08003944
Jeff Brown86ea1f52011-04-12 22:39:53 -07003945 float speed1 = hypotf(vx1, vy1);
3946 float speed2 = hypotf(vx2, vy2);
3947 if (speed1 >= MULTITOUCH_MIN_SPEED && speed2 >= MULTITOUCH_MIN_SPEED) {
3948 // Calculate the dot product of the velocity vectors.
Jeff Brown96ad3972011-03-09 17:39:48 -08003949 // When the vectors are oriented in approximately the same direction,
3950 // the angle betweeen them is near zero and the cosine of the angle
3951 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
Jeff Brown86ea1f52011-04-12 22:39:53 -07003952 float dot = vx1 * vx2 + vy1 * vy2;
3953 float cosine = dot / (speed1 * speed2); // denominator always > 0
3954 if (cosine >= SWIPE_TRANSITION_ANGLE_COSINE) {
3955 // Pointers are moving in the same direction. Switch to SWIPE.
3956#if DEBUG_GESTURES
3957 LOGD("Gestures: PRESS transitioned to SWIPE, "
3958 "speed1 %0.3f >= %0.3f, speed2 %0.3f >= %0.3f, "
3959 "cosine %0.3f >= %0.3f",
3960 speed1, MULTITOUCH_MIN_SPEED, speed2, MULTITOUCH_MIN_SPEED,
3961 cosine, SWIPE_TRANSITION_ANGLE_COSINE);
3962#endif
Jeff Brown96ad3972011-03-09 17:39:48 -08003963 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
Jeff Brown86ea1f52011-04-12 22:39:53 -07003964 } else {
3965 // Pointers are moving in different directions. Switch to FREEFORM.
3966#if DEBUG_GESTURES
3967 LOGD("Gestures: PRESS transitioned to FREEFORM, "
3968 "speed1 %0.3f >= %0.3f, speed2 %0.3f >= %0.3f, "
3969 "cosine %0.3f < %0.3f",
3970 speed1, MULTITOUCH_MIN_SPEED, speed2, MULTITOUCH_MIN_SPEED,
3971 cosine, SWIPE_TRANSITION_ANGLE_COSINE);
3972#endif
3973 *outCancelPreviousGesture = true;
3974 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown96ad3972011-03-09 17:39:48 -08003975 }
3976 }
Jeff Brown96ad3972011-03-09 17:39:48 -08003977 }
3978 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
Jeff Brown86ea1f52011-04-12 22:39:53 -07003979 // Switch from SWIPE to FREEFORM if additional pointers go down.
3980 // Cancel previous gesture.
3981 if (mCurrentTouch.pointerCount > 2) {
3982#if DEBUG_GESTURES
3983 LOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3984 mCurrentTouch.pointerCount);
3985#endif
Jeff Brown96ad3972011-03-09 17:39:48 -08003986 *outCancelPreviousGesture = true;
3987 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003988 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003989 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003990
Jeff Brown538881e2011-05-25 18:23:38 -07003991 // Clear the reference deltas for fingers not yet included in the reference calculation.
3992 for (BitSet32 idBits(mCurrentTouch.idBits.value & ~mPointerGesture.referenceIdBits.value);
3993 !idBits.isEmpty(); ) {
3994 uint32_t id = idBits.firstMarkedBit();
3995 idBits.clearBit(id);
3996
3997 mPointerGesture.referenceDeltas[id].dx = 0;
3998 mPointerGesture.referenceDeltas[id].dy = 0;
3999 }
4000 mPointerGesture.referenceIdBits = mCurrentTouch.idBits;
4001
Jeff Brown86ea1f52011-04-12 22:39:53 -07004002 // Move the reference points based on the overall group motion of the fingers.
4003 // The objective is to calculate a vector delta that is common to the movement
4004 // of all fingers.
4005 BitSet32 commonIdBits(mLastTouch.idBits.value & mCurrentTouch.idBits.value);
4006 if (!commonIdBits.isEmpty()) {
4007 float commonDeltaX = 0, commonDeltaY = 0;
4008 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
4009 bool first = (idBits == commonIdBits);
4010 uint32_t id = idBits.firstMarkedBit();
4011 idBits.clearBit(id);
4012
4013 const PointerData& cpd = mCurrentTouch.pointers[mCurrentTouch.idToIndex[id]];
4014 const PointerData& lpd = mLastTouch.pointers[mLastTouch.idToIndex[id]];
Jeff Brown538881e2011-05-25 18:23:38 -07004015 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
4016 delta.dx += cpd.x - lpd.x;
4017 delta.dy += cpd.y - lpd.y;
Jeff Brown86ea1f52011-04-12 22:39:53 -07004018
4019 if (first) {
Jeff Brown538881e2011-05-25 18:23:38 -07004020 commonDeltaX = delta.dx;
4021 commonDeltaY = delta.dy;
Jeff Brown86ea1f52011-04-12 22:39:53 -07004022 } else {
Jeff Brown538881e2011-05-25 18:23:38 -07004023 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
4024 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
Jeff Brown86ea1f52011-04-12 22:39:53 -07004025 }
4026 }
4027
Jeff Brown538881e2011-05-25 18:23:38 -07004028 if (commonDeltaX || commonDeltaY) {
4029 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
4030 uint32_t id = idBits.firstMarkedBit();
4031 idBits.clearBit(id);
4032
4033 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
4034 delta.dx = 0;
4035 delta.dy = 0;
4036 }
4037
4038 mPointerGesture.referenceTouchX += commonDeltaX;
4039 mPointerGesture.referenceTouchY += commonDeltaY;
4040 mPointerGesture.referenceGestureX +=
4041 commonDeltaX * mLocked.pointerGestureXMovementScale;
4042 mPointerGesture.referenceGestureY +=
4043 commonDeltaY * mLocked.pointerGestureYMovementScale;
4044 clampPositionUsingPointerBounds(mPointerController,
4045 &mPointerGesture.referenceGestureX,
4046 &mPointerGesture.referenceGestureY);
4047 }
Jeff Brown86ea1f52011-04-12 22:39:53 -07004048 }
4049
4050 // Report gestures.
4051 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
4052 // PRESS mode.
Jeff Brown96ad3972011-03-09 17:39:48 -08004053#if DEBUG_GESTURES
Jeff Brown86ea1f52011-04-12 22:39:53 -07004054 LOGD("Gestures: PRESS activeTouchId=%d,"
Jeff Brown96ad3972011-03-09 17:39:48 -08004055 "activeGestureId=%d, currentTouchPointerCount=%d",
Jeff Brown86ea1f52011-04-12 22:39:53 -07004056 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
Jeff Brown96ad3972011-03-09 17:39:48 -08004057#endif
Jeff Brown86ea1f52011-04-12 22:39:53 -07004058 LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
Jeff Brown96ad3972011-03-09 17:39:48 -08004059
Jeff Brown96ad3972011-03-09 17:39:48 -08004060 mPointerGesture.currentGestureIdBits.clear();
4061 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
4062 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
4063 mPointerGesture.currentGestureCoords[0].clear();
Jeff Brown86ea1f52011-04-12 22:39:53 -07004064 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4065 mPointerGesture.referenceGestureX);
4066 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
4067 mPointerGesture.referenceGestureY);
Jeff Brown96ad3972011-03-09 17:39:48 -08004068 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown86ea1f52011-04-12 22:39:53 -07004069
4070 mPointerController->setButtonState(BUTTON_STATE_PRIMARY);
4071
4072 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4073 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_PRESS;
4074 }
4075 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
4076 // SWIPE mode.
4077#if DEBUG_GESTURES
4078 LOGD("Gestures: SWIPE activeTouchId=%d,"
4079 "activeGestureId=%d, currentTouchPointerCount=%d",
4080 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
4081#endif
4082 assert(mPointerGesture.activeGestureId >= 0);
4083
4084 mPointerGesture.currentGestureIdBits.clear();
4085 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
4086 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
4087 mPointerGesture.currentGestureCoords[0].clear();
4088 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4089 mPointerGesture.referenceGestureX);
4090 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
4091 mPointerGesture.referenceGestureY);
4092 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4093
4094 mPointerController->setButtonState(0); // touch is not actually following the pointer
4095
4096 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4097 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_SWIPE;
4098 }
Jeff Brown96ad3972011-03-09 17:39:48 -08004099 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
4100 // FREEFORM mode.
4101#if DEBUG_GESTURES
4102 LOGD("Gestures: FREEFORM activeTouchId=%d,"
4103 "activeGestureId=%d, currentTouchPointerCount=%d",
Jeff Brown86ea1f52011-04-12 22:39:53 -07004104 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
Jeff Brown96ad3972011-03-09 17:39:48 -08004105#endif
4106 assert(mPointerGesture.activeGestureId >= 0);
4107
Jeff Brown96ad3972011-03-09 17:39:48 -08004108 mPointerGesture.currentGestureIdBits.clear();
4109
4110 BitSet32 mappedTouchIdBits;
4111 BitSet32 usedGestureIdBits;
4112 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
4113 // Initially, assign the active gesture id to the active touch point
4114 // if there is one. No other touch id bits are mapped yet.
4115 if (!*outCancelPreviousGesture) {
4116 mappedTouchIdBits.markBit(activeTouchId);
4117 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
4118 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
4119 mPointerGesture.activeGestureId;
4120 } else {
4121 mPointerGesture.activeGestureId = -1;
4122 }
4123 } else {
4124 // Otherwise, assume we mapped all touches from the previous frame.
4125 // Reuse all mappings that are still applicable.
4126 mappedTouchIdBits.value = mLastTouch.idBits.value & mCurrentTouch.idBits.value;
4127 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
4128
4129 // Check whether we need to choose a new active gesture id because the
4130 // current went went up.
4131 for (BitSet32 upTouchIdBits(mLastTouch.idBits.value & ~mCurrentTouch.idBits.value);
4132 !upTouchIdBits.isEmpty(); ) {
4133 uint32_t upTouchId = upTouchIdBits.firstMarkedBit();
4134 upTouchIdBits.clearBit(upTouchId);
4135 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
4136 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
4137 mPointerGesture.activeGestureId = -1;
4138 break;
4139 }
4140 }
4141 }
4142
4143#if DEBUG_GESTURES
4144 LOGD("Gestures: FREEFORM follow up "
4145 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
4146 "activeGestureId=%d",
4147 mappedTouchIdBits.value, usedGestureIdBits.value,
4148 mPointerGesture.activeGestureId);
4149#endif
4150
Jeff Brown86ea1f52011-04-12 22:39:53 -07004151 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
Jeff Brown96ad3972011-03-09 17:39:48 -08004152 uint32_t touchId = mCurrentTouch.pointers[i].id;
4153 uint32_t gestureId;
4154 if (!mappedTouchIdBits.hasBit(touchId)) {
4155 gestureId = usedGestureIdBits.firstUnmarkedBit();
4156 usedGestureIdBits.markBit(gestureId);
4157 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
4158#if DEBUG_GESTURES
4159 LOGD("Gestures: FREEFORM "
4160 "new mapping for touch id %d -> gesture id %d",
4161 touchId, gestureId);
4162#endif
4163 } else {
4164 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
4165#if DEBUG_GESTURES
4166 LOGD("Gestures: FREEFORM "
4167 "existing mapping for touch id %d -> gesture id %d",
4168 touchId, gestureId);
4169#endif
4170 }
4171 mPointerGesture.currentGestureIdBits.markBit(gestureId);
4172 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
4173
Jeff Brown86ea1f52011-04-12 22:39:53 -07004174 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.referenceTouchX)
4175 * mLocked.pointerGestureXZoomScale + mPointerGesture.referenceGestureX;
4176 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.referenceTouchY)
4177 * mLocked.pointerGestureYZoomScale + mPointerGesture.referenceGestureY;
Jeff Brown96ad3972011-03-09 17:39:48 -08004178
4179 mPointerGesture.currentGestureCoords[i].clear();
4180 mPointerGesture.currentGestureCoords[i].setAxisValue(
4181 AMOTION_EVENT_AXIS_X, x);
4182 mPointerGesture.currentGestureCoords[i].setAxisValue(
4183 AMOTION_EVENT_AXIS_Y, y);
4184 mPointerGesture.currentGestureCoords[i].setAxisValue(
4185 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4186 }
4187
4188 if (mPointerGesture.activeGestureId < 0) {
4189 mPointerGesture.activeGestureId =
4190 mPointerGesture.currentGestureIdBits.firstMarkedBit();
4191#if DEBUG_GESTURES
4192 LOGD("Gestures: FREEFORM new "
4193 "activeGestureId=%d", mPointerGesture.activeGestureId);
4194#endif
4195 }
Jeff Brown96ad3972011-03-09 17:39:48 -08004196
Jeff Brown86ea1f52011-04-12 22:39:53 -07004197 mPointerController->setButtonState(0); // touch is not actually following the pointer
4198
4199 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4200 mPointerGesture.spotGesture = PointerControllerInterface::SPOT_GESTURE_FREEFORM;
4201 }
4202 }
4203
4204 // Update spot locations for PRESS, SWIPE and FREEFORM.
4205 // We use the same calculation as we do to calculate the gesture pointers
4206 // for FREEFORM so that the spots smoothly track gestures.
4207 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
4208 mPointerGesture.spotIdBits.clear();
4209 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
4210 uint32_t id = mCurrentTouch.pointers[i].id;
4211 mPointerGesture.spotIdBits.markBit(id);
4212 mPointerGesture.spotIdToIndex[id] = i;
4213
4214 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.referenceTouchX)
4215 * mLocked.pointerGestureXZoomScale + mPointerGesture.referenceGestureX;
4216 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.referenceTouchY)
4217 * mLocked.pointerGestureYZoomScale + mPointerGesture.referenceGestureY;
4218
4219 mPointerGesture.spotCoords[i].clear();
4220 mPointerGesture.spotCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4221 mPointerGesture.spotCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4222 mPointerGesture.spotCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4223 }
4224 moveSpotsLocked();
4225 }
Jeff Brown96ad3972011-03-09 17:39:48 -08004226 }
4227
4228#if DEBUG_GESTURES
4229 LOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
Jeff Brown86ea1f52011-04-12 22:39:53 -07004230 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
4231 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
Jeff Brown96ad3972011-03-09 17:39:48 -08004232 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
Jeff Brown86ea1f52011-04-12 22:39:53 -07004233 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
4234 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
Jeff Brown96ad3972011-03-09 17:39:48 -08004235 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
4236 uint32_t id = idBits.firstMarkedBit();
4237 idBits.clearBit(id);
4238 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
4239 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
4240 LOGD(" currentGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
4241 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
4242 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
4243 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
4244 }
4245 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
4246 uint32_t id = idBits.firstMarkedBit();
4247 idBits.clearBit(id);
4248 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
4249 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
4250 LOGD(" lastGesture[%d]: index=%d, x=%0.3f, y=%0.3f, pressure=%0.3f",
4251 id, index, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
4252 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
4253 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
4254 }
4255#endif
Jeff Brown325bd072011-04-19 21:20:10 -07004256 return true;
Jeff Brown96ad3972011-03-09 17:39:48 -08004257}
4258
Jeff Brown86ea1f52011-04-12 22:39:53 -07004259void TouchInputMapper::moveSpotsLocked() {
4260 mPointerController->setSpots(mPointerGesture.spotGesture,
4261 mPointerGesture.spotCoords, mPointerGesture.spotIdToIndex, mPointerGesture.spotIdBits);
4262}
4263
Jeff Brown96ad3972011-03-09 17:39:48 -08004264void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
4265 int32_t action, int32_t flags, uint32_t metaState, int32_t edgeFlags,
4266 const PointerCoords* coords, const uint32_t* idToIndex, BitSet32 idBits,
4267 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
4268 PointerCoords pointerCoords[MAX_POINTERS];
4269 int32_t pointerIds[MAX_POINTERS];
4270 uint32_t pointerCount = 0;
4271 while (!idBits.isEmpty()) {
4272 uint32_t id = idBits.firstMarkedBit();
4273 idBits.clearBit(id);
4274 uint32_t index = idToIndex[id];
4275 pointerIds[pointerCount] = id;
4276 pointerCoords[pointerCount].copyFrom(coords[index]);
4277
4278 if (changedId >= 0 && id == uint32_t(changedId)) {
4279 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
4280 }
4281
4282 pointerCount += 1;
4283 }
4284
4285 assert(pointerCount != 0);
4286
4287 if (changedId >= 0 && pointerCount == 1) {
4288 // Replace initial down and final up action.
4289 // We can compare the action without masking off the changed pointer index
4290 // because we know the index is 0.
4291 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
4292 action = AMOTION_EVENT_ACTION_DOWN;
4293 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
4294 action = AMOTION_EVENT_ACTION_UP;
4295 } else {
4296 // Can't happen.
4297 assert(false);
4298 }
4299 }
4300
4301 getDispatcher()->notifyMotion(when, getDeviceId(), source, policyFlags,
4302 action, flags, metaState, edgeFlags,
4303 pointerCount, pointerIds, pointerCoords, xPrecision, yPrecision, downTime);
4304}
4305
4306bool TouchInputMapper::updateMovedPointerCoords(
4307 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
4308 PointerCoords* outCoords, const uint32_t* outIdToIndex, BitSet32 idBits) const {
4309 bool changed = false;
4310 while (!idBits.isEmpty()) {
4311 uint32_t id = idBits.firstMarkedBit();
4312 idBits.clearBit(id);
4313
4314 uint32_t inIndex = inIdToIndex[id];
4315 uint32_t outIndex = outIdToIndex[id];
4316 const PointerCoords& curInCoords = inCoords[inIndex];
4317 PointerCoords& curOutCoords = outCoords[outIndex];
4318
4319 if (curInCoords != curOutCoords) {
4320 curOutCoords.copyFrom(curInCoords);
4321 changed = true;
4322 }
4323 }
4324 return changed;
4325}
4326
4327void TouchInputMapper::fadePointer() {
4328 { // acquire lock
4329 AutoMutex _l(mLock);
4330 if (mPointerController != NULL) {
Jeff Brown538881e2011-05-25 18:23:38 -07004331 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
Jeff Brown96ad3972011-03-09 17:39:48 -08004332 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004333 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004334}
4335
Jeff Brown6328cdc2010-07-29 18:18:33 -07004336bool TouchInputMapper::isPointInsideSurfaceLocked(int32_t x, int32_t y) {
Jeff Brown9626b142011-03-03 02:09:54 -08004337 return x >= mRawAxes.x.minValue && x <= mRawAxes.x.maxValue
4338 && y >= mRawAxes.y.minValue && y <= mRawAxes.y.maxValue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004339}
4340
Jeff Brown6328cdc2010-07-29 18:18:33 -07004341const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHitLocked(
4342 int32_t x, int32_t y) {
4343 size_t numVirtualKeys = mLocked.virtualKeys.size();
4344 for (size_t i = 0; i < numVirtualKeys; i++) {
4345 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004346
4347#if DEBUG_VIRTUAL_KEYS
4348 LOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
4349 "left=%d, top=%d, right=%d, bottom=%d",
4350 x, y,
4351 virtualKey.keyCode, virtualKey.scanCode,
4352 virtualKey.hitLeft, virtualKey.hitTop,
4353 virtualKey.hitRight, virtualKey.hitBottom);
4354#endif
4355
4356 if (virtualKey.isHit(x, y)) {
4357 return & virtualKey;
4358 }
4359 }
4360
4361 return NULL;
4362}
4363
4364void TouchInputMapper::calculatePointerIds() {
4365 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
4366 uint32_t lastPointerCount = mLastTouch.pointerCount;
4367
4368 if (currentPointerCount == 0) {
4369 // No pointers to assign.
4370 mCurrentTouch.idBits.clear();
4371 } else if (lastPointerCount == 0) {
4372 // All pointers are new.
4373 mCurrentTouch.idBits.clear();
4374 for (uint32_t i = 0; i < currentPointerCount; i++) {
4375 mCurrentTouch.pointers[i].id = i;
4376 mCurrentTouch.idToIndex[i] = i;
4377 mCurrentTouch.idBits.markBit(i);
4378 }
4379 } else if (currentPointerCount == 1 && lastPointerCount == 1) {
4380 // Only one pointer and no change in count so it must have the same id as before.
4381 uint32_t id = mLastTouch.pointers[0].id;
4382 mCurrentTouch.pointers[0].id = id;
4383 mCurrentTouch.idToIndex[id] = 0;
4384 mCurrentTouch.idBits.value = BitSet32::valueForBit(id);
4385 } else {
4386 // General case.
4387 // We build a heap of squared euclidean distances between current and last pointers
4388 // associated with the current and last pointer indices. Then, we find the best
4389 // match (by distance) for each current pointer.
4390 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
4391
4392 uint32_t heapSize = 0;
4393 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
4394 currentPointerIndex++) {
4395 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
4396 lastPointerIndex++) {
4397 int64_t deltaX = mCurrentTouch.pointers[currentPointerIndex].x
4398 - mLastTouch.pointers[lastPointerIndex].x;
4399 int64_t deltaY = mCurrentTouch.pointers[currentPointerIndex].y
4400 - mLastTouch.pointers[lastPointerIndex].y;
4401
4402 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4403
4404 // Insert new element into the heap (sift up).
4405 heap[heapSize].currentPointerIndex = currentPointerIndex;
4406 heap[heapSize].lastPointerIndex = lastPointerIndex;
4407 heap[heapSize].distance = distance;
4408 heapSize += 1;
4409 }
4410 }
4411
4412 // Heapify
4413 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
4414 startIndex -= 1;
4415 for (uint32_t parentIndex = startIndex; ;) {
4416 uint32_t childIndex = parentIndex * 2 + 1;
4417 if (childIndex >= heapSize) {
4418 break;
4419 }
4420
4421 if (childIndex + 1 < heapSize
4422 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4423 childIndex += 1;
4424 }
4425
4426 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4427 break;
4428 }
4429
4430 swap(heap[parentIndex], heap[childIndex]);
4431 parentIndex = childIndex;
4432 }
4433 }
4434
4435#if DEBUG_POINTER_ASSIGNMENT
4436 LOGD("calculatePointerIds - initial distance min-heap: size=%d", heapSize);
4437 for (size_t i = 0; i < heapSize; i++) {
4438 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4439 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4440 heap[i].distance);
4441 }
4442#endif
4443
4444 // Pull matches out by increasing order of distance.
4445 // To avoid reassigning pointers that have already been matched, the loop keeps track
4446 // of which last and current pointers have been matched using the matchedXXXBits variables.
4447 // It also tracks the used pointer id bits.
4448 BitSet32 matchedLastBits(0);
4449 BitSet32 matchedCurrentBits(0);
4450 BitSet32 usedIdBits(0);
4451 bool first = true;
4452 for (uint32_t i = min(currentPointerCount, lastPointerCount); i > 0; i--) {
4453 for (;;) {
4454 if (first) {
4455 // The first time through the loop, we just consume the root element of
4456 // the heap (the one with smallest distance).
4457 first = false;
4458 } else {
4459 // Previous iterations consumed the root element of the heap.
4460 // Pop root element off of the heap (sift down).
4461 heapSize -= 1;
4462 assert(heapSize > 0);
4463
4464 // Sift down.
4465 heap[0] = heap[heapSize];
4466 for (uint32_t parentIndex = 0; ;) {
4467 uint32_t childIndex = parentIndex * 2 + 1;
4468 if (childIndex >= heapSize) {
4469 break;
4470 }
4471
4472 if (childIndex + 1 < heapSize
4473 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4474 childIndex += 1;
4475 }
4476
4477 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4478 break;
4479 }
4480
4481 swap(heap[parentIndex], heap[childIndex]);
4482 parentIndex = childIndex;
4483 }
4484
4485#if DEBUG_POINTER_ASSIGNMENT
4486 LOGD("calculatePointerIds - reduced distance min-heap: size=%d", heapSize);
4487 for (size_t i = 0; i < heapSize; i++) {
4488 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4489 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4490 heap[i].distance);
4491 }
4492#endif
4493 }
4494
4495 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4496 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4497
4498 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4499 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4500
4501 matchedCurrentBits.markBit(currentPointerIndex);
4502 matchedLastBits.markBit(lastPointerIndex);
4503
4504 uint32_t id = mLastTouch.pointers[lastPointerIndex].id;
4505 mCurrentTouch.pointers[currentPointerIndex].id = id;
4506 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4507 usedIdBits.markBit(id);
4508
4509#if DEBUG_POINTER_ASSIGNMENT
4510 LOGD("calculatePointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
4511 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
4512#endif
4513 break;
4514 }
4515 }
4516
4517 // Assign fresh ids to new pointers.
4518 if (currentPointerCount > lastPointerCount) {
4519 for (uint32_t i = currentPointerCount - lastPointerCount; ;) {
4520 uint32_t currentPointerIndex = matchedCurrentBits.firstUnmarkedBit();
4521 uint32_t id = usedIdBits.firstUnmarkedBit();
4522
4523 mCurrentTouch.pointers[currentPointerIndex].id = id;
4524 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4525 usedIdBits.markBit(id);
4526
4527#if DEBUG_POINTER_ASSIGNMENT
4528 LOGD("calculatePointerIds - assigned: cur=%d, id=%d",
4529 currentPointerIndex, id);
4530#endif
4531
4532 if (--i == 0) break; // done
4533 matchedCurrentBits.markBit(currentPointerIndex);
4534 }
4535 }
4536
4537 // Fix id bits.
4538 mCurrentTouch.idBits = usedIdBits;
4539 }
4540}
4541
4542/* Special hack for devices that have bad screen data: if one of the
4543 * points has moved more than a screen height from the last position,
4544 * then drop it. */
4545bool TouchInputMapper::applyBadTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004546 uint32_t pointerCount = mCurrentTouch.pointerCount;
4547
4548 // Nothing to do if there are no points.
4549 if (pointerCount == 0) {
4550 return false;
4551 }
4552
4553 // Don't do anything if a finger is going down or up. We run
4554 // here before assigning pointer IDs, so there isn't a good
4555 // way to do per-finger matching.
4556 if (pointerCount != mLastTouch.pointerCount) {
4557 return false;
4558 }
4559
4560 // We consider a single movement across more than a 7/16 of
4561 // the long size of the screen to be bad. This was a magic value
4562 // determined by looking at the maximum distance it is feasible
4563 // to actually move in one sample.
Jeff Brown9626b142011-03-03 02:09:54 -08004564 int32_t maxDeltaY = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) * 7 / 16;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004565
4566 // XXX The original code in InputDevice.java included commented out
4567 // code for testing the X axis. Note that when we drop a point
4568 // we don't actually restore the old X either. Strange.
4569 // The old code also tries to track when bad points were previously
4570 // detected but it turns out that due to the placement of a "break"
4571 // at the end of the loop, we never set mDroppedBadPoint to true
4572 // so it is effectively dead code.
4573 // Need to figure out if the old code is busted or just overcomplicated
4574 // but working as intended.
4575
4576 // Look through all new points and see if any are farther than
4577 // acceptable from all previous points.
4578 for (uint32_t i = pointerCount; i-- > 0; ) {
4579 int32_t y = mCurrentTouch.pointers[i].y;
4580 int32_t closestY = INT_MAX;
4581 int32_t closestDeltaY = 0;
4582
4583#if DEBUG_HACKS
4584 LOGD("BadTouchFilter: Looking at next point #%d: y=%d", i, y);
4585#endif
4586
4587 for (uint32_t j = pointerCount; j-- > 0; ) {
4588 int32_t lastY = mLastTouch.pointers[j].y;
4589 int32_t deltaY = abs(y - lastY);
4590
4591#if DEBUG_HACKS
4592 LOGD("BadTouchFilter: Comparing with last point #%d: y=%d deltaY=%d",
4593 j, lastY, deltaY);
4594#endif
4595
4596 if (deltaY < maxDeltaY) {
4597 goto SkipSufficientlyClosePoint;
4598 }
4599 if (deltaY < closestDeltaY) {
4600 closestDeltaY = deltaY;
4601 closestY = lastY;
4602 }
4603 }
4604
4605 // Must not have found a close enough match.
4606#if DEBUG_HACKS
4607 LOGD("BadTouchFilter: Dropping bad point #%d: newY=%d oldY=%d deltaY=%d maxDeltaY=%d",
4608 i, y, closestY, closestDeltaY, maxDeltaY);
4609#endif
4610
4611 mCurrentTouch.pointers[i].y = closestY;
4612 return true; // XXX original code only corrects one point
4613
4614 SkipSufficientlyClosePoint: ;
4615 }
4616
4617 // No change.
4618 return false;
4619}
4620
4621/* Special hack for devices that have bad screen data: drop points where
4622 * the coordinate value for one axis has jumped to the other pointer's location.
4623 */
4624bool TouchInputMapper::applyJumpyTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004625 uint32_t pointerCount = mCurrentTouch.pointerCount;
4626 if (mLastTouch.pointerCount != pointerCount) {
4627#if DEBUG_HACKS
4628 LOGD("JumpyTouchFilter: Different pointer count %d -> %d",
4629 mLastTouch.pointerCount, pointerCount);
4630 for (uint32_t i = 0; i < pointerCount; i++) {
4631 LOGD(" Pointer %d (%d, %d)", i,
4632 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4633 }
4634#endif
4635
4636 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_TRANSITION_DROPS) {
4637 if (mLastTouch.pointerCount == 1 && pointerCount == 2) {
4638 // Just drop the first few events going from 1 to 2 pointers.
4639 // They're bad often enough that they're not worth considering.
4640 mCurrentTouch.pointerCount = 1;
4641 mJumpyTouchFilter.jumpyPointsDropped += 1;
4642
4643#if DEBUG_HACKS
4644 LOGD("JumpyTouchFilter: Pointer 2 dropped");
4645#endif
4646 return true;
4647 } else if (mLastTouch.pointerCount == 2 && pointerCount == 1) {
4648 // The event when we go from 2 -> 1 tends to be messed up too
4649 mCurrentTouch.pointerCount = 2;
4650 mCurrentTouch.pointers[0] = mLastTouch.pointers[0];
4651 mCurrentTouch.pointers[1] = mLastTouch.pointers[1];
4652 mJumpyTouchFilter.jumpyPointsDropped += 1;
4653
4654#if DEBUG_HACKS
4655 for (int32_t i = 0; i < 2; i++) {
4656 LOGD("JumpyTouchFilter: Pointer %d replaced (%d, %d)", i,
4657 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4658 }
4659#endif
4660 return true;
4661 }
4662 }
4663 // Reset jumpy points dropped on other transitions or if limit exceeded.
4664 mJumpyTouchFilter.jumpyPointsDropped = 0;
4665
4666#if DEBUG_HACKS
4667 LOGD("JumpyTouchFilter: Transition - drop limit reset");
4668#endif
4669 return false;
4670 }
4671
4672 // We have the same number of pointers as last time.
4673 // A 'jumpy' point is one where the coordinate value for one axis
4674 // has jumped to the other pointer's location. No need to do anything
4675 // else if we only have one pointer.
4676 if (pointerCount < 2) {
4677 return false;
4678 }
4679
4680 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_DROP_LIMIT) {
Jeff Brown9626b142011-03-03 02:09:54 -08004681 int jumpyEpsilon = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) / JUMPY_EPSILON_DIVISOR;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004682
4683 // We only replace the single worst jumpy point as characterized by pointer distance
4684 // in a single axis.
4685 int32_t badPointerIndex = -1;
4686 int32_t badPointerReplacementIndex = -1;
4687 int32_t badPointerDistance = INT_MIN; // distance to be corrected
4688
4689 for (uint32_t i = pointerCount; i-- > 0; ) {
4690 int32_t x = mCurrentTouch.pointers[i].x;
4691 int32_t y = mCurrentTouch.pointers[i].y;
4692
4693#if DEBUG_HACKS
4694 LOGD("JumpyTouchFilter: Point %d (%d, %d)", i, x, y);
4695#endif
4696
4697 // Check if a touch point is too close to another's coordinates
4698 bool dropX = false, dropY = false;
4699 for (uint32_t j = 0; j < pointerCount; j++) {
4700 if (i == j) {
4701 continue;
4702 }
4703
4704 if (abs(x - mCurrentTouch.pointers[j].x) <= jumpyEpsilon) {
4705 dropX = true;
4706 break;
4707 }
4708
4709 if (abs(y - mCurrentTouch.pointers[j].y) <= jumpyEpsilon) {
4710 dropY = true;
4711 break;
4712 }
4713 }
4714 if (! dropX && ! dropY) {
4715 continue; // not jumpy
4716 }
4717
4718 // Find a replacement candidate by comparing with older points on the
4719 // complementary (non-jumpy) axis.
4720 int32_t distance = INT_MIN; // distance to be corrected
4721 int32_t replacementIndex = -1;
4722
4723 if (dropX) {
4724 // X looks too close. Find an older replacement point with a close Y.
4725 int32_t smallestDeltaY = INT_MAX;
4726 for (uint32_t j = 0; j < pointerCount; j++) {
4727 int32_t deltaY = abs(y - mLastTouch.pointers[j].y);
4728 if (deltaY < smallestDeltaY) {
4729 smallestDeltaY = deltaY;
4730 replacementIndex = j;
4731 }
4732 }
4733 distance = abs(x - mLastTouch.pointers[replacementIndex].x);
4734 } else {
4735 // Y looks too close. Find an older replacement point with a close X.
4736 int32_t smallestDeltaX = INT_MAX;
4737 for (uint32_t j = 0; j < pointerCount; j++) {
4738 int32_t deltaX = abs(x - mLastTouch.pointers[j].x);
4739 if (deltaX < smallestDeltaX) {
4740 smallestDeltaX = deltaX;
4741 replacementIndex = j;
4742 }
4743 }
4744 distance = abs(y - mLastTouch.pointers[replacementIndex].y);
4745 }
4746
4747 // If replacing this pointer would correct a worse error than the previous ones
4748 // considered, then use this replacement instead.
4749 if (distance > badPointerDistance) {
4750 badPointerIndex = i;
4751 badPointerReplacementIndex = replacementIndex;
4752 badPointerDistance = distance;
4753 }
4754 }
4755
4756 // Correct the jumpy pointer if one was found.
4757 if (badPointerIndex >= 0) {
4758#if DEBUG_HACKS
4759 LOGD("JumpyTouchFilter: Replacing bad pointer %d with (%d, %d)",
4760 badPointerIndex,
4761 mLastTouch.pointers[badPointerReplacementIndex].x,
4762 mLastTouch.pointers[badPointerReplacementIndex].y);
4763#endif
4764
4765 mCurrentTouch.pointers[badPointerIndex].x =
4766 mLastTouch.pointers[badPointerReplacementIndex].x;
4767 mCurrentTouch.pointers[badPointerIndex].y =
4768 mLastTouch.pointers[badPointerReplacementIndex].y;
4769 mJumpyTouchFilter.jumpyPointsDropped += 1;
4770 return true;
4771 }
4772 }
4773
4774 mJumpyTouchFilter.jumpyPointsDropped = 0;
4775 return false;
4776}
4777
4778/* Special hack for devices that have bad screen data: aggregate and
4779 * compute averages of the coordinate data, to reduce the amount of
4780 * jitter seen by applications. */
4781void TouchInputMapper::applyAveragingTouchFilter() {
4782 for (uint32_t currentIndex = 0; currentIndex < mCurrentTouch.pointerCount; currentIndex++) {
4783 uint32_t id = mCurrentTouch.pointers[currentIndex].id;
4784 int32_t x = mCurrentTouch.pointers[currentIndex].x;
4785 int32_t y = mCurrentTouch.pointers[currentIndex].y;
Jeff Brown8d608662010-08-30 03:02:23 -07004786 int32_t pressure;
4787 switch (mCalibration.pressureSource) {
4788 case Calibration::PRESSURE_SOURCE_PRESSURE:
4789 pressure = mCurrentTouch.pointers[currentIndex].pressure;
4790 break;
4791 case Calibration::PRESSURE_SOURCE_TOUCH:
4792 pressure = mCurrentTouch.pointers[currentIndex].touchMajor;
4793 break;
4794 default:
4795 pressure = 1;
4796 break;
4797 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004798
4799 if (mLastTouch.idBits.hasBit(id)) {
4800 // Pointer was down before and is still down now.
4801 // Compute average over history trace.
4802 uint32_t start = mAveragingTouchFilter.historyStart[id];
4803 uint32_t end = mAveragingTouchFilter.historyEnd[id];
4804
4805 int64_t deltaX = x - mAveragingTouchFilter.historyData[end].pointers[id].x;
4806 int64_t deltaY = y - mAveragingTouchFilter.historyData[end].pointers[id].y;
4807 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4808
4809#if DEBUG_HACKS
4810 LOGD("AveragingTouchFilter: Pointer id %d - Distance from last sample: %lld",
4811 id, distance);
4812#endif
4813
4814 if (distance < AVERAGING_DISTANCE_LIMIT) {
4815 // Increment end index in preparation for recording new historical data.
4816 end += 1;
4817 if (end > AVERAGING_HISTORY_SIZE) {
4818 end = 0;
4819 }
4820
4821 // If the end index has looped back to the start index then we have filled
4822 // the historical trace up to the desired size so we drop the historical
4823 // data at the start of the trace.
4824 if (end == start) {
4825 start += 1;
4826 if (start > AVERAGING_HISTORY_SIZE) {
4827 start = 0;
4828 }
4829 }
4830
4831 // Add the raw data to the historical trace.
4832 mAveragingTouchFilter.historyStart[id] = start;
4833 mAveragingTouchFilter.historyEnd[id] = end;
4834 mAveragingTouchFilter.historyData[end].pointers[id].x = x;
4835 mAveragingTouchFilter.historyData[end].pointers[id].y = y;
4836 mAveragingTouchFilter.historyData[end].pointers[id].pressure = pressure;
4837
4838 // Average over all historical positions in the trace by total pressure.
4839 int32_t averagedX = 0;
4840 int32_t averagedY = 0;
4841 int32_t totalPressure = 0;
4842 for (;;) {
4843 int32_t historicalX = mAveragingTouchFilter.historyData[start].pointers[id].x;
4844 int32_t historicalY = mAveragingTouchFilter.historyData[start].pointers[id].y;
4845 int32_t historicalPressure = mAveragingTouchFilter.historyData[start]
4846 .pointers[id].pressure;
4847
4848 averagedX += historicalX * historicalPressure;
4849 averagedY += historicalY * historicalPressure;
4850 totalPressure += historicalPressure;
4851
4852 if (start == end) {
4853 break;
4854 }
4855
4856 start += 1;
4857 if (start > AVERAGING_HISTORY_SIZE) {
4858 start = 0;
4859 }
4860 }
4861
Jeff Brown8d608662010-08-30 03:02:23 -07004862 if (totalPressure != 0) {
4863 averagedX /= totalPressure;
4864 averagedY /= totalPressure;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004865
4866#if DEBUG_HACKS
Jeff Brown8d608662010-08-30 03:02:23 -07004867 LOGD("AveragingTouchFilter: Pointer id %d - "
4868 "totalPressure=%d, averagedX=%d, averagedY=%d", id, totalPressure,
4869 averagedX, averagedY);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004870#endif
4871
Jeff Brown8d608662010-08-30 03:02:23 -07004872 mCurrentTouch.pointers[currentIndex].x = averagedX;
4873 mCurrentTouch.pointers[currentIndex].y = averagedY;
4874 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07004875 } else {
4876#if DEBUG_HACKS
4877 LOGD("AveragingTouchFilter: Pointer id %d - Exceeded max distance", id);
4878#endif
4879 }
4880 } else {
4881#if DEBUG_HACKS
4882 LOGD("AveragingTouchFilter: Pointer id %d - Pointer went up", id);
4883#endif
4884 }
4885
4886 // Reset pointer history.
4887 mAveragingTouchFilter.historyStart[id] = 0;
4888 mAveragingTouchFilter.historyEnd[id] = 0;
4889 mAveragingTouchFilter.historyData[0].pointers[id].x = x;
4890 mAveragingTouchFilter.historyData[0].pointers[id].y = y;
4891 mAveragingTouchFilter.historyData[0].pointers[id].pressure = pressure;
4892 }
4893}
4894
4895int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004896 { // acquire lock
4897 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004898
Jeff Brown6328cdc2010-07-29 18:18:33 -07004899 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.keyCode == keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004900 return AKEY_STATE_VIRTUAL;
4901 }
4902
Jeff Brown6328cdc2010-07-29 18:18:33 -07004903 size_t numVirtualKeys = mLocked.virtualKeys.size();
4904 for (size_t i = 0; i < numVirtualKeys; i++) {
4905 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004906 if (virtualKey.keyCode == keyCode) {
4907 return AKEY_STATE_UP;
4908 }
4909 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004910 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004911
4912 return AKEY_STATE_UNKNOWN;
4913}
4914
4915int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004916 { // acquire lock
4917 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004918
Jeff Brown6328cdc2010-07-29 18:18:33 -07004919 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004920 return AKEY_STATE_VIRTUAL;
4921 }
4922
Jeff Brown6328cdc2010-07-29 18:18:33 -07004923 size_t numVirtualKeys = mLocked.virtualKeys.size();
4924 for (size_t i = 0; i < numVirtualKeys; i++) {
4925 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004926 if (virtualKey.scanCode == scanCode) {
4927 return AKEY_STATE_UP;
4928 }
4929 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004930 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004931
4932 return AKEY_STATE_UNKNOWN;
4933}
4934
4935bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4936 const int32_t* keyCodes, uint8_t* outFlags) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07004937 { // acquire lock
4938 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004939
Jeff Brown6328cdc2010-07-29 18:18:33 -07004940 size_t numVirtualKeys = mLocked.virtualKeys.size();
4941 for (size_t i = 0; i < numVirtualKeys; i++) {
4942 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004943
4944 for (size_t i = 0; i < numCodes; i++) {
4945 if (virtualKey.keyCode == keyCodes[i]) {
4946 outFlags[i] = 1;
4947 }
4948 }
4949 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004950 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07004951
4952 return true;
4953}
4954
4955
4956// --- SingleTouchInputMapper ---
4957
Jeff Brown47e6b1b2010-11-29 17:37:49 -08004958SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
4959 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004960 initialize();
4961}
4962
4963SingleTouchInputMapper::~SingleTouchInputMapper() {
4964}
4965
4966void SingleTouchInputMapper::initialize() {
4967 mAccumulator.clear();
4968
4969 mDown = false;
4970 mX = 0;
4971 mY = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07004972 mPressure = 0; // default to 0 for devices that don't report pressure
4973 mToolWidth = 0; // default to 0 for devices that don't report tool width
Jeff Brown96ad3972011-03-09 17:39:48 -08004974 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004975}
4976
4977void SingleTouchInputMapper::reset() {
4978 TouchInputMapper::reset();
4979
Jeff Brown6d0fec22010-07-23 21:28:06 -07004980 initialize();
4981 }
4982
4983void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
4984 switch (rawEvent->type) {
4985 case EV_KEY:
4986 switch (rawEvent->scanCode) {
4987 case BTN_TOUCH:
4988 mAccumulator.fields |= Accumulator::FIELD_BTN_TOUCH;
4989 mAccumulator.btnTouch = rawEvent->value != 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07004990 // Don't sync immediately. Wait until the next SYN_REPORT since we might
4991 // not have received valid position information yet. This logic assumes that
4992 // BTN_TOUCH is always followed by SYN_REPORT as part of a complete packet.
Jeff Brown6d0fec22010-07-23 21:28:06 -07004993 break;
Jeff Brown96ad3972011-03-09 17:39:48 -08004994 default:
4995 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
4996 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
4997 if (buttonState) {
4998 if (rawEvent->value) {
4999 mAccumulator.buttonDown |= buttonState;
5000 } else {
5001 mAccumulator.buttonUp |= buttonState;
5002 }
5003 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
5004 }
5005 }
5006 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005007 }
5008 break;
5009
5010 case EV_ABS:
5011 switch (rawEvent->scanCode) {
5012 case ABS_X:
5013 mAccumulator.fields |= Accumulator::FIELD_ABS_X;
5014 mAccumulator.absX = rawEvent->value;
5015 break;
5016 case ABS_Y:
5017 mAccumulator.fields |= Accumulator::FIELD_ABS_Y;
5018 mAccumulator.absY = rawEvent->value;
5019 break;
5020 case ABS_PRESSURE:
5021 mAccumulator.fields |= Accumulator::FIELD_ABS_PRESSURE;
5022 mAccumulator.absPressure = rawEvent->value;
5023 break;
5024 case ABS_TOOL_WIDTH:
5025 mAccumulator.fields |= Accumulator::FIELD_ABS_TOOL_WIDTH;
5026 mAccumulator.absToolWidth = rawEvent->value;
5027 break;
5028 }
5029 break;
5030
5031 case EV_SYN:
5032 switch (rawEvent->scanCode) {
5033 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005034 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005035 break;
5036 }
5037 break;
5038 }
5039}
5040
5041void SingleTouchInputMapper::sync(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07005042 uint32_t fields = mAccumulator.fields;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005043 if (fields == 0) {
5044 return; // no new state changes, so nothing to do
5045 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07005046
5047 if (fields & Accumulator::FIELD_BTN_TOUCH) {
5048 mDown = mAccumulator.btnTouch;
5049 }
5050
5051 if (fields & Accumulator::FIELD_ABS_X) {
5052 mX = mAccumulator.absX;
5053 }
5054
5055 if (fields & Accumulator::FIELD_ABS_Y) {
5056 mY = mAccumulator.absY;
5057 }
5058
5059 if (fields & Accumulator::FIELD_ABS_PRESSURE) {
5060 mPressure = mAccumulator.absPressure;
5061 }
5062
5063 if (fields & Accumulator::FIELD_ABS_TOOL_WIDTH) {
Jeff Brown8d608662010-08-30 03:02:23 -07005064 mToolWidth = mAccumulator.absToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005065 }
5066
Jeff Brown96ad3972011-03-09 17:39:48 -08005067 if (fields & Accumulator::FIELD_BUTTONS) {
5068 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
5069 }
5070
Jeff Brown6d0fec22010-07-23 21:28:06 -07005071 mCurrentTouch.clear();
5072
5073 if (mDown) {
5074 mCurrentTouch.pointerCount = 1;
5075 mCurrentTouch.pointers[0].id = 0;
5076 mCurrentTouch.pointers[0].x = mX;
5077 mCurrentTouch.pointers[0].y = mY;
5078 mCurrentTouch.pointers[0].pressure = mPressure;
Jeff Brown8d608662010-08-30 03:02:23 -07005079 mCurrentTouch.pointers[0].touchMajor = 0;
5080 mCurrentTouch.pointers[0].touchMinor = 0;
5081 mCurrentTouch.pointers[0].toolMajor = mToolWidth;
5082 mCurrentTouch.pointers[0].toolMinor = mToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005083 mCurrentTouch.pointers[0].orientation = 0;
5084 mCurrentTouch.idToIndex[0] = 0;
5085 mCurrentTouch.idBits.markBit(0);
Jeff Brown96ad3972011-03-09 17:39:48 -08005086 mCurrentTouch.buttonState = mButtonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005087 }
5088
5089 syncTouch(when, true);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005090
5091 mAccumulator.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07005092}
5093
Jeff Brown8d608662010-08-30 03:02:23 -07005094void SingleTouchInputMapper::configureRawAxes() {
5095 TouchInputMapper::configureRawAxes();
Jeff Brown6d0fec22010-07-23 21:28:06 -07005096
Jeff Brown8d608662010-08-30 03:02:23 -07005097 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_X, & mRawAxes.x);
5098 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_Y, & mRawAxes.y);
5099 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_PRESSURE, & mRawAxes.pressure);
5100 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_TOOL_WIDTH, & mRawAxes.toolMajor);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005101}
5102
5103
5104// --- MultiTouchInputMapper ---
5105
Jeff Brown47e6b1b2010-11-29 17:37:49 -08005106MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
5107 TouchInputMapper(device) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07005108 initialize();
5109}
5110
5111MultiTouchInputMapper::~MultiTouchInputMapper() {
5112}
5113
5114void MultiTouchInputMapper::initialize() {
5115 mAccumulator.clear();
Jeff Brown96ad3972011-03-09 17:39:48 -08005116 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005117}
5118
5119void MultiTouchInputMapper::reset() {
5120 TouchInputMapper::reset();
5121
Jeff Brown6d0fec22010-07-23 21:28:06 -07005122 initialize();
5123}
5124
5125void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
5126 switch (rawEvent->type) {
Jeff Brown96ad3972011-03-09 17:39:48 -08005127 case EV_KEY: {
5128 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
5129 uint32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
5130 if (buttonState) {
5131 if (rawEvent->value) {
5132 mAccumulator.buttonDown |= buttonState;
5133 } else {
5134 mAccumulator.buttonUp |= buttonState;
5135 }
5136 }
5137 }
5138 break;
5139 }
5140
Jeff Brown6d0fec22010-07-23 21:28:06 -07005141 case EV_ABS: {
5142 uint32_t pointerIndex = mAccumulator.pointerCount;
5143 Accumulator::Pointer* pointer = & mAccumulator.pointers[pointerIndex];
5144
5145 switch (rawEvent->scanCode) {
5146 case ABS_MT_POSITION_X:
5147 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_X;
5148 pointer->absMTPositionX = rawEvent->value;
5149 break;
5150 case ABS_MT_POSITION_Y:
5151 pointer->fields |= Accumulator::FIELD_ABS_MT_POSITION_Y;
5152 pointer->absMTPositionY = rawEvent->value;
5153 break;
5154 case ABS_MT_TOUCH_MAJOR:
5155 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MAJOR;
5156 pointer->absMTTouchMajor = rawEvent->value;
5157 break;
5158 case ABS_MT_TOUCH_MINOR:
5159 pointer->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MINOR;
5160 pointer->absMTTouchMinor = rawEvent->value;
5161 break;
5162 case ABS_MT_WIDTH_MAJOR:
5163 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MAJOR;
5164 pointer->absMTWidthMajor = rawEvent->value;
5165 break;
5166 case ABS_MT_WIDTH_MINOR:
5167 pointer->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MINOR;
5168 pointer->absMTWidthMinor = rawEvent->value;
5169 break;
5170 case ABS_MT_ORIENTATION:
5171 pointer->fields |= Accumulator::FIELD_ABS_MT_ORIENTATION;
5172 pointer->absMTOrientation = rawEvent->value;
5173 break;
5174 case ABS_MT_TRACKING_ID:
5175 pointer->fields |= Accumulator::FIELD_ABS_MT_TRACKING_ID;
5176 pointer->absMTTrackingId = rawEvent->value;
5177 break;
Jeff Brown8d608662010-08-30 03:02:23 -07005178 case ABS_MT_PRESSURE:
5179 pointer->fields |= Accumulator::FIELD_ABS_MT_PRESSURE;
5180 pointer->absMTPressure = rawEvent->value;
5181 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005182 }
5183 break;
5184 }
5185
5186 case EV_SYN:
5187 switch (rawEvent->scanCode) {
5188 case SYN_MT_REPORT: {
5189 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
5190 uint32_t pointerIndex = mAccumulator.pointerCount;
5191
5192 if (mAccumulator.pointers[pointerIndex].fields) {
5193 if (pointerIndex == MAX_POINTERS) {
5194 LOGW("MultiTouch device driver returned more than maximum of %d pointers.",
5195 MAX_POINTERS);
5196 } else {
5197 pointerIndex += 1;
5198 mAccumulator.pointerCount = pointerIndex;
5199 }
5200 }
5201
5202 mAccumulator.pointers[pointerIndex].clear();
5203 break;
5204 }
5205
5206 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005207 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005208 break;
5209 }
5210 break;
5211 }
5212}
5213
5214void MultiTouchInputMapper::sync(nsecs_t when) {
5215 static const uint32_t REQUIRED_FIELDS =
Jeff Brown8d608662010-08-30 03:02:23 -07005216 Accumulator::FIELD_ABS_MT_POSITION_X | Accumulator::FIELD_ABS_MT_POSITION_Y;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005217
Jeff Brown6d0fec22010-07-23 21:28:06 -07005218 uint32_t inCount = mAccumulator.pointerCount;
5219 uint32_t outCount = 0;
5220 bool havePointerIds = true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005221
Jeff Brown6d0fec22010-07-23 21:28:06 -07005222 mCurrentTouch.clear();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005223
Jeff Brown6d0fec22010-07-23 21:28:06 -07005224 for (uint32_t inIndex = 0; inIndex < inCount; inIndex++) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005225 const Accumulator::Pointer& inPointer = mAccumulator.pointers[inIndex];
5226 uint32_t fields = inPointer.fields;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005227
Jeff Brown6d0fec22010-07-23 21:28:06 -07005228 if ((fields & REQUIRED_FIELDS) != REQUIRED_FIELDS) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005229 // Some drivers send empty MT sync packets without X / Y to indicate a pointer up.
5230 // Drop this finger.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005231 continue;
5232 }
5233
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005234 PointerData& outPointer = mCurrentTouch.pointers[outCount];
5235 outPointer.x = inPointer.absMTPositionX;
5236 outPointer.y = inPointer.absMTPositionY;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005237
Jeff Brown8d608662010-08-30 03:02:23 -07005238 if (fields & Accumulator::FIELD_ABS_MT_PRESSURE) {
5239 if (inPointer.absMTPressure <= 0) {
Jeff Brownc3db8582010-10-20 15:33:38 -07005240 // Some devices send sync packets with X / Y but with a 0 pressure to indicate
5241 // a pointer going up. Drop this finger.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005242 continue;
5243 }
Jeff Brown8d608662010-08-30 03:02:23 -07005244 outPointer.pressure = inPointer.absMTPressure;
5245 } else {
5246 // Default pressure to 0 if absent.
5247 outPointer.pressure = 0;
5248 }
5249
5250 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MAJOR) {
5251 if (inPointer.absMTTouchMajor <= 0) {
5252 // Some devices send sync packets with X / Y but with a 0 touch major to indicate
5253 // a pointer going up. Drop this finger.
5254 continue;
5255 }
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005256 outPointer.touchMajor = inPointer.absMTTouchMajor;
5257 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005258 // Default touch area to 0 if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005259 outPointer.touchMajor = 0;
5260 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005261
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005262 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MINOR) {
5263 outPointer.touchMinor = inPointer.absMTTouchMinor;
5264 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005265 // Assume touch area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005266 outPointer.touchMinor = outPointer.touchMajor;
5267 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005268
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005269 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MAJOR) {
5270 outPointer.toolMajor = inPointer.absMTWidthMajor;
5271 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005272 // Default tool area to 0 if absent.
5273 outPointer.toolMajor = 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005274 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005275
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005276 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MINOR) {
5277 outPointer.toolMinor = inPointer.absMTWidthMinor;
5278 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005279 // Assume tool area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005280 outPointer.toolMinor = outPointer.toolMajor;
5281 }
5282
5283 if (fields & Accumulator::FIELD_ABS_MT_ORIENTATION) {
5284 outPointer.orientation = inPointer.absMTOrientation;
5285 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005286 // Default orientation to vertical if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005287 outPointer.orientation = 0;
5288 }
5289
Jeff Brown8d608662010-08-30 03:02:23 -07005290 // Assign pointer id using tracking id if available.
Jeff Brown6d0fec22010-07-23 21:28:06 -07005291 if (havePointerIds) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005292 if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) {
5293 uint32_t id = uint32_t(inPointer.absMTTrackingId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005294
Jeff Brown6d0fec22010-07-23 21:28:06 -07005295 if (id > MAX_POINTER_ID) {
5296#if DEBUG_POINTERS
5297 LOGD("Pointers: Ignoring driver provided pointer id %d because "
Jeff Brown01ce2e92010-09-26 22:20:12 -07005298 "it is larger than max supported id %d",
Jeff Brown6d0fec22010-07-23 21:28:06 -07005299 id, MAX_POINTER_ID);
5300#endif
5301 havePointerIds = false;
5302 }
5303 else {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005304 outPointer.id = id;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005305 mCurrentTouch.idToIndex[id] = outCount;
5306 mCurrentTouch.idBits.markBit(id);
5307 }
5308 } else {
5309 havePointerIds = false;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005310 }
5311 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005312
Jeff Brown6d0fec22010-07-23 21:28:06 -07005313 outCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005314 }
5315
Jeff Brown6d0fec22010-07-23 21:28:06 -07005316 mCurrentTouch.pointerCount = outCount;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005317
Jeff Brown96ad3972011-03-09 17:39:48 -08005318 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
5319 mCurrentTouch.buttonState = mButtonState;
5320
Jeff Brown6d0fec22010-07-23 21:28:06 -07005321 syncTouch(when, havePointerIds);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005322
5323 mAccumulator.clear();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005324}
5325
Jeff Brown8d608662010-08-30 03:02:23 -07005326void MultiTouchInputMapper::configureRawAxes() {
5327 TouchInputMapper::configureRawAxes();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005328
Jeff Brown8d608662010-08-30 03:02:23 -07005329 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_X, & mRawAxes.x);
5330 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_Y, & mRawAxes.y);
5331 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MAJOR, & mRawAxes.touchMajor);
5332 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MINOR, & mRawAxes.touchMinor);
5333 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MAJOR, & mRawAxes.toolMajor);
5334 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MINOR, & mRawAxes.toolMinor);
5335 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_ORIENTATION, & mRawAxes.orientation);
5336 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_PRESSURE, & mRawAxes.pressure);
Jeff Brown9c3cda02010-06-15 01:31:58 -07005337}
5338
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005339
Jeff Browncb1404e2011-01-15 18:14:15 -08005340// --- JoystickInputMapper ---
5341
5342JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
5343 InputMapper(device) {
Jeff Browncb1404e2011-01-15 18:14:15 -08005344}
5345
5346JoystickInputMapper::~JoystickInputMapper() {
5347}
5348
5349uint32_t JoystickInputMapper::getSources() {
5350 return AINPUT_SOURCE_JOYSTICK;
5351}
5352
5353void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
5354 InputMapper::populateDeviceInfo(info);
5355
Jeff Brown6f2fba42011-02-19 01:08:02 -08005356 for (size_t i = 0; i < mAxes.size(); i++) {
5357 const Axis& axis = mAxes.valueAt(i);
Jeff Brownefd32662011-03-08 15:13:06 -08005358 info->addMotionRange(axis.axisInfo.axis, AINPUT_SOURCE_JOYSTICK,
5359 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08005360 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
Jeff Brownefd32662011-03-08 15:13:06 -08005361 info->addMotionRange(axis.axisInfo.highAxis, AINPUT_SOURCE_JOYSTICK,
5362 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08005363 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005364 }
5365}
5366
5367void JoystickInputMapper::dump(String8& dump) {
5368 dump.append(INDENT2 "Joystick Input Mapper:\n");
5369
Jeff Brown6f2fba42011-02-19 01:08:02 -08005370 dump.append(INDENT3 "Axes:\n");
5371 size_t numAxes = mAxes.size();
5372 for (size_t i = 0; i < numAxes; i++) {
5373 const Axis& axis = mAxes.valueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005374 const char* label = getAxisLabel(axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005375 if (label) {
Jeff Brown85297452011-03-04 13:07:49 -08005376 dump.appendFormat(INDENT4 "%s", label);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005377 } else {
Jeff Brown85297452011-03-04 13:07:49 -08005378 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005379 }
Jeff Brown85297452011-03-04 13:07:49 -08005380 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5381 label = getAxisLabel(axis.axisInfo.highAxis);
5382 if (label) {
5383 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
5384 } else {
5385 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
5386 axis.axisInfo.splitValue);
5387 }
5388 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
5389 dump.append(" (invert)");
5390 }
5391
5392 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f\n",
5393 axis.min, axis.max, axis.flat, axis.fuzz);
5394 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
5395 "highScale=%0.5f, highOffset=%0.5f\n",
5396 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005397 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, rawFlat=%d, rawFuzz=%d\n",
5398 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
5399 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz);
Jeff Browncb1404e2011-01-15 18:14:15 -08005400 }
5401}
5402
5403void JoystickInputMapper::configure() {
5404 InputMapper::configure();
5405
Jeff Brown6f2fba42011-02-19 01:08:02 -08005406 // Collect all axes.
5407 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
5408 RawAbsoluteAxisInfo rawAxisInfo;
5409 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), abs, &rawAxisInfo);
5410 if (rawAxisInfo.valid) {
Jeff Brown85297452011-03-04 13:07:49 -08005411 // Map axis.
5412 AxisInfo axisInfo;
5413 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005414 if (!explicitlyMapped) {
5415 // Axis is not explicitly mapped, will choose a generic axis later.
Jeff Brown85297452011-03-04 13:07:49 -08005416 axisInfo.mode = AxisInfo::MODE_NORMAL;
5417 axisInfo.axis = -1;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005418 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005419
Jeff Brown85297452011-03-04 13:07:49 -08005420 // Apply flat override.
5421 int32_t rawFlat = axisInfo.flatOverride < 0
5422 ? rawAxisInfo.flat : axisInfo.flatOverride;
5423
5424 // Calculate scaling factors and limits.
Jeff Brown6f2fba42011-02-19 01:08:02 -08005425 Axis axis;
Jeff Brown85297452011-03-04 13:07:49 -08005426 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
5427 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
5428 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
5429 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5430 scale, 0.0f, highScale, 0.0f,
5431 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
5432 } else if (isCenteredAxis(axisInfo.axis)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005433 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
5434 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
Jeff Brown85297452011-03-04 13:07:49 -08005435 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5436 scale, offset, scale, offset,
5437 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005438 } else {
5439 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
Jeff Brown85297452011-03-04 13:07:49 -08005440 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5441 scale, 0.0f, scale, 0.0f,
5442 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005443 }
5444
5445 // To eliminate noise while the joystick is at rest, filter out small variations
5446 // in axis values up front.
5447 axis.filter = axis.flat * 0.25f;
5448
5449 mAxes.add(abs, axis);
5450 }
5451 }
5452
5453 // If there are too many axes, start dropping them.
5454 // Prefer to keep explicitly mapped axes.
5455 if (mAxes.size() > PointerCoords::MAX_AXES) {
5456 LOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.",
5457 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
5458 pruneAxes(true);
5459 pruneAxes(false);
5460 }
5461
5462 // Assign generic axis ids to remaining axes.
5463 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
5464 size_t numAxes = mAxes.size();
5465 for (size_t i = 0; i < numAxes; i++) {
5466 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005467 if (axis.axisInfo.axis < 0) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005468 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
5469 && haveAxis(nextGenericAxisId)) {
5470 nextGenericAxisId += 1;
5471 }
5472
5473 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
Jeff Brown85297452011-03-04 13:07:49 -08005474 axis.axisInfo.axis = nextGenericAxisId;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005475 nextGenericAxisId += 1;
5476 } else {
5477 LOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
5478 "have already been assigned to other axes.",
5479 getDeviceName().string(), mAxes.keyAt(i));
5480 mAxes.removeItemsAt(i--);
5481 numAxes -= 1;
5482 }
5483 }
5484 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005485}
5486
Jeff Brown85297452011-03-04 13:07:49 -08005487bool JoystickInputMapper::haveAxis(int32_t axisId) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005488 size_t numAxes = mAxes.size();
5489 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005490 const Axis& axis = mAxes.valueAt(i);
5491 if (axis.axisInfo.axis == axisId
5492 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
5493 && axis.axisInfo.highAxis == axisId)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005494 return true;
5495 }
5496 }
5497 return false;
5498}
Jeff Browncb1404e2011-01-15 18:14:15 -08005499
Jeff Brown6f2fba42011-02-19 01:08:02 -08005500void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
5501 size_t i = mAxes.size();
5502 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
5503 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
5504 continue;
5505 }
5506 LOGI("Discarding joystick '%s' axis %d because there are too many axes.",
5507 getDeviceName().string(), mAxes.keyAt(i));
5508 mAxes.removeItemsAt(i);
5509 }
5510}
5511
5512bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
5513 switch (axis) {
5514 case AMOTION_EVENT_AXIS_X:
5515 case AMOTION_EVENT_AXIS_Y:
5516 case AMOTION_EVENT_AXIS_Z:
5517 case AMOTION_EVENT_AXIS_RX:
5518 case AMOTION_EVENT_AXIS_RY:
5519 case AMOTION_EVENT_AXIS_RZ:
5520 case AMOTION_EVENT_AXIS_HAT_X:
5521 case AMOTION_EVENT_AXIS_HAT_Y:
5522 case AMOTION_EVENT_AXIS_ORIENTATION:
Jeff Brown85297452011-03-04 13:07:49 -08005523 case AMOTION_EVENT_AXIS_RUDDER:
5524 case AMOTION_EVENT_AXIS_WHEEL:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005525 return true;
5526 default:
5527 return false;
5528 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005529}
5530
5531void JoystickInputMapper::reset() {
5532 // Recenter all axes.
5533 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Browncb1404e2011-01-15 18:14:15 -08005534
Jeff Brown6f2fba42011-02-19 01:08:02 -08005535 size_t numAxes = mAxes.size();
5536 for (size_t i = 0; i < numAxes; i++) {
5537 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005538 axis.resetValue();
Jeff Brown6f2fba42011-02-19 01:08:02 -08005539 }
5540
5541 sync(when, true /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005542
5543 InputMapper::reset();
5544}
5545
5546void JoystickInputMapper::process(const RawEvent* rawEvent) {
5547 switch (rawEvent->type) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005548 case EV_ABS: {
5549 ssize_t index = mAxes.indexOfKey(rawEvent->scanCode);
5550 if (index >= 0) {
5551 Axis& axis = mAxes.editValueAt(index);
Jeff Brown85297452011-03-04 13:07:49 -08005552 float newValue, highNewValue;
5553 switch (axis.axisInfo.mode) {
5554 case AxisInfo::MODE_INVERT:
5555 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
5556 * axis.scale + axis.offset;
5557 highNewValue = 0.0f;
5558 break;
5559 case AxisInfo::MODE_SPLIT:
5560 if (rawEvent->value < axis.axisInfo.splitValue) {
5561 newValue = (axis.axisInfo.splitValue - rawEvent->value)
5562 * axis.scale + axis.offset;
5563 highNewValue = 0.0f;
5564 } else if (rawEvent->value > axis.axisInfo.splitValue) {
5565 newValue = 0.0f;
5566 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
5567 * axis.highScale + axis.highOffset;
5568 } else {
5569 newValue = 0.0f;
5570 highNewValue = 0.0f;
5571 }
5572 break;
5573 default:
5574 newValue = rawEvent->value * axis.scale + axis.offset;
5575 highNewValue = 0.0f;
5576 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005577 }
Jeff Brown85297452011-03-04 13:07:49 -08005578 axis.newValue = newValue;
5579 axis.highNewValue = highNewValue;
Jeff Browncb1404e2011-01-15 18:14:15 -08005580 }
5581 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005582 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005583
5584 case EV_SYN:
5585 switch (rawEvent->scanCode) {
5586 case SYN_REPORT:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005587 sync(rawEvent->when, false /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005588 break;
5589 }
5590 break;
5591 }
5592}
5593
Jeff Brown6f2fba42011-02-19 01:08:02 -08005594void JoystickInputMapper::sync(nsecs_t when, bool force) {
Jeff Brown85297452011-03-04 13:07:49 -08005595 if (!filterAxes(force)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005596 return;
Jeff Browncb1404e2011-01-15 18:14:15 -08005597 }
5598
5599 int32_t metaState = mContext->getGlobalMetaState();
5600
Jeff Brown6f2fba42011-02-19 01:08:02 -08005601 PointerCoords pointerCoords;
5602 pointerCoords.clear();
5603
5604 size_t numAxes = mAxes.size();
5605 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005606 const Axis& axis = mAxes.valueAt(i);
5607 pointerCoords.setAxisValue(axis.axisInfo.axis, axis.currentValue);
5608 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5609 pointerCoords.setAxisValue(axis.axisInfo.highAxis, axis.highCurrentValue);
5610 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005611 }
5612
Jeff Brown56194eb2011-03-02 19:23:13 -08005613 // Moving a joystick axis should not wake the devide because joysticks can
5614 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
5615 // button will likely wake the device.
5616 // TODO: Use the input device configuration to control this behavior more finely.
5617 uint32_t policyFlags = 0;
5618
Jeff Brown6f2fba42011-02-19 01:08:02 -08005619 int32_t pointerId = 0;
Jeff Brown56194eb2011-03-02 19:23:13 -08005620 getDispatcher()->notifyMotion(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Jeff Brown6f2fba42011-02-19 01:08:02 -08005621 AMOTION_EVENT_ACTION_MOVE, 0, metaState, AMOTION_EVENT_EDGE_FLAG_NONE,
5622 1, &pointerId, &pointerCoords, 0, 0, 0);
Jeff Browncb1404e2011-01-15 18:14:15 -08005623}
5624
Jeff Brown85297452011-03-04 13:07:49 -08005625bool JoystickInputMapper::filterAxes(bool force) {
5626 bool atLeastOneSignificantChange = force;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005627 size_t numAxes = mAxes.size();
5628 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005629 Axis& axis = mAxes.editValueAt(i);
5630 if (force || hasValueChangedSignificantly(axis.filter,
5631 axis.newValue, axis.currentValue, axis.min, axis.max)) {
5632 axis.currentValue = axis.newValue;
5633 atLeastOneSignificantChange = true;
5634 }
5635 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5636 if (force || hasValueChangedSignificantly(axis.filter,
5637 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
5638 axis.highCurrentValue = axis.highNewValue;
5639 atLeastOneSignificantChange = true;
5640 }
5641 }
5642 }
5643 return atLeastOneSignificantChange;
5644}
5645
5646bool JoystickInputMapper::hasValueChangedSignificantly(
5647 float filter, float newValue, float currentValue, float min, float max) {
5648 if (newValue != currentValue) {
5649 // Filter out small changes in value unless the value is converging on the axis
5650 // bounds or center point. This is intended to reduce the amount of information
5651 // sent to applications by particularly noisy joysticks (such as PS3).
5652 if (fabs(newValue - currentValue) > filter
5653 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
5654 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
5655 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
5656 return true;
5657 }
5658 }
5659 return false;
5660}
5661
5662bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
5663 float filter, float newValue, float currentValue, float thresholdValue) {
5664 float newDistance = fabs(newValue - thresholdValue);
5665 if (newDistance < filter) {
5666 float oldDistance = fabs(currentValue - thresholdValue);
5667 if (newDistance < oldDistance) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005668 return true;
5669 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005670 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08005671 return false;
Jeff Browncb1404e2011-01-15 18:14:15 -08005672}
5673
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005674} // namespace android