blob: 79218a5581ca70052330dc9e064fd4e9810be674 [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 Brown9f2106f2011-05-24 14:40:35 -070031#define DEBUG_POINTERS 0
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070032
Jeff Brown5c225b12010-06-16 01:53:36 -070033// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
Jeff Brownace13b12011-03-09 17:39:48 -080036// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
Jeff Brownb4ff35d2011-01-02 16:37:43 -080039#include "InputReader.h"
40
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070041#include <cutils/log.h>
Jeff Brown6b53e8d2010-11-10 16:03:06 -080042#include <ui/Keyboard.h>
Jeff Brown90655042010-12-02 13:50:46 -080043#include <ui/VirtualKeyMap.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070044
45#include <stddef.h>
Jeff Brown8d608662010-08-30 03:02:23 -070046#include <stdlib.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070047#include <unistd.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070048#include <errno.h>
49#include <limits.h>
Jeff Brownc5ed5912010-07-14 18:48:53 -070050#include <math.h>
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070051
Jeff Brown8d608662010-08-30 03:02:23 -070052#define INDENT " "
Jeff Brownef3d7e82010-09-30 14:33:04 -070053#define INDENT2 " "
54#define INDENT3 " "
55#define INDENT4 " "
Jeff Brownaba321a2011-06-28 20:34:40 -070056#define INDENT5 " "
Jeff Brown8d608662010-08-30 03:02:23 -070057
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070058namespace android {
59
Jeff Brownace13b12011-03-09 17:39:48 -080060// --- Constants ---
61
Jeff Brown80fd47c2011-05-24 01:07:44 -070062// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
63static const size_t MAX_SLOTS = 32;
64
Jeff Brown46b9ac0a2010-04-22 18:58:52 -070065// --- Static Functions ---
66
67template<typename T>
68inline static T abs(const T& value) {
69 return value < 0 ? - value : value;
70}
71
72template<typename T>
73inline static T min(const T& a, const T& b) {
74 return a < b ? a : b;
75}
76
Jeff Brown5c225b12010-06-16 01:53:36 -070077template<typename T>
78inline static void swap(T& a, T& b) {
79 T temp = a;
80 a = b;
81 b = temp;
82}
83
Jeff Brown8d608662010-08-30 03:02:23 -070084inline static float avg(float x, float y) {
85 return (x + y) / 2;
86}
87
Jeff Brown2352b972011-04-12 22:39:53 -070088inline static float distance(float x1, float y1, float x2, float y2) {
89 return hypotf(x1 - x2, y1 - y2);
Jeff Brownace13b12011-03-09 17:39:48 -080090}
91
Jeff Brown517bb4c2011-01-14 19:09:23 -080092inline static int32_t signExtendNybble(int32_t value) {
93 return value >= 8 ? value - 16 : value;
94}
95
Jeff Brownef3d7e82010-09-30 14:33:04 -070096static inline const char* toString(bool value) {
97 return value ? "true" : "false";
98}
99
Jeff Brown9626b142011-03-03 02:09:54 -0800100static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
101 const int32_t map[][4], size_t mapSize) {
102 if (orientation != DISPLAY_ORIENTATION_0) {
103 for (size_t i = 0; i < mapSize; i++) {
104 if (value == map[i][0]) {
105 return map[i][orientation];
106 }
107 }
108 }
109 return value;
110}
111
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700112static const int32_t keyCodeRotationMap[][4] = {
113 // key codes enumerated counter-clockwise with the original (unrotated) key first
114 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
Jeff Brownfd0358292010-06-30 16:10:35 -0700115 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
116 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
117 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
118 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700119};
Jeff Brown9626b142011-03-03 02:09:54 -0800120static const size_t keyCodeRotationMapSize =
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700121 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
122
123int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Jeff Brown9626b142011-03-03 02:09:54 -0800124 return rotateValueUsingRotationMap(keyCode, orientation,
125 keyCodeRotationMap, keyCodeRotationMapSize);
126}
127
128static const int32_t edgeFlagRotationMap[][4] = {
129 // edge flags enumerated counter-clockwise with the original (unrotated) edge flag first
130 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
131 { AMOTION_EVENT_EDGE_FLAG_BOTTOM, AMOTION_EVENT_EDGE_FLAG_RIGHT,
132 AMOTION_EVENT_EDGE_FLAG_TOP, AMOTION_EVENT_EDGE_FLAG_LEFT },
133 { AMOTION_EVENT_EDGE_FLAG_RIGHT, AMOTION_EVENT_EDGE_FLAG_TOP,
134 AMOTION_EVENT_EDGE_FLAG_LEFT, AMOTION_EVENT_EDGE_FLAG_BOTTOM },
135 { AMOTION_EVENT_EDGE_FLAG_TOP, AMOTION_EVENT_EDGE_FLAG_LEFT,
136 AMOTION_EVENT_EDGE_FLAG_BOTTOM, AMOTION_EVENT_EDGE_FLAG_RIGHT },
137 { AMOTION_EVENT_EDGE_FLAG_LEFT, AMOTION_EVENT_EDGE_FLAG_BOTTOM,
138 AMOTION_EVENT_EDGE_FLAG_RIGHT, AMOTION_EVENT_EDGE_FLAG_TOP },
139};
140static const size_t edgeFlagRotationMapSize =
141 sizeof(edgeFlagRotationMap) / sizeof(edgeFlagRotationMap[0]);
142
143static int32_t rotateEdgeFlag(int32_t edgeFlag, int32_t orientation) {
144 return rotateValueUsingRotationMap(edgeFlag, orientation,
145 edgeFlagRotationMap, edgeFlagRotationMapSize);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700146}
147
Jeff Brown6d0fec22010-07-23 21:28:06 -0700148static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
149 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
150}
151
Jeff Brownefd32662011-03-08 15:13:06 -0800152static uint32_t getButtonStateForScanCode(int32_t scanCode) {
153 // Currently all buttons are mapped to the primary button.
154 switch (scanCode) {
155 case BTN_LEFT:
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700156 return AMOTION_EVENT_BUTTON_PRIMARY;
Jeff Brownefd32662011-03-08 15:13:06 -0800157 case BTN_RIGHT:
Jeff Brown53ca3f12011-06-27 18:36:00 -0700158 case BTN_STYLUS:
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700159 return AMOTION_EVENT_BUTTON_SECONDARY;
Jeff Brownefd32662011-03-08 15:13:06 -0800160 case BTN_MIDDLE:
Jeff Brown53ca3f12011-06-27 18:36:00 -0700161 case BTN_STYLUS2:
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700162 return AMOTION_EVENT_BUTTON_TERTIARY;
Jeff Brownefd32662011-03-08 15:13:06 -0800163 case BTN_SIDE:
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700164 return AMOTION_EVENT_BUTTON_BACK;
Jeff Brownefd32662011-03-08 15:13:06 -0800165 case BTN_FORWARD:
Jeff Brown53ca3f12011-06-27 18:36:00 -0700166 case BTN_EXTRA:
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700167 return AMOTION_EVENT_BUTTON_FORWARD;
Jeff Brownefd32662011-03-08 15:13:06 -0800168 case BTN_BACK:
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700169 return AMOTION_EVENT_BUTTON_BACK;
Jeff Brownefd32662011-03-08 15:13:06 -0800170 case BTN_TASK:
Jeff Brownefd32662011-03-08 15:13:06 -0800171 default:
172 return 0;
173 }
174}
175
176// Returns true if the pointer should be reported as being down given the specified
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700177// button states. This determines whether the event is reported as a touch event.
178static bool isPointerDown(int32_t buttonState) {
179 return buttonState &
180 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
Jeff Brown53ca3f12011-06-27 18:36:00 -0700181 | AMOTION_EVENT_BUTTON_TERTIARY);
Jeff Brownefd32662011-03-08 15:13:06 -0800182}
183
184static int32_t calculateEdgeFlagsUsingPointerBounds(
185 const sp<PointerControllerInterface>& pointerController, float x, float y) {
186 int32_t edgeFlags = 0;
187 float minX, minY, maxX, maxY;
188 if (pointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
189 if (x <= minX) {
190 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_LEFT;
191 } else if (x >= maxX) {
192 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_RIGHT;
193 }
194 if (y <= minY) {
195 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_TOP;
196 } else if (y >= maxY) {
197 edgeFlags |= AMOTION_EVENT_EDGE_FLAG_BOTTOM;
198 }
199 }
200 return edgeFlags;
201}
202
Jeff Brown2352b972011-04-12 22:39:53 -0700203static float calculateCommonVector(float a, float b) {
204 if (a > 0 && b > 0) {
205 return a < b ? a : b;
206 } else if (a < 0 && b < 0) {
207 return a > b ? a : b;
208 } else {
209 return 0;
210 }
211}
212
Jeff Brownfe9f8ab2011-05-06 18:20:01 -0700213static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
214 nsecs_t when, int32_t deviceId, uint32_t source,
215 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
216 int32_t buttonState, int32_t keyCode) {
217 if (
218 (action == AKEY_EVENT_ACTION_DOWN
219 && !(lastButtonState & buttonState)
220 && (currentButtonState & buttonState))
221 || (action == AKEY_EVENT_ACTION_UP
222 && (lastButtonState & buttonState)
223 && !(currentButtonState & buttonState))) {
224 context->getDispatcher()->notifyKey(when, deviceId, source, policyFlags,
225 action, 0, keyCode, 0, context->getGlobalMetaState(), when);
226 }
227}
228
229static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
230 nsecs_t when, int32_t deviceId, uint32_t source,
231 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
232 synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
233 lastButtonState, currentButtonState,
234 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
235 synthesizeButtonKey(context, action, when, deviceId, source, policyFlags,
236 lastButtonState, currentButtonState,
237 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
238}
239
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700240
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700241// --- InputReader ---
242
243InputReader::InputReader(const sp<EventHubInterface>& eventHub,
Jeff Brown9c3cda02010-06-15 01:31:58 -0700244 const sp<InputReaderPolicyInterface>& policy,
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700245 const sp<InputDispatcherInterface>& dispatcher) :
Jeff Brown6d0fec22010-07-23 21:28:06 -0700246 mEventHub(eventHub), mPolicy(policy), mDispatcher(dispatcher),
Jeff Brown1a84fd12011-06-02 01:26:32 -0700247 mGlobalMetaState(0), mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
Jeff Brown474dcb52011-06-14 20:22:50 -0700248 mConfigurationChangesToRefresh(0) {
249 refreshConfiguration(0);
Jeff Brown6d0fec22010-07-23 21:28:06 -0700250 updateGlobalMetaState();
251 updateInputConfiguration();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700252}
253
254InputReader::~InputReader() {
255 for (size_t i = 0; i < mDevices.size(); i++) {
256 delete mDevices.valueAt(i);
257 }
258}
259
260void InputReader::loopOnce() {
Jeff Brown474dcb52011-06-14 20:22:50 -0700261 uint32_t changes;
262 { // acquire lock
263 AutoMutex _l(mStateLock);
264
265 changes = mConfigurationChangesToRefresh;
266 mConfigurationChangesToRefresh = 0;
267 } // release lock
268
269 if (changes) {
270 refreshConfiguration(changes);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700271 }
272
Jeff Brownaa3855d2011-03-17 01:34:19 -0700273 int32_t timeoutMillis = -1;
274 if (mNextTimeout != LLONG_MAX) {
275 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
276 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
277 }
278
Jeff Brownb7198742011-03-18 18:14:26 -0700279 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
280 if (count) {
281 processEvents(mEventBuffer, count);
282 }
283 if (!count || timeoutMillis == 0) {
Jeff Brownaa3855d2011-03-17 01:34:19 -0700284 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
285#if DEBUG_RAW_EVENTS
286 LOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
287#endif
288 mNextTimeout = LLONG_MAX;
289 timeoutExpired(now);
290 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700291}
292
Jeff Brownb7198742011-03-18 18:14:26 -0700293void InputReader::processEvents(const RawEvent* rawEvents, size_t count) {
294 for (const RawEvent* rawEvent = rawEvents; count;) {
295 int32_t type = rawEvent->type;
296 size_t batchSize = 1;
297 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
298 int32_t deviceId = rawEvent->deviceId;
299 while (batchSize < count) {
300 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
301 || rawEvent[batchSize].deviceId != deviceId) {
302 break;
303 }
304 batchSize += 1;
305 }
306#if DEBUG_RAW_EVENTS
307 LOGD("BatchSize: %d Count: %d", batchSize, count);
308#endif
309 processEventsForDevice(deviceId, rawEvent, batchSize);
310 } else {
311 switch (rawEvent->type) {
312 case EventHubInterface::DEVICE_ADDED:
313 addDevice(rawEvent->deviceId);
314 break;
315 case EventHubInterface::DEVICE_REMOVED:
316 removeDevice(rawEvent->deviceId);
317 break;
318 case EventHubInterface::FINISHED_DEVICE_SCAN:
319 handleConfigurationChanged(rawEvent->when);
320 break;
321 default:
Jeff Brownb6110c22011-04-01 16:15:13 -0700322 LOG_ASSERT(false); // can't happen
Jeff Brownb7198742011-03-18 18:14:26 -0700323 break;
324 }
325 }
326 count -= batchSize;
327 rawEvent += batchSize;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700328 }
329}
330
Jeff Brown7342bb92010-10-01 18:55:43 -0700331void InputReader::addDevice(int32_t deviceId) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700332 String8 name = mEventHub->getDeviceName(deviceId);
333 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
334
335 InputDevice* device = createDevice(deviceId, name, classes);
Jeff Brown474dcb52011-06-14 20:22:50 -0700336 device->configure(&mConfig, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -0700337
Jeff Brown8d608662010-08-30 03:02:23 -0700338 if (device->isIgnored()) {
Jeff Brown90655042010-12-02 13:50:46 -0800339 LOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, name.string());
Jeff Brown8d608662010-08-30 03:02:23 -0700340 } else {
Jeff Brown90655042010-12-02 13:50:46 -0800341 LOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, name.string(),
Jeff Brownef3d7e82010-09-30 14:33:04 -0700342 device->getSources());
Jeff Brown8d608662010-08-30 03:02:23 -0700343 }
344
Jeff Brown6d0fec22010-07-23 21:28:06 -0700345 bool added = false;
346 { // acquire device registry writer lock
347 RWLock::AutoWLock _wl(mDeviceRegistryLock);
348
349 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
350 if (deviceIndex < 0) {
351 mDevices.add(deviceId, device);
352 added = true;
353 }
354 } // release device registry writer lock
355
356 if (! added) {
357 LOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
358 delete device;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700359 return;
360 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700361}
362
Jeff Brown7342bb92010-10-01 18:55:43 -0700363void InputReader::removeDevice(int32_t deviceId) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700364 bool removed = false;
365 InputDevice* device = NULL;
366 { // acquire device registry writer lock
367 RWLock::AutoWLock _wl(mDeviceRegistryLock);
368
369 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
370 if (deviceIndex >= 0) {
371 device = mDevices.valueAt(deviceIndex);
372 mDevices.removeItemsAt(deviceIndex, 1);
373 removed = true;
374 }
375 } // release device registry writer lock
376
377 if (! removed) {
378 LOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700379 return;
380 }
381
Jeff Brown6d0fec22010-07-23 21:28:06 -0700382 if (device->isIgnored()) {
Jeff Brown90655042010-12-02 13:50:46 -0800383 LOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Jeff Brown6d0fec22010-07-23 21:28:06 -0700384 device->getId(), device->getName().string());
385 } else {
Jeff Brown90655042010-12-02 13:50:46 -0800386 LOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Jeff Brown6d0fec22010-07-23 21:28:06 -0700387 device->getId(), device->getName().string(), device->getSources());
388 }
389
Jeff Brown8d608662010-08-30 03:02:23 -0700390 device->reset();
391
Jeff Brown6d0fec22010-07-23 21:28:06 -0700392 delete device;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700393}
394
Jeff Brown6d0fec22010-07-23 21:28:06 -0700395InputDevice* InputReader::createDevice(int32_t deviceId, const String8& name, uint32_t classes) {
396 InputDevice* device = new InputDevice(this, deviceId, name);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700397
Jeff Brown56194eb2011-03-02 19:23:13 -0800398 // External devices.
399 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
400 device->setExternal(true);
401 }
402
Jeff Brown6d0fec22010-07-23 21:28:06 -0700403 // Switch-like devices.
404 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
405 device->addMapper(new SwitchInputMapper(device));
406 }
407
408 // Keyboard-like devices.
Jeff Brownefd32662011-03-08 15:13:06 -0800409 uint32_t keyboardSource = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700410 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
411 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800412 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700413 }
414 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
415 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
416 }
417 if (classes & INPUT_DEVICE_CLASS_DPAD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800418 keyboardSource |= AINPUT_SOURCE_DPAD;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700419 }
Jeff Browncb1404e2011-01-15 18:14:15 -0800420 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Jeff Brownefd32662011-03-08 15:13:06 -0800421 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
Jeff Browncb1404e2011-01-15 18:14:15 -0800422 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700423
Jeff Brownefd32662011-03-08 15:13:06 -0800424 if (keyboardSource != 0) {
425 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700426 }
427
Jeff Brown83c09682010-12-23 17:50:18 -0800428 // Cursor-like devices.
429 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
430 device->addMapper(new CursorInputMapper(device));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700431 }
432
Jeff Brown58a2da82011-01-25 16:02:22 -0800433 // Touchscreens and touchpad devices.
434 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800435 device->addMapper(new MultiTouchInputMapper(device));
Jeff Brown58a2da82011-01-25 16:02:22 -0800436 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800437 device->addMapper(new SingleTouchInputMapper(device));
Jeff Brown6d0fec22010-07-23 21:28:06 -0700438 }
439
Jeff Browncb1404e2011-01-15 18:14:15 -0800440 // Joystick-like devices.
441 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
442 device->addMapper(new JoystickInputMapper(device));
443 }
444
Jeff Brown6d0fec22010-07-23 21:28:06 -0700445 return device;
446}
447
Jeff Brownb7198742011-03-18 18:14:26 -0700448void InputReader::processEventsForDevice(int32_t deviceId,
449 const RawEvent* rawEvents, size_t count) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700450 { // acquire device registry reader lock
451 RWLock::AutoRLock _rl(mDeviceRegistryLock);
452
453 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
454 if (deviceIndex < 0) {
455 LOGW("Discarding event for unknown deviceId %d.", deviceId);
456 return;
457 }
458
459 InputDevice* device = mDevices.valueAt(deviceIndex);
460 if (device->isIgnored()) {
461 //LOGD("Discarding event for ignored deviceId %d.", deviceId);
462 return;
463 }
464
Jeff Brownb7198742011-03-18 18:14:26 -0700465 device->process(rawEvents, count);
Jeff Brown6d0fec22010-07-23 21:28:06 -0700466 } // release device registry reader lock
467}
468
Jeff Brownaa3855d2011-03-17 01:34:19 -0700469void InputReader::timeoutExpired(nsecs_t when) {
470 { // acquire device registry reader lock
471 RWLock::AutoRLock _rl(mDeviceRegistryLock);
472
473 for (size_t i = 0; i < mDevices.size(); i++) {
474 InputDevice* device = mDevices.valueAt(i);
475 if (!device->isIgnored()) {
476 device->timeoutExpired(when);
477 }
478 }
479 } // release device registry reader lock
480}
481
Jeff Brownc3db8582010-10-20 15:33:38 -0700482void InputReader::handleConfigurationChanged(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700483 // Reset global meta state because it depends on the list of all configured devices.
484 updateGlobalMetaState();
485
486 // Update input configuration.
487 updateInputConfiguration();
488
489 // Enqueue configuration changed.
490 mDispatcher->notifyConfigurationChanged(when);
491}
492
Jeff Brown474dcb52011-06-14 20:22:50 -0700493void InputReader::refreshConfiguration(uint32_t changes) {
Jeff Brown1a84fd12011-06-02 01:26:32 -0700494 mPolicy->getReaderConfiguration(&mConfig);
495 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
496
Jeff Brown474dcb52011-06-14 20:22:50 -0700497 if (changes) {
498 LOGI("Reconfiguring input devices. changes=0x%08x", changes);
499
500 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
501 mEventHub->requestReopenDevices();
502 } else {
503 { // acquire device registry reader lock
504 RWLock::AutoRLock _rl(mDeviceRegistryLock);
505
506 for (size_t i = 0; i < mDevices.size(); i++) {
507 InputDevice* device = mDevices.valueAt(i);
508 device->configure(&mConfig, changes);
509 }
510 } // release device registry reader lock
511 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700512 }
513}
514
515void InputReader::updateGlobalMetaState() {
516 { // acquire state lock
517 AutoMutex _l(mStateLock);
518
519 mGlobalMetaState = 0;
520
521 { // acquire device registry reader lock
522 RWLock::AutoRLock _rl(mDeviceRegistryLock);
523
524 for (size_t i = 0; i < mDevices.size(); i++) {
525 InputDevice* device = mDevices.valueAt(i);
526 mGlobalMetaState |= device->getMetaState();
527 }
528 } // release device registry reader lock
529 } // release state lock
530}
531
532int32_t InputReader::getGlobalMetaState() {
533 { // acquire state lock
534 AutoMutex _l(mStateLock);
535
536 return mGlobalMetaState;
537 } // release state lock
538}
539
540void InputReader::updateInputConfiguration() {
541 { // acquire state lock
542 AutoMutex _l(mStateLock);
543
544 int32_t touchScreenConfig = InputConfiguration::TOUCHSCREEN_NOTOUCH;
545 int32_t keyboardConfig = InputConfiguration::KEYBOARD_NOKEYS;
546 int32_t navigationConfig = InputConfiguration::NAVIGATION_NONAV;
547 { // acquire device registry reader lock
548 RWLock::AutoRLock _rl(mDeviceRegistryLock);
549
550 InputDeviceInfo deviceInfo;
551 for (size_t i = 0; i < mDevices.size(); i++) {
552 InputDevice* device = mDevices.valueAt(i);
553 device->getDeviceInfo(& deviceInfo);
554 uint32_t sources = deviceInfo.getSources();
555
556 if ((sources & AINPUT_SOURCE_TOUCHSCREEN) == AINPUT_SOURCE_TOUCHSCREEN) {
557 touchScreenConfig = InputConfiguration::TOUCHSCREEN_FINGER;
558 }
559 if ((sources & AINPUT_SOURCE_TRACKBALL) == AINPUT_SOURCE_TRACKBALL) {
560 navigationConfig = InputConfiguration::NAVIGATION_TRACKBALL;
561 } else if ((sources & AINPUT_SOURCE_DPAD) == AINPUT_SOURCE_DPAD) {
562 navigationConfig = InputConfiguration::NAVIGATION_DPAD;
563 }
564 if (deviceInfo.getKeyboardType() == AINPUT_KEYBOARD_TYPE_ALPHABETIC) {
565 keyboardConfig = InputConfiguration::KEYBOARD_QWERTY;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700566 }
567 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700568 } // release device registry reader lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700569
Jeff Brown6d0fec22010-07-23 21:28:06 -0700570 mInputConfiguration.touchScreen = touchScreenConfig;
571 mInputConfiguration.keyboard = keyboardConfig;
572 mInputConfiguration.navigation = navigationConfig;
573 } // release state lock
574}
575
Jeff Brownfe508922011-01-18 15:10:10 -0800576void InputReader::disableVirtualKeysUntil(nsecs_t time) {
577 mDisableVirtualKeysTimeout = time;
578}
579
580bool InputReader::shouldDropVirtualKey(nsecs_t now,
581 InputDevice* device, int32_t keyCode, int32_t scanCode) {
582 if (now < mDisableVirtualKeysTimeout) {
583 LOGI("Dropping virtual key from device %s because virtual keys are "
584 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
585 device->getName().string(),
586 (mDisableVirtualKeysTimeout - now) * 0.000001,
587 keyCode, scanCode);
588 return true;
589 } else {
590 return false;
591 }
592}
593
Jeff Brown05dc66a2011-03-02 14:41:58 -0800594void InputReader::fadePointer() {
595 { // acquire device registry reader lock
596 RWLock::AutoRLock _rl(mDeviceRegistryLock);
597
598 for (size_t i = 0; i < mDevices.size(); i++) {
599 InputDevice* device = mDevices.valueAt(i);
600 device->fadePointer();
601 }
602 } // release device registry reader lock
603}
604
Jeff Brownaa3855d2011-03-17 01:34:19 -0700605void InputReader::requestTimeoutAtTime(nsecs_t when) {
606 if (when < mNextTimeout) {
607 mNextTimeout = when;
608 }
609}
610
Jeff Brown6d0fec22010-07-23 21:28:06 -0700611void InputReader::getInputConfiguration(InputConfiguration* outConfiguration) {
612 { // acquire state lock
613 AutoMutex _l(mStateLock);
614
615 *outConfiguration = mInputConfiguration;
616 } // release state lock
617}
618
619status_t InputReader::getInputDeviceInfo(int32_t deviceId, InputDeviceInfo* outDeviceInfo) {
620 { // acquire device registry reader lock
621 RWLock::AutoRLock _rl(mDeviceRegistryLock);
622
623 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
624 if (deviceIndex < 0) {
625 return NAME_NOT_FOUND;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700626 }
627
Jeff Brown6d0fec22010-07-23 21:28:06 -0700628 InputDevice* device = mDevices.valueAt(deviceIndex);
629 if (device->isIgnored()) {
630 return NAME_NOT_FOUND;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700631 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700632
633 device->getDeviceInfo(outDeviceInfo);
634 return OK;
635 } // release device registy reader lock
636}
637
638void InputReader::getInputDeviceIds(Vector<int32_t>& outDeviceIds) {
639 outDeviceIds.clear();
640
641 { // acquire device registry reader lock
642 RWLock::AutoRLock _rl(mDeviceRegistryLock);
643
644 size_t numDevices = mDevices.size();
645 for (size_t i = 0; i < numDevices; i++) {
646 InputDevice* device = mDevices.valueAt(i);
647 if (! device->isIgnored()) {
648 outDeviceIds.add(device->getId());
649 }
650 }
651 } // release device registy reader lock
652}
653
654int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
655 int32_t keyCode) {
656 return getState(deviceId, sourceMask, keyCode, & InputDevice::getKeyCodeState);
657}
658
659int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
660 int32_t scanCode) {
661 return getState(deviceId, sourceMask, scanCode, & InputDevice::getScanCodeState);
662}
663
664int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
665 return getState(deviceId, sourceMask, switchCode, & InputDevice::getSwitchState);
666}
667
668int32_t InputReader::getState(int32_t deviceId, uint32_t sourceMask, int32_t code,
669 GetStateFunc getStateFunc) {
670 { // acquire device registry reader lock
671 RWLock::AutoRLock _rl(mDeviceRegistryLock);
672
673 int32_t result = AKEY_STATE_UNKNOWN;
674 if (deviceId >= 0) {
675 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
676 if (deviceIndex >= 0) {
677 InputDevice* device = mDevices.valueAt(deviceIndex);
678 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
679 result = (device->*getStateFunc)(sourceMask, code);
680 }
681 }
682 } else {
683 size_t numDevices = mDevices.size();
684 for (size_t i = 0; i < numDevices; i++) {
685 InputDevice* device = mDevices.valueAt(i);
686 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
687 result = (device->*getStateFunc)(sourceMask, code);
688 if (result >= AKEY_STATE_DOWN) {
689 return result;
690 }
691 }
692 }
693 }
694 return result;
695 } // release device registy reader lock
696}
697
698bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
699 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
700 memset(outFlags, 0, numCodes);
701 return markSupportedKeyCodes(deviceId, sourceMask, numCodes, keyCodes, outFlags);
702}
703
704bool InputReader::markSupportedKeyCodes(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
705 const int32_t* keyCodes, uint8_t* outFlags) {
706 { // acquire device registry reader lock
707 RWLock::AutoRLock _rl(mDeviceRegistryLock);
708 bool result = false;
709 if (deviceId >= 0) {
710 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
711 if (deviceIndex >= 0) {
712 InputDevice* device = mDevices.valueAt(deviceIndex);
713 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
714 result = device->markSupportedKeyCodes(sourceMask,
715 numCodes, keyCodes, outFlags);
716 }
717 }
718 } else {
719 size_t numDevices = mDevices.size();
720 for (size_t i = 0; i < numDevices; i++) {
721 InputDevice* device = mDevices.valueAt(i);
722 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
723 result |= device->markSupportedKeyCodes(sourceMask,
724 numCodes, keyCodes, outFlags);
725 }
726 }
727 }
728 return result;
729 } // release device registy reader lock
730}
731
Jeff Brown474dcb52011-06-14 20:22:50 -0700732void InputReader::requestRefreshConfiguration(uint32_t changes) {
733 if (changes) {
734 bool needWake;
735 { // acquire lock
736 AutoMutex _l(mStateLock);
Jeff Brown93fa9b32011-06-14 17:09:25 -0700737
Jeff Brown474dcb52011-06-14 20:22:50 -0700738 needWake = !mConfigurationChangesToRefresh;
739 mConfigurationChangesToRefresh |= changes;
740 } // release lock
741
742 if (needWake) {
743 mEventHub->wake();
744 }
745 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700746}
747
Jeff Brownb88102f2010-09-08 11:49:43 -0700748void InputReader::dump(String8& dump) {
Jeff Brownf2f487182010-10-01 17:46:21 -0700749 mEventHub->dump(dump);
750 dump.append("\n");
751
752 dump.append("Input Reader State:\n");
753
Jeff Brownef3d7e82010-09-30 14:33:04 -0700754 { // acquire device registry reader lock
755 RWLock::AutoRLock _rl(mDeviceRegistryLock);
Jeff Brownb88102f2010-09-08 11:49:43 -0700756
Jeff Brownef3d7e82010-09-30 14:33:04 -0700757 for (size_t i = 0; i < mDevices.size(); i++) {
758 mDevices.valueAt(i)->dump(dump);
Jeff Brownb88102f2010-09-08 11:49:43 -0700759 }
Jeff Brownef3d7e82010-09-30 14:33:04 -0700760 } // release device registy reader lock
Jeff Brown214eaf42011-05-26 19:17:02 -0700761
762 dump.append(INDENT "Configuration:\n");
763 dump.append(INDENT2 "ExcludedDeviceNames: [");
764 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
765 if (i != 0) {
766 dump.append(", ");
767 }
768 dump.append(mConfig.excludedDeviceNames.itemAt(i).string());
769 }
770 dump.append("]\n");
771 dump.appendFormat(INDENT2 "FilterTouchEvents: %s\n",
772 toString(mConfig.filterTouchEvents));
773 dump.appendFormat(INDENT2 "FilterJumpyTouchEvents: %s\n",
774 toString(mConfig.filterJumpyTouchEvents));
775 dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
776 mConfig.virtualKeyQuietTime * 0.000001f);
777
Jeff Brown19c97d462011-06-01 12:33:19 -0700778 dump.appendFormat(INDENT2 "PointerVelocityControlParameters: "
779 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
780 mConfig.pointerVelocityControlParameters.scale,
781 mConfig.pointerVelocityControlParameters.lowThreshold,
782 mConfig.pointerVelocityControlParameters.highThreshold,
783 mConfig.pointerVelocityControlParameters.acceleration);
784
785 dump.appendFormat(INDENT2 "WheelVelocityControlParameters: "
786 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
787 mConfig.wheelVelocityControlParameters.scale,
788 mConfig.wheelVelocityControlParameters.lowThreshold,
789 mConfig.wheelVelocityControlParameters.highThreshold,
790 mConfig.wheelVelocityControlParameters.acceleration);
791
Jeff Brown214eaf42011-05-26 19:17:02 -0700792 dump.appendFormat(INDENT2 "PointerGesture:\n");
Jeff Brown474dcb52011-06-14 20:22:50 -0700793 dump.appendFormat(INDENT3 "Enabled: %s\n",
794 toString(mConfig.pointerGesturesEnabled));
Jeff Brown214eaf42011-05-26 19:17:02 -0700795 dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n",
796 mConfig.pointerGestureQuietInterval * 0.000001f);
797 dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
798 mConfig.pointerGestureDragMinSwitchSpeed);
799 dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n",
800 mConfig.pointerGestureTapInterval * 0.000001f);
801 dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n",
802 mConfig.pointerGestureTapDragInterval * 0.000001f);
803 dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n",
804 mConfig.pointerGestureTapSlop);
805 dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
806 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -0700807 dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
808 mConfig.pointerGestureMultitouchMinDistance);
Jeff Brown214eaf42011-05-26 19:17:02 -0700809 dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
810 mConfig.pointerGestureSwipeTransitionAngleCosine);
811 dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
812 mConfig.pointerGestureSwipeMaxWidthRatio);
813 dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n",
814 mConfig.pointerGestureMovementSpeedRatio);
815 dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n",
816 mConfig.pointerGestureZoomSpeedRatio);
Jeff Brownb88102f2010-09-08 11:49:43 -0700817}
818
Jeff Brown6d0fec22010-07-23 21:28:06 -0700819
820// --- InputReaderThread ---
821
822InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) :
823 Thread(/*canCallJava*/ true), mReader(reader) {
824}
825
826InputReaderThread::~InputReaderThread() {
827}
828
829bool InputReaderThread::threadLoop() {
830 mReader->loopOnce();
831 return true;
832}
833
834
835// --- InputDevice ---
836
837InputDevice::InputDevice(InputReaderContext* context, int32_t id, const String8& name) :
Jeff Brown80fd47c2011-05-24 01:07:44 -0700838 mContext(context), mId(id), mName(name), mSources(0),
839 mIsExternal(false), mDropUntilNextSync(false) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700840}
841
842InputDevice::~InputDevice() {
843 size_t numMappers = mMappers.size();
844 for (size_t i = 0; i < numMappers; i++) {
845 delete mMappers[i];
846 }
847 mMappers.clear();
848}
849
Jeff Brownef3d7e82010-09-30 14:33:04 -0700850void InputDevice::dump(String8& dump) {
851 InputDeviceInfo deviceInfo;
852 getDeviceInfo(& deviceInfo);
853
Jeff Brown90655042010-12-02 13:50:46 -0800854 dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(),
Jeff Brownef3d7e82010-09-30 14:33:04 -0700855 deviceInfo.getName().string());
Jeff Brown56194eb2011-03-02 19:23:13 -0800856 dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Jeff Brownef3d7e82010-09-30 14:33:04 -0700857 dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
858 dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Jeff Browncc0c1592011-02-19 05:07:28 -0800859
Jeff Brownefd32662011-03-08 15:13:06 -0800860 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
Jeff Browncc0c1592011-02-19 05:07:28 -0800861 if (!ranges.isEmpty()) {
Jeff Brownef3d7e82010-09-30 14:33:04 -0700862 dump.append(INDENT2 "Motion Ranges:\n");
Jeff Browncc0c1592011-02-19 05:07:28 -0800863 for (size_t i = 0; i < ranges.size(); i++) {
Jeff Brownefd32662011-03-08 15:13:06 -0800864 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
865 const char* label = getAxisLabel(range.axis);
Jeff Browncc0c1592011-02-19 05:07:28 -0800866 char name[32];
867 if (label) {
868 strncpy(name, label, sizeof(name));
869 name[sizeof(name) - 1] = '\0';
870 } else {
Jeff Brownefd32662011-03-08 15:13:06 -0800871 snprintf(name, sizeof(name), "%d", range.axis);
Jeff Browncc0c1592011-02-19 05:07:28 -0800872 }
Jeff Brownefd32662011-03-08 15:13:06 -0800873 dump.appendFormat(INDENT3 "%s: source=0x%08x, "
874 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f\n",
875 name, range.source, range.min, range.max, range.flat, range.fuzz);
Jeff Browncc0c1592011-02-19 05:07:28 -0800876 }
Jeff Brownef3d7e82010-09-30 14:33:04 -0700877 }
878
879 size_t numMappers = mMappers.size();
880 for (size_t i = 0; i < numMappers; i++) {
881 InputMapper* mapper = mMappers[i];
882 mapper->dump(dump);
883 }
884}
885
Jeff Brown6d0fec22010-07-23 21:28:06 -0700886void InputDevice::addMapper(InputMapper* mapper) {
887 mMappers.add(mapper);
888}
889
Jeff Brown474dcb52011-06-14 20:22:50 -0700890void InputDevice::configure(const InputReaderConfiguration* config, uint32_t changes) {
Jeff Brown6d0fec22010-07-23 21:28:06 -0700891 mSources = 0;
892
Jeff Brown474dcb52011-06-14 20:22:50 -0700893 if (!isIgnored()) {
894 if (!changes) { // first time only
895 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
896 }
897
898 size_t numMappers = mMappers.size();
899 for (size_t i = 0; i < numMappers; i++) {
900 InputMapper* mapper = mMappers[i];
901 mapper->configure(config, changes);
902 mSources |= mapper->getSources();
903 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700904 }
905}
906
Jeff Brown6d0fec22010-07-23 21:28:06 -0700907void InputDevice::reset() {
908 size_t numMappers = mMappers.size();
909 for (size_t i = 0; i < numMappers; i++) {
910 InputMapper* mapper = mMappers[i];
911 mapper->reset();
912 }
913}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700914
Jeff Brownb7198742011-03-18 18:14:26 -0700915void InputDevice::process(const RawEvent* rawEvents, size_t count) {
916 // Process all of the events in order for each mapper.
917 // We cannot simply ask each mapper to process them in bulk because mappers may
918 // have side-effects that must be interleaved. For example, joystick movement events and
919 // gamepad button presses are handled by different mappers but they should be dispatched
920 // in the order received.
Jeff Brown6d0fec22010-07-23 21:28:06 -0700921 size_t numMappers = mMappers.size();
Jeff Brownb7198742011-03-18 18:14:26 -0700922 for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {
923#if DEBUG_RAW_EVENTS
924 LOGD("Input event: device=%d type=0x%04x scancode=0x%04x "
Jeff Brown2e45fb62011-06-29 21:19:05 -0700925 "keycode=0x%04x value=0x%08x flags=0x%08x",
Jeff Brownb7198742011-03-18 18:14:26 -0700926 rawEvent->deviceId, rawEvent->type, rawEvent->scanCode, rawEvent->keyCode,
927 rawEvent->value, rawEvent->flags);
928#endif
929
Jeff Brown80fd47c2011-05-24 01:07:44 -0700930 if (mDropUntilNextSync) {
931 if (rawEvent->type == EV_SYN && rawEvent->scanCode == SYN_REPORT) {
932 mDropUntilNextSync = false;
933#if DEBUG_RAW_EVENTS
934 LOGD("Recovered from input event buffer overrun.");
935#endif
936 } else {
937#if DEBUG_RAW_EVENTS
938 LOGD("Dropped input event while waiting for next input sync.");
939#endif
940 }
941 } else if (rawEvent->type == EV_SYN && rawEvent->scanCode == SYN_DROPPED) {
942 LOGI("Detected input event buffer overrun for device %s.", mName.string());
943 mDropUntilNextSync = true;
944 reset();
945 } else {
946 for (size_t i = 0; i < numMappers; i++) {
947 InputMapper* mapper = mMappers[i];
948 mapper->process(rawEvent);
949 }
Jeff Brownb7198742011-03-18 18:14:26 -0700950 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700951 }
952}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -0700953
Jeff Brownaa3855d2011-03-17 01:34:19 -0700954void InputDevice::timeoutExpired(nsecs_t when) {
955 size_t numMappers = mMappers.size();
956 for (size_t i = 0; i < numMappers; i++) {
957 InputMapper* mapper = mMappers[i];
958 mapper->timeoutExpired(when);
959 }
960}
961
Jeff Brown6d0fec22010-07-23 21:28:06 -0700962void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
963 outDeviceInfo->initialize(mId, mName);
964
965 size_t numMappers = mMappers.size();
966 for (size_t i = 0; i < numMappers; i++) {
967 InputMapper* mapper = mMappers[i];
968 mapper->populateDeviceInfo(outDeviceInfo);
969 }
970}
971
972int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
973 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
974}
975
976int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
977 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
978}
979
980int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
981 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
982}
983
984int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
985 int32_t result = AKEY_STATE_UNKNOWN;
986 size_t numMappers = mMappers.size();
987 for (size_t i = 0; i < numMappers; i++) {
988 InputMapper* mapper = mMappers[i];
989 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
990 result = (mapper->*getStateFunc)(sourceMask, code);
991 if (result >= AKEY_STATE_DOWN) {
992 return result;
993 }
994 }
995 }
996 return result;
997}
998
999bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1000 const int32_t* keyCodes, uint8_t* outFlags) {
1001 bool result = false;
1002 size_t numMappers = mMappers.size();
1003 for (size_t i = 0; i < numMappers; i++) {
1004 InputMapper* mapper = mMappers[i];
1005 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1006 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1007 }
1008 }
1009 return result;
1010}
1011
1012int32_t InputDevice::getMetaState() {
1013 int32_t result = 0;
1014 size_t numMappers = mMappers.size();
1015 for (size_t i = 0; i < numMappers; i++) {
1016 InputMapper* mapper = mMappers[i];
1017 result |= mapper->getMetaState();
1018 }
1019 return result;
1020}
1021
Jeff Brown05dc66a2011-03-02 14:41:58 -08001022void InputDevice::fadePointer() {
1023 size_t numMappers = mMappers.size();
1024 for (size_t i = 0; i < numMappers; i++) {
1025 InputMapper* mapper = mMappers[i];
1026 mapper->fadePointer();
1027 }
1028}
1029
Jeff Brown6d0fec22010-07-23 21:28:06 -07001030
1031// --- InputMapper ---
1032
1033InputMapper::InputMapper(InputDevice* device) :
1034 mDevice(device), mContext(device->getContext()) {
1035}
1036
1037InputMapper::~InputMapper() {
1038}
1039
1040void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1041 info->addSource(getSources());
1042}
1043
Jeff Brownef3d7e82010-09-30 14:33:04 -07001044void InputMapper::dump(String8& dump) {
1045}
1046
Jeff Brown474dcb52011-06-14 20:22:50 -07001047void InputMapper::configure(const InputReaderConfiguration* config, uint32_t changes) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001048}
1049
1050void InputMapper::reset() {
1051}
1052
Jeff Brownaa3855d2011-03-17 01:34:19 -07001053void InputMapper::timeoutExpired(nsecs_t when) {
1054}
1055
Jeff Brown6d0fec22010-07-23 21:28:06 -07001056int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1057 return AKEY_STATE_UNKNOWN;
1058}
1059
1060int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1061 return AKEY_STATE_UNKNOWN;
1062}
1063
1064int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1065 return AKEY_STATE_UNKNOWN;
1066}
1067
1068bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1069 const int32_t* keyCodes, uint8_t* outFlags) {
1070 return false;
1071}
1072
1073int32_t InputMapper::getMetaState() {
1074 return 0;
1075}
1076
Jeff Brown05dc66a2011-03-02 14:41:58 -08001077void InputMapper::fadePointer() {
1078}
1079
Jeff Browncb1404e2011-01-15 18:14:15 -08001080void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump,
1081 const RawAbsoluteAxisInfo& axis, const char* name) {
1082 if (axis.valid) {
Jeff Brownb3a2d132011-06-12 18:14:50 -07001083 dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
1084 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
Jeff Browncb1404e2011-01-15 18:14:15 -08001085 } else {
1086 dump.appendFormat(INDENT4 "%s: unknown range\n", name);
1087 }
1088}
1089
Jeff Brown6d0fec22010-07-23 21:28:06 -07001090
1091// --- SwitchInputMapper ---
1092
1093SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
1094 InputMapper(device) {
1095}
1096
1097SwitchInputMapper::~SwitchInputMapper() {
1098}
1099
1100uint32_t SwitchInputMapper::getSources() {
Jeff Brown89de57a2011-01-19 18:41:38 -08001101 return AINPUT_SOURCE_SWITCH;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001102}
1103
1104void SwitchInputMapper::process(const RawEvent* rawEvent) {
1105 switch (rawEvent->type) {
1106 case EV_SW:
1107 processSwitch(rawEvent->when, rawEvent->scanCode, rawEvent->value);
1108 break;
1109 }
1110}
1111
1112void SwitchInputMapper::processSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue) {
Jeff Brownb6997262010-10-08 22:31:17 -07001113 getDispatcher()->notifySwitch(when, switchCode, switchValue, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001114}
1115
1116int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1117 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
1118}
1119
1120
1121// --- KeyboardInputMapper ---
1122
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001123KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
Jeff Brownefd32662011-03-08 15:13:06 -08001124 uint32_t source, int32_t keyboardType) :
1125 InputMapper(device), mSource(source),
Jeff Brown6d0fec22010-07-23 21:28:06 -07001126 mKeyboardType(keyboardType) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001127 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001128}
1129
1130KeyboardInputMapper::~KeyboardInputMapper() {
1131}
1132
Jeff Brown6328cdc2010-07-29 18:18:33 -07001133void KeyboardInputMapper::initializeLocked() {
1134 mLocked.metaState = AMETA_NONE;
1135 mLocked.downTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001136}
1137
1138uint32_t KeyboardInputMapper::getSources() {
Jeff Brownefd32662011-03-08 15:13:06 -08001139 return mSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001140}
1141
1142void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1143 InputMapper::populateDeviceInfo(info);
1144
1145 info->setKeyboardType(mKeyboardType);
1146}
1147
Jeff Brownef3d7e82010-09-30 14:33:04 -07001148void KeyboardInputMapper::dump(String8& dump) {
1149 { // acquire lock
1150 AutoMutex _l(mLock);
1151 dump.append(INDENT2 "Keyboard Input Mapper:\n");
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001152 dumpParameters(dump);
Jeff Brownef3d7e82010-09-30 14:33:04 -07001153 dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType);
1154 dump.appendFormat(INDENT3 "KeyDowns: %d keys currently down\n", mLocked.keyDowns.size());
1155 dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mLocked.metaState);
1156 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
1157 } // release lock
1158}
1159
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001160
Jeff Brown474dcb52011-06-14 20:22:50 -07001161void KeyboardInputMapper::configure(const InputReaderConfiguration* config, uint32_t changes) {
1162 InputMapper::configure(config, changes);
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001163
Jeff Brown474dcb52011-06-14 20:22:50 -07001164 if (!changes) { // first time only
1165 // Configure basic parameters.
1166 configureParameters();
Jeff Brown49ed71d2010-12-06 17:13:33 -08001167
Jeff Brown474dcb52011-06-14 20:22:50 -07001168 // Reset LEDs.
1169 {
1170 AutoMutex _l(mLock);
1171 resetLedStateLocked();
1172 }
Jeff Brown49ed71d2010-12-06 17:13:33 -08001173 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001174}
1175
1176void KeyboardInputMapper::configureParameters() {
1177 mParameters.orientationAware = false;
1178 getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"),
1179 mParameters.orientationAware);
1180
1181 mParameters.associatedDisplayId = mParameters.orientationAware ? 0 : -1;
1182}
1183
1184void KeyboardInputMapper::dumpParameters(String8& dump) {
1185 dump.append(INDENT3 "Parameters:\n");
1186 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1187 mParameters.associatedDisplayId);
1188 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1189 toString(mParameters.orientationAware));
1190}
1191
Jeff Brown6d0fec22010-07-23 21:28:06 -07001192void KeyboardInputMapper::reset() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001193 for (;;) {
1194 int32_t keyCode, scanCode;
1195 { // acquire lock
1196 AutoMutex _l(mLock);
1197
1198 // Synthesize key up event on reset if keys are currently down.
1199 if (mLocked.keyDowns.isEmpty()) {
1200 initializeLocked();
Jeff Brown49ed71d2010-12-06 17:13:33 -08001201 resetLedStateLocked();
Jeff Brown6328cdc2010-07-29 18:18:33 -07001202 break; // done
1203 }
1204
1205 const KeyDown& keyDown = mLocked.keyDowns.top();
1206 keyCode = keyDown.keyCode;
1207 scanCode = keyDown.scanCode;
1208 } // release lock
1209
Jeff Brown6d0fec22010-07-23 21:28:06 -07001210 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brown6328cdc2010-07-29 18:18:33 -07001211 processKey(when, false, keyCode, scanCode, 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001212 }
1213
1214 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001215 getContext()->updateGlobalMetaState();
1216}
1217
1218void KeyboardInputMapper::process(const RawEvent* rawEvent) {
1219 switch (rawEvent->type) {
1220 case EV_KEY: {
1221 int32_t scanCode = rawEvent->scanCode;
1222 if (isKeyboardOrGamepadKey(scanCode)) {
1223 processKey(rawEvent->when, rawEvent->value != 0, rawEvent->keyCode, scanCode,
1224 rawEvent->flags);
1225 }
1226 break;
1227 }
1228 }
1229}
1230
1231bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
1232 return scanCode < BTN_MOUSE
1233 || scanCode >= KEY_OK
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001234 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
Jeff Browncb1404e2011-01-15 18:14:15 -08001235 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001236}
1237
Jeff Brown6328cdc2010-07-29 18:18:33 -07001238void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode,
1239 int32_t scanCode, uint32_t policyFlags) {
1240 int32_t newMetaState;
1241 nsecs_t downTime;
1242 bool metaStateChanged = false;
1243
1244 { // acquire lock
1245 AutoMutex _l(mLock);
1246
1247 if (down) {
1248 // Rotate key codes according to orientation if needed.
1249 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001250 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001251 int32_t orientation;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001252 if (!getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1253 NULL, NULL, & orientation)) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001254 orientation = DISPLAY_ORIENTATION_0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001255 }
1256
1257 keyCode = rotateKeyCode(keyCode, orientation);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001258 }
1259
Jeff Brown6328cdc2010-07-29 18:18:33 -07001260 // Add key down.
1261 ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1262 if (keyDownIndex >= 0) {
1263 // key repeat, be sure to use same keycode as before in case of rotation
Jeff Brown6b53e8d2010-11-10 16:03:06 -08001264 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001265 } else {
1266 // key down
Jeff Brownfe508922011-01-18 15:10:10 -08001267 if ((policyFlags & POLICY_FLAG_VIRTUAL)
1268 && mContext->shouldDropVirtualKey(when,
1269 getDevice(), keyCode, scanCode)) {
1270 return;
1271 }
1272
Jeff Brown6328cdc2010-07-29 18:18:33 -07001273 mLocked.keyDowns.push();
1274 KeyDown& keyDown = mLocked.keyDowns.editTop();
1275 keyDown.keyCode = keyCode;
1276 keyDown.scanCode = scanCode;
1277 }
1278
1279 mLocked.downTime = when;
1280 } else {
1281 // Remove key down.
1282 ssize_t keyDownIndex = findKeyDownLocked(scanCode);
1283 if (keyDownIndex >= 0) {
1284 // key up, be sure to use same keycode as before in case of rotation
Jeff Brown6b53e8d2010-11-10 16:03:06 -08001285 keyCode = mLocked.keyDowns.itemAt(keyDownIndex).keyCode;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001286 mLocked.keyDowns.removeAt(size_t(keyDownIndex));
1287 } else {
1288 // key was not actually down
1289 LOGI("Dropping key up from device %s because the key was not down. "
1290 "keyCode=%d, scanCode=%d",
1291 getDeviceName().string(), keyCode, scanCode);
1292 return;
1293 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001294 }
1295
Jeff Brown6328cdc2010-07-29 18:18:33 -07001296 int32_t oldMetaState = mLocked.metaState;
1297 newMetaState = updateMetaState(keyCode, down, oldMetaState);
1298 if (oldMetaState != newMetaState) {
1299 mLocked.metaState = newMetaState;
1300 metaStateChanged = true;
Jeff Brown497a92c2010-09-12 17:55:08 -07001301 updateLedStateLocked(false);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001302 }
Jeff Brownfd0358292010-06-30 16:10:35 -07001303
Jeff Brown6328cdc2010-07-29 18:18:33 -07001304 downTime = mLocked.downTime;
1305 } // release lock
1306
Jeff Brown56194eb2011-03-02 19:23:13 -08001307 // Key down on external an keyboard should wake the device.
1308 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
1309 // For internal keyboards, the key layout file should specify the policy flags for
1310 // each wake key individually.
1311 // TODO: Use the input device configuration to control this behavior more finely.
1312 if (down && getDevice()->isExternal()
1313 && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) {
1314 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1315 }
1316
Jeff Brown6328cdc2010-07-29 18:18:33 -07001317 if (metaStateChanged) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001318 getContext()->updateGlobalMetaState();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001319 }
1320
Jeff Brown05dc66a2011-03-02 14:41:58 -08001321 if (down && !isMetaKey(keyCode)) {
1322 getContext()->fadePointer();
1323 }
1324
Jeff Brownefd32662011-03-08 15:13:06 -08001325 getDispatcher()->notifyKey(when, getDeviceId(), mSource, policyFlags,
Jeff Brownb6997262010-10-08 22:31:17 -07001326 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
1327 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001328}
1329
Jeff Brown6328cdc2010-07-29 18:18:33 -07001330ssize_t KeyboardInputMapper::findKeyDownLocked(int32_t scanCode) {
1331 size_t n = mLocked.keyDowns.size();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001332 for (size_t i = 0; i < n; i++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001333 if (mLocked.keyDowns[i].scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001334 return i;
1335 }
1336 }
1337 return -1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001338}
1339
Jeff Brown6d0fec22010-07-23 21:28:06 -07001340int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1341 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
1342}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001343
Jeff Brown6d0fec22010-07-23 21:28:06 -07001344int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1345 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1346}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001347
Jeff Brown6d0fec22010-07-23 21:28:06 -07001348bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1349 const int32_t* keyCodes, uint8_t* outFlags) {
1350 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
1351}
1352
1353int32_t KeyboardInputMapper::getMetaState() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001354 { // acquire lock
1355 AutoMutex _l(mLock);
1356 return mLocked.metaState;
1357 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001358}
1359
Jeff Brown49ed71d2010-12-06 17:13:33 -08001360void KeyboardInputMapper::resetLedStateLocked() {
1361 initializeLedStateLocked(mLocked.capsLockLedState, LED_CAPSL);
1362 initializeLedStateLocked(mLocked.numLockLedState, LED_NUML);
1363 initializeLedStateLocked(mLocked.scrollLockLedState, LED_SCROLLL);
1364
1365 updateLedStateLocked(true);
1366}
1367
1368void KeyboardInputMapper::initializeLedStateLocked(LockedState::LedState& ledState, int32_t led) {
1369 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
1370 ledState.on = false;
1371}
1372
Jeff Brown497a92c2010-09-12 17:55:08 -07001373void KeyboardInputMapper::updateLedStateLocked(bool reset) {
1374 updateLedStateForModifierLocked(mLocked.capsLockLedState, LED_CAPSL,
Jeff Brown51e7fe752010-10-29 22:19:53 -07001375 AMETA_CAPS_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001376 updateLedStateForModifierLocked(mLocked.numLockLedState, LED_NUML,
Jeff Brown51e7fe752010-10-29 22:19:53 -07001377 AMETA_NUM_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001378 updateLedStateForModifierLocked(mLocked.scrollLockLedState, LED_SCROLLL,
Jeff Brown51e7fe752010-10-29 22:19:53 -07001379 AMETA_SCROLL_LOCK_ON, reset);
Jeff Brown497a92c2010-09-12 17:55:08 -07001380}
1381
1382void KeyboardInputMapper::updateLedStateForModifierLocked(LockedState::LedState& ledState,
1383 int32_t led, int32_t modifier, bool reset) {
1384 if (ledState.avail) {
1385 bool desiredState = (mLocked.metaState & modifier) != 0;
Jeff Brown49ed71d2010-12-06 17:13:33 -08001386 if (reset || ledState.on != desiredState) {
Jeff Brown497a92c2010-09-12 17:55:08 -07001387 getEventHub()->setLedState(getDeviceId(), led, desiredState);
1388 ledState.on = desiredState;
1389 }
1390 }
1391}
1392
Jeff Brown6d0fec22010-07-23 21:28:06 -07001393
Jeff Brown83c09682010-12-23 17:50:18 -08001394// --- CursorInputMapper ---
Jeff Brown6d0fec22010-07-23 21:28:06 -07001395
Jeff Brown83c09682010-12-23 17:50:18 -08001396CursorInputMapper::CursorInputMapper(InputDevice* device) :
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001397 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001398 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001399}
1400
Jeff Brown83c09682010-12-23 17:50:18 -08001401CursorInputMapper::~CursorInputMapper() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001402}
1403
Jeff Brown83c09682010-12-23 17:50:18 -08001404uint32_t CursorInputMapper::getSources() {
Jeff Brownefd32662011-03-08 15:13:06 -08001405 return mSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001406}
1407
Jeff Brown83c09682010-12-23 17:50:18 -08001408void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001409 InputMapper::populateDeviceInfo(info);
1410
Jeff Brown83c09682010-12-23 17:50:18 -08001411 if (mParameters.mode == Parameters::MODE_POINTER) {
1412 float minX, minY, maxX, maxY;
1413 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
Jeff Brownefd32662011-03-08 15:13:06 -08001414 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f);
1415 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f);
Jeff Brown83c09682010-12-23 17:50:18 -08001416 }
1417 } else {
Jeff Brownefd32662011-03-08 15:13:06 -08001418 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale);
1419 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale);
Jeff Brown83c09682010-12-23 17:50:18 -08001420 }
Jeff Brownefd32662011-03-08 15:13:06 -08001421 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001422
1423 if (mHaveVWheel) {
Jeff Brownefd32662011-03-08 15:13:06 -08001424 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001425 }
1426 if (mHaveHWheel) {
Jeff Brownefd32662011-03-08 15:13:06 -08001427 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001428 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001429}
1430
Jeff Brown83c09682010-12-23 17:50:18 -08001431void CursorInputMapper::dump(String8& dump) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07001432 { // acquire lock
1433 AutoMutex _l(mLock);
Jeff Brown83c09682010-12-23 17:50:18 -08001434 dump.append(INDENT2 "Cursor Input Mapper:\n");
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001435 dumpParameters(dump);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001436 dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale);
1437 dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale);
Jeff Brownef3d7e82010-09-30 14:33:04 -07001438 dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
1439 dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
Jeff Brown6f2fba42011-02-19 01:08:02 -08001440 dump.appendFormat(INDENT3 "HaveVWheel: %s\n", toString(mHaveVWheel));
1441 dump.appendFormat(INDENT3 "HaveHWheel: %s\n", toString(mHaveHWheel));
1442 dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
1443 dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001444 dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mLocked.buttonState);
1445 dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mLocked.buttonState)));
Jeff Brownef3d7e82010-09-30 14:33:04 -07001446 dump.appendFormat(INDENT3 "DownTime: %lld\n", mLocked.downTime);
1447 } // release lock
1448}
1449
Jeff Brown474dcb52011-06-14 20:22:50 -07001450void CursorInputMapper::configure(const InputReaderConfiguration* config, uint32_t changes) {
1451 InputMapper::configure(config, changes);
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001452
Jeff Brown474dcb52011-06-14 20:22:50 -07001453 if (!changes) { // first time only
1454 // Configure basic parameters.
1455 configureParameters();
Jeff Brown83c09682010-12-23 17:50:18 -08001456
Jeff Brown474dcb52011-06-14 20:22:50 -07001457 // Configure device mode.
1458 switch (mParameters.mode) {
1459 case Parameters::MODE_POINTER:
1460 mSource = AINPUT_SOURCE_MOUSE;
1461 mXPrecision = 1.0f;
1462 mYPrecision = 1.0f;
1463 mXScale = 1.0f;
1464 mYScale = 1.0f;
1465 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
1466 break;
1467 case Parameters::MODE_NAVIGATION:
1468 mSource = AINPUT_SOURCE_TRACKBALL;
1469 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1470 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
1471 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1472 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
1473 break;
1474 }
1475
1476 mVWheelScale = 1.0f;
1477 mHWheelScale = 1.0f;
1478
1479 mHaveVWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_WHEEL);
1480 mHaveHWheel = getEventHub()->hasRelativeAxis(getDeviceId(), REL_HWHEEL);
Jeff Brown83c09682010-12-23 17:50:18 -08001481 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08001482
Jeff Brown474dcb52011-06-14 20:22:50 -07001483 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
1484 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
1485 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
1486 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
1487 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001488}
1489
Jeff Brown83c09682010-12-23 17:50:18 -08001490void CursorInputMapper::configureParameters() {
1491 mParameters.mode = Parameters::MODE_POINTER;
1492 String8 cursorModeString;
1493 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
1494 if (cursorModeString == "navigation") {
1495 mParameters.mode = Parameters::MODE_NAVIGATION;
1496 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
1497 LOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
1498 }
1499 }
1500
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001501 mParameters.orientationAware = false;
Jeff Brown83c09682010-12-23 17:50:18 -08001502 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001503 mParameters.orientationAware);
1504
Jeff Brown83c09682010-12-23 17:50:18 -08001505 mParameters.associatedDisplayId = mParameters.mode == Parameters::MODE_POINTER
1506 || mParameters.orientationAware ? 0 : -1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001507}
1508
Jeff Brown83c09682010-12-23 17:50:18 -08001509void CursorInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001510 dump.append(INDENT3 "Parameters:\n");
1511 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
1512 mParameters.associatedDisplayId);
Jeff Brown83c09682010-12-23 17:50:18 -08001513
1514 switch (mParameters.mode) {
1515 case Parameters::MODE_POINTER:
1516 dump.append(INDENT4 "Mode: pointer\n");
1517 break;
1518 case Parameters::MODE_NAVIGATION:
1519 dump.append(INDENT4 "Mode: navigation\n");
1520 break;
1521 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07001522 LOG_ASSERT(false);
Jeff Brown83c09682010-12-23 17:50:18 -08001523 }
1524
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001525 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
1526 toString(mParameters.orientationAware));
1527}
1528
Jeff Brown83c09682010-12-23 17:50:18 -08001529void CursorInputMapper::initializeLocked() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001530 mAccumulator.clear();
1531
Jeff Brownefd32662011-03-08 15:13:06 -08001532 mLocked.buttonState = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001533 mLocked.downTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001534}
1535
Jeff Brown83c09682010-12-23 17:50:18 -08001536void CursorInputMapper::reset() {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001537 for (;;) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001538 int32_t buttonState;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001539 { // acquire lock
1540 AutoMutex _l(mLock);
1541
Jeff Brownefd32662011-03-08 15:13:06 -08001542 buttonState = mLocked.buttonState;
1543 if (!buttonState) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001544 initializeLocked();
1545 break; // done
1546 }
1547 } // release lock
1548
Jeff Brown19c97d462011-06-01 12:33:19 -07001549 // Reset velocity.
1550 mPointerVelocityControl.reset();
1551 mWheelXVelocityControl.reset();
1552 mWheelYVelocityControl.reset();
1553
Jeff Brown83c09682010-12-23 17:50:18 -08001554 // Synthesize button up event on reset.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001555 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Brownefd32662011-03-08 15:13:06 -08001556 mAccumulator.clear();
1557 mAccumulator.buttonDown = 0;
1558 mAccumulator.buttonUp = buttonState;
1559 mAccumulator.fields = Accumulator::FIELD_BUTTONS;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001560 sync(when);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001561 }
1562
Jeff Brown6d0fec22010-07-23 21:28:06 -07001563 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001564}
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001565
Jeff Brown83c09682010-12-23 17:50:18 -08001566void CursorInputMapper::process(const RawEvent* rawEvent) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07001567 switch (rawEvent->type) {
Jeff Brownefd32662011-03-08 15:13:06 -08001568 case EV_KEY: {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001569 int32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
Jeff Brownefd32662011-03-08 15:13:06 -08001570 if (buttonState) {
1571 if (rawEvent->value) {
1572 mAccumulator.buttonDown = buttonState;
1573 mAccumulator.buttonUp = 0;
1574 } else {
1575 mAccumulator.buttonDown = 0;
1576 mAccumulator.buttonUp = buttonState;
1577 }
1578 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
1579
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001580 // Sync now since BTN_MOUSE is not necessarily followed by SYN_REPORT and
1581 // we need to ensure that we report the up/down promptly.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001582 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001583 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001584 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001585 break;
Jeff Brownefd32662011-03-08 15:13:06 -08001586 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001587
Jeff Brown6d0fec22010-07-23 21:28:06 -07001588 case EV_REL:
1589 switch (rawEvent->scanCode) {
1590 case REL_X:
1591 mAccumulator.fields |= Accumulator::FIELD_REL_X;
1592 mAccumulator.relX = rawEvent->value;
1593 break;
1594 case REL_Y:
1595 mAccumulator.fields |= Accumulator::FIELD_REL_Y;
1596 mAccumulator.relY = rawEvent->value;
1597 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001598 case REL_WHEEL:
1599 mAccumulator.fields |= Accumulator::FIELD_REL_WHEEL;
1600 mAccumulator.relWheel = rawEvent->value;
1601 break;
1602 case REL_HWHEEL:
1603 mAccumulator.fields |= Accumulator::FIELD_REL_HWHEEL;
1604 mAccumulator.relHWheel = rawEvent->value;
1605 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001606 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001607 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001608
Jeff Brown6d0fec22010-07-23 21:28:06 -07001609 case EV_SYN:
1610 switch (rawEvent->scanCode) {
1611 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001612 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001613 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001614 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07001615 break;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001616 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001617}
1618
Jeff Brown83c09682010-12-23 17:50:18 -08001619void CursorInputMapper::sync(nsecs_t when) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07001620 uint32_t fields = mAccumulator.fields;
1621 if (fields == 0) {
1622 return; // no new state changes, so nothing to do
1623 }
1624
Jeff Brown9626b142011-03-03 02:09:54 -08001625 int32_t motionEventAction;
1626 int32_t motionEventEdgeFlags;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001627 int32_t lastButtonState, currentButtonState;
1628 PointerProperties pointerProperties;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001629 PointerCoords pointerCoords;
1630 nsecs_t downTime;
Jeff Brown33bbfd22011-02-24 20:55:35 -08001631 float vscroll, hscroll;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001632 { // acquire lock
1633 AutoMutex _l(mLock);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001634
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001635 lastButtonState = mLocked.buttonState;
1636
Jeff Brownefd32662011-03-08 15:13:06 -08001637 bool down, downChanged;
1638 bool wasDown = isPointerDown(mLocked.buttonState);
1639 bool buttonsChanged = fields & Accumulator::FIELD_BUTTONS;
1640 if (buttonsChanged) {
1641 mLocked.buttonState = (mLocked.buttonState | mAccumulator.buttonDown)
1642 & ~mAccumulator.buttonUp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001643
Jeff Brownefd32662011-03-08 15:13:06 -08001644 down = isPointerDown(mLocked.buttonState);
1645
1646 if (!wasDown && down) {
1647 mLocked.downTime = when;
1648 downChanged = true;
1649 } else if (wasDown && !down) {
1650 downChanged = true;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001651 } else {
Jeff Brownefd32662011-03-08 15:13:06 -08001652 downChanged = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001653 }
Jeff Brownefd32662011-03-08 15:13:06 -08001654 } else {
1655 down = wasDown;
1656 downChanged = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001657 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001658
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001659 currentButtonState = mLocked.buttonState;
1660
Jeff Brown6328cdc2010-07-29 18:18:33 -07001661 downTime = mLocked.downTime;
Jeff Brown83c09682010-12-23 17:50:18 -08001662 float deltaX = fields & Accumulator::FIELD_REL_X ? mAccumulator.relX * mXScale : 0.0f;
1663 float deltaY = fields & Accumulator::FIELD_REL_Y ? mAccumulator.relY * mYScale : 0.0f;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001664
Jeff Brown6328cdc2010-07-29 18:18:33 -07001665 if (downChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08001666 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
1667 } else if (down || mPointerController == NULL) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001668 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
Jeff Browncc0c1592011-02-19 05:07:28 -08001669 } else {
1670 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001671 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07001672
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001673 if (mParameters.orientationAware && mParameters.associatedDisplayId >= 0
Jeff Brown83c09682010-12-23 17:50:18 -08001674 && (deltaX != 0.0f || deltaY != 0.0f)) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001675 // Rotate motion based on display orientation if needed.
1676 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
1677 int32_t orientation;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001678 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
1679 NULL, NULL, & orientation)) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001680 orientation = DISPLAY_ORIENTATION_0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001681 }
1682
1683 float temp;
1684 switch (orientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001685 case DISPLAY_ORIENTATION_90:
Jeff Brown83c09682010-12-23 17:50:18 -08001686 temp = deltaX;
1687 deltaX = deltaY;
1688 deltaY = -temp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001689 break;
1690
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001691 case DISPLAY_ORIENTATION_180:
Jeff Brown83c09682010-12-23 17:50:18 -08001692 deltaX = -deltaX;
1693 deltaY = -deltaY;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001694 break;
1695
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001696 case DISPLAY_ORIENTATION_270:
Jeff Brown83c09682010-12-23 17:50:18 -08001697 temp = deltaX;
1698 deltaX = -deltaY;
1699 deltaY = temp;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001700 break;
1701 }
1702 }
Jeff Brown83c09682010-12-23 17:50:18 -08001703
Jeff Brown9626b142011-03-03 02:09:54 -08001704 motionEventEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
1705
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001706 pointerProperties.clear();
1707 pointerProperties.id = 0;
1708 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
1709
1710 pointerCoords.clear();
1711
Jeff Brown2352b972011-04-12 22:39:53 -07001712 if (mHaveVWheel && (fields & Accumulator::FIELD_REL_WHEEL)) {
1713 vscroll = mAccumulator.relWheel;
1714 } else {
1715 vscroll = 0;
1716 }
Jeff Brown19c97d462011-06-01 12:33:19 -07001717 mWheelYVelocityControl.move(when, NULL, &vscroll);
1718
Jeff Brown2352b972011-04-12 22:39:53 -07001719 if (mHaveHWheel && (fields & Accumulator::FIELD_REL_HWHEEL)) {
1720 hscroll = mAccumulator.relHWheel;
1721 } else {
1722 hscroll = 0;
1723 }
Jeff Brown19c97d462011-06-01 12:33:19 -07001724 mWheelXVelocityControl.move(when, &hscroll, NULL);
1725
1726 mPointerVelocityControl.move(when, &deltaX, &deltaY);
Jeff Brown2352b972011-04-12 22:39:53 -07001727
Jeff Brown83c09682010-12-23 17:50:18 -08001728 if (mPointerController != NULL) {
Jeff Brown2352b972011-04-12 22:39:53 -07001729 if (deltaX != 0 || deltaY != 0 || vscroll != 0 || hscroll != 0
1730 || buttonsChanged) {
1731 mPointerController->setPresentation(
1732 PointerControllerInterface::PRESENTATION_POINTER);
1733
1734 if (deltaX != 0 || deltaY != 0) {
1735 mPointerController->move(deltaX, deltaY);
1736 }
1737
1738 if (buttonsChanged) {
1739 mPointerController->setButtonState(mLocked.buttonState);
1740 }
1741
Jeff Brown538881e2011-05-25 18:23:38 -07001742 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
Jeff Brown83c09682010-12-23 17:50:18 -08001743 }
Jeff Brownefd32662011-03-08 15:13:06 -08001744
Jeff Brown91c69ab2011-02-14 17:03:18 -08001745 float x, y;
1746 mPointerController->getPosition(&x, &y);
Jeff Brownebbd5d12011-02-17 13:01:34 -08001747 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
1748 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jeff Brown9626b142011-03-03 02:09:54 -08001749
1750 if (motionEventAction == AMOTION_EVENT_ACTION_DOWN) {
Jeff Brownefd32662011-03-08 15:13:06 -08001751 motionEventEdgeFlags = calculateEdgeFlagsUsingPointerBounds(
1752 mPointerController, x, y);
Jeff Brown9626b142011-03-03 02:09:54 -08001753 }
Jeff Brown83c09682010-12-23 17:50:18 -08001754 } else {
Jeff Brownebbd5d12011-02-17 13:01:34 -08001755 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
1756 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
Jeff Brown83c09682010-12-23 17:50:18 -08001757 }
1758
Jeff Brownefd32662011-03-08 15:13:06 -08001759 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
Jeff Brown6328cdc2010-07-29 18:18:33 -07001760 } // release lock
1761
Jeff Brown56194eb2011-03-02 19:23:13 -08001762 // Moving an external trackball or mouse should wake the device.
1763 // We don't do this for internal cursor devices to prevent them from waking up
1764 // the device in your pocket.
1765 // TODO: Use the input device configuration to control this behavior more finely.
1766 uint32_t policyFlags = 0;
1767 if (getDevice()->isExternal()) {
1768 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
1769 }
1770
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001771 // Synthesize key down from buttons if needed.
1772 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1773 policyFlags, lastButtonState, currentButtonState);
1774
1775 // Send motion event.
Jeff Brown6d0fec22010-07-23 21:28:06 -07001776 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brownefd32662011-03-08 15:13:06 -08001777 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001778 motionEventAction, 0, metaState, currentButtonState, motionEventEdgeFlags,
1779 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime);
Jeff Brownb6997262010-10-08 22:31:17 -07001780
Jeff Browna032cc02011-03-07 16:56:21 -08001781 // Send hover move after UP to tell the application that the mouse is hovering now.
1782 if (motionEventAction == AMOTION_EVENT_ACTION_UP
1783 && mPointerController != NULL) {
1784 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001785 AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
1786 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1787 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime);
Jeff Browna032cc02011-03-07 16:56:21 -08001788 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001789
Jeff Browna032cc02011-03-07 16:56:21 -08001790 // Send scroll events.
Jeff Brown33bbfd22011-02-24 20:55:35 -08001791 if (vscroll != 0 || hscroll != 0) {
1792 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
1793 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
1794
Jeff Brownefd32662011-03-08 15:13:06 -08001795 getDispatcher()->notifyMotion(when, getDeviceId(), mSource, policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001796 AMOTION_EVENT_ACTION_SCROLL, 0, metaState, currentButtonState,
1797 AMOTION_EVENT_EDGE_FLAG_NONE,
1798 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime);
Jeff Brown33bbfd22011-02-24 20:55:35 -08001799 }
Jeff Browna032cc02011-03-07 16:56:21 -08001800
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07001801 // Synthesize key up from buttons if needed.
1802 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1803 policyFlags, lastButtonState, currentButtonState);
1804
Jeff Browna032cc02011-03-07 16:56:21 -08001805 mAccumulator.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001806}
1807
Jeff Brown83c09682010-12-23 17:50:18 -08001808int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brownc3fc2d02010-08-10 15:47:53 -07001809 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
1810 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
1811 } else {
1812 return AKEY_STATE_UNKNOWN;
1813 }
1814}
1815
Jeff Brown05dc66a2011-03-02 14:41:58 -08001816void CursorInputMapper::fadePointer() {
1817 { // acquire lock
1818 AutoMutex _l(mLock);
Jeff Brownefd32662011-03-08 15:13:06 -08001819 if (mPointerController != NULL) {
Jeff Brown538881e2011-05-25 18:23:38 -07001820 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
Jeff Brownefd32662011-03-08 15:13:06 -08001821 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001822 } // release lock
1823}
1824
Jeff Brown6d0fec22010-07-23 21:28:06 -07001825
1826// --- TouchInputMapper ---
1827
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001828TouchInputMapper::TouchInputMapper(InputDevice* device) :
1829 InputMapper(device) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07001830 mLocked.surfaceOrientation = -1;
1831 mLocked.surfaceWidth = -1;
1832 mLocked.surfaceHeight = -1;
1833
1834 initializeLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001835}
1836
1837TouchInputMapper::~TouchInputMapper() {
1838}
1839
1840uint32_t TouchInputMapper::getSources() {
Jeff Brownace13b12011-03-09 17:39:48 -08001841 return mTouchSource | mPointerSource;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001842}
1843
1844void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1845 InputMapper::populateDeviceInfo(info);
1846
Jeff Brown6328cdc2010-07-29 18:18:33 -07001847 { // acquire lock
1848 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001849
Jeff Brown6328cdc2010-07-29 18:18:33 -07001850 // Ensure surface information is up to date so that orientation changes are
1851 // noticed immediately.
Jeff Brownefd32662011-03-08 15:13:06 -08001852 if (!configureSurfaceLocked()) {
1853 return;
1854 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001855
Jeff Brownefd32662011-03-08 15:13:06 -08001856 info->addMotionRange(mLocked.orientedRanges.x);
1857 info->addMotionRange(mLocked.orientedRanges.y);
Jeff Brown8d608662010-08-30 03:02:23 -07001858
1859 if (mLocked.orientedRanges.havePressure) {
Jeff Brownefd32662011-03-08 15:13:06 -08001860 info->addMotionRange(mLocked.orientedRanges.pressure);
Jeff Brown8d608662010-08-30 03:02:23 -07001861 }
1862
1863 if (mLocked.orientedRanges.haveSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001864 info->addMotionRange(mLocked.orientedRanges.size);
Jeff Brown8d608662010-08-30 03:02:23 -07001865 }
1866
Jeff Brownc6d282b2010-10-14 21:42:15 -07001867 if (mLocked.orientedRanges.haveTouchSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001868 info->addMotionRange(mLocked.orientedRanges.touchMajor);
1869 info->addMotionRange(mLocked.orientedRanges.touchMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001870 }
1871
Jeff Brownc6d282b2010-10-14 21:42:15 -07001872 if (mLocked.orientedRanges.haveToolSize) {
Jeff Brownefd32662011-03-08 15:13:06 -08001873 info->addMotionRange(mLocked.orientedRanges.toolMajor);
1874 info->addMotionRange(mLocked.orientedRanges.toolMinor);
Jeff Brown8d608662010-08-30 03:02:23 -07001875 }
1876
1877 if (mLocked.orientedRanges.haveOrientation) {
Jeff Brownefd32662011-03-08 15:13:06 -08001878 info->addMotionRange(mLocked.orientedRanges.orientation);
Jeff Brown8d608662010-08-30 03:02:23 -07001879 }
Jeff Brownace13b12011-03-09 17:39:48 -08001880
Jeff Brown80fd47c2011-05-24 01:07:44 -07001881 if (mLocked.orientedRanges.haveDistance) {
1882 info->addMotionRange(mLocked.orientedRanges.distance);
1883 }
1884
Jeff Brownace13b12011-03-09 17:39:48 -08001885 if (mPointerController != NULL) {
1886 float minX, minY, maxX, maxY;
1887 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
1888 info->addMotionRange(AMOTION_EVENT_AXIS_X, mPointerSource,
1889 minX, maxX, 0.0f, 0.0f);
1890 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mPointerSource,
1891 minY, maxY, 0.0f, 0.0f);
1892 }
1893 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mPointerSource,
1894 0.0f, 1.0f, 0.0f, 0.0f);
1895 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07001896 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07001897}
1898
Jeff Brownef3d7e82010-09-30 14:33:04 -07001899void TouchInputMapper::dump(String8& dump) {
1900 { // acquire lock
1901 AutoMutex _l(mLock);
1902 dump.append(INDENT2 "Touch Input Mapper:\n");
Jeff Brownef3d7e82010-09-30 14:33:04 -07001903 dumpParameters(dump);
1904 dumpVirtualKeysLocked(dump);
1905 dumpRawAxes(dump);
1906 dumpCalibration(dump);
1907 dumpSurfaceLocked(dump);
Jeff Brownefd32662011-03-08 15:13:06 -08001908
Jeff Brown511ee5f2010-10-18 13:32:20 -07001909 dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n");
Jeff Brownc6d282b2010-10-14 21:42:15 -07001910 dump.appendFormat(INDENT4 "XScale: %0.3f\n", mLocked.xScale);
1911 dump.appendFormat(INDENT4 "YScale: %0.3f\n", mLocked.yScale);
1912 dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mLocked.xPrecision);
1913 dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mLocked.yPrecision);
1914 dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mLocked.geometricScale);
1915 dump.appendFormat(INDENT4 "ToolSizeLinearScale: %0.3f\n", mLocked.toolSizeLinearScale);
1916 dump.appendFormat(INDENT4 "ToolSizeLinearBias: %0.3f\n", mLocked.toolSizeLinearBias);
1917 dump.appendFormat(INDENT4 "ToolSizeAreaScale: %0.3f\n", mLocked.toolSizeAreaScale);
1918 dump.appendFormat(INDENT4 "ToolSizeAreaBias: %0.3f\n", mLocked.toolSizeAreaBias);
1919 dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mLocked.pressureScale);
1920 dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mLocked.sizeScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001921 dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mLocked.orientationScale);
Jeff Brown80fd47c2011-05-24 01:07:44 -07001922 dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mLocked.distanceScale);
Jeff Brownefd32662011-03-08 15:13:06 -08001923
1924 dump.appendFormat(INDENT3 "Last Touch:\n");
Jeff Brownace13b12011-03-09 17:39:48 -08001925 dump.appendFormat(INDENT4 "Button State: 0x%08x\n", mLastTouch.buttonState);
Jeff Brownaba321a2011-06-28 20:34:40 -07001926 dump.appendFormat(INDENT4 "Pointer Count: %d\n", mLastTouch.pointerCount);
1927 for (uint32_t i = 0; i < mLastTouch.pointerCount; i++) {
1928 const PointerData& pointer = mLastTouch.pointers[i];
1929 dump.appendFormat(INDENT5 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
1930 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
1931 "orientation=%d, distance=%d, isStylus=%s\n", i,
1932 pointer.id, pointer.x, pointer.y, pointer.pressure,
1933 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor, pointer.toolMinor,
1934 pointer.orientation, pointer.distance, toString(pointer.isStylus));
1935 }
Jeff Brownace13b12011-03-09 17:39:48 -08001936
1937 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
1938 dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n");
1939 dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n",
1940 mLocked.pointerGestureXMovementScale);
1941 dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n",
1942 mLocked.pointerGestureYMovementScale);
1943 dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n",
1944 mLocked.pointerGestureXZoomScale);
1945 dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n",
1946 mLocked.pointerGestureYZoomScale);
Jeff Brown2352b972011-04-12 22:39:53 -07001947 dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n",
1948 mLocked.pointerGestureMaxSwipeWidth);
Jeff Brownace13b12011-03-09 17:39:48 -08001949 }
Jeff Brownef3d7e82010-09-30 14:33:04 -07001950 } // release lock
1951}
1952
Jeff Brown6328cdc2010-07-29 18:18:33 -07001953void TouchInputMapper::initializeLocked() {
1954 mCurrentTouch.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07001955 mLastTouch.clear();
1956 mDownTime = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001957
1958 for (uint32_t i = 0; i < MAX_POINTERS; i++) {
1959 mAveragingTouchFilter.historyStart[i] = 0;
1960 mAveragingTouchFilter.historyEnd[i] = 0;
1961 }
1962
1963 mJumpyTouchFilter.jumpyPointsDropped = 0;
Jeff Brown6328cdc2010-07-29 18:18:33 -07001964
1965 mLocked.currentVirtualKey.down = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001966
1967 mLocked.orientedRanges.havePressure = false;
1968 mLocked.orientedRanges.haveSize = false;
Jeff Brownc6d282b2010-10-14 21:42:15 -07001969 mLocked.orientedRanges.haveTouchSize = false;
1970 mLocked.orientedRanges.haveToolSize = false;
Jeff Brown8d608662010-08-30 03:02:23 -07001971 mLocked.orientedRanges.haveOrientation = false;
Jeff Brown80fd47c2011-05-24 01:07:44 -07001972 mLocked.orientedRanges.haveDistance = false;
Jeff Brownace13b12011-03-09 17:39:48 -08001973
1974 mPointerGesture.reset();
Jeff Brown8d608662010-08-30 03:02:23 -07001975}
1976
Jeff Brown474dcb52011-06-14 20:22:50 -07001977void TouchInputMapper::configure(const InputReaderConfiguration* config, uint32_t changes) {
1978 InputMapper::configure(config, changes);
Jeff Brown6d0fec22010-07-23 21:28:06 -07001979
Jeff Brown474dcb52011-06-14 20:22:50 -07001980 mConfig = *config;
Jeff Brown6d0fec22010-07-23 21:28:06 -07001981
Jeff Brown474dcb52011-06-14 20:22:50 -07001982 if (!changes) { // first time only
1983 // Configure basic parameters.
1984 configureParameters();
1985
1986 // Configure sources.
1987 switch (mParameters.deviceType) {
1988 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
1989 mTouchSource = AINPUT_SOURCE_TOUCHSCREEN;
1990 mPointerSource = 0;
1991 break;
1992 case Parameters::DEVICE_TYPE_TOUCH_PAD:
1993 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
1994 mPointerSource = 0;
1995 break;
1996 case Parameters::DEVICE_TYPE_POINTER:
1997 mTouchSource = AINPUT_SOURCE_TOUCHPAD;
1998 mPointerSource = AINPUT_SOURCE_MOUSE;
1999 break;
2000 default:
2001 LOG_ASSERT(false);
2002 }
2003
2004 // Configure absolute axis information.
2005 configureRawAxes();
2006
2007 // Prepare input device calibration.
2008 parseCalibration();
2009 resolveCalibration();
2010
2011 { // acquire lock
2012 AutoMutex _l(mLock);
2013
2014 // Configure surface dimensions and orientation.
2015 configureSurfaceLocked();
2016 } // release lock
Jeff Brown83c09682010-12-23 17:50:18 -08002017 }
2018
Jeff Brown474dcb52011-06-14 20:22:50 -07002019 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2020 mPointerGesture.pointerVelocityControl.setParameters(
2021 mConfig.pointerVelocityControlParameters);
2022 }
Jeff Brown8d608662010-08-30 03:02:23 -07002023
Jeff Brown474dcb52011-06-14 20:22:50 -07002024 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT)) {
2025 // Reset the touch screen when pointer gesture enablement changes.
2026 reset();
2027 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002028}
2029
Jeff Brown8d608662010-08-30 03:02:23 -07002030void TouchInputMapper::configureParameters() {
Jeff Brown474dcb52011-06-14 20:22:50 -07002031 mParameters.useBadTouchFilter = mConfig.filterTouchEvents;
2032 mParameters.useAveragingTouchFilter = mConfig.filterTouchEvents;
2033 mParameters.useJumpyTouchFilter = mConfig.filterJumpyTouchEvents;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002034
Jeff Brownb1268222011-06-03 17:06:16 -07002035 // Use the pointer presentation mode for devices that do not support distinct
2036 // multitouch. The spot-based presentation relies on being able to accurately
2037 // locate two or more fingers on the touch pad.
2038 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
2039 ? Parameters::GESTURE_MODE_POINTER : Parameters::GESTURE_MODE_SPOTS;
Jeff Brown2352b972011-04-12 22:39:53 -07002040
Jeff Brown538881e2011-05-25 18:23:38 -07002041 String8 gestureModeString;
2042 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
2043 gestureModeString)) {
2044 if (gestureModeString == "pointer") {
2045 mParameters.gestureMode = Parameters::GESTURE_MODE_POINTER;
2046 } else if (gestureModeString == "spots") {
2047 mParameters.gestureMode = Parameters::GESTURE_MODE_SPOTS;
2048 } else if (gestureModeString != "default") {
2049 LOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
2050 }
2051 }
2052
Jeff Brownace13b12011-03-09 17:39:48 -08002053 if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
2054 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
2055 // The device is a cursor device with a touch pad attached.
2056 // By default don't use the touch pad to move the pointer.
2057 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
Jeff Brown80fd47c2011-05-24 01:07:44 -07002058 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
2059 // The device is a pointing device like a track pad.
2060 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2061 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
2062 // The device is a touch screen.
2063 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brownace13b12011-03-09 17:39:48 -08002064 } else {
Jeff Brown80fd47c2011-05-24 01:07:44 -07002065 // The device is a touch pad of unknown purpose.
Jeff Brownace13b12011-03-09 17:39:48 -08002066 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
2067 }
2068
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002069 String8 deviceTypeString;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002070 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
2071 deviceTypeString)) {
Jeff Brown58a2da82011-01-25 16:02:22 -08002072 if (deviceTypeString == "touchScreen") {
2073 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brownefd32662011-03-08 15:13:06 -08002074 } else if (deviceTypeString == "touchPad") {
2075 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
Jeff Brownace13b12011-03-09 17:39:48 -08002076 } else if (deviceTypeString == "pointer") {
2077 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
Jeff Brown538881e2011-05-25 18:23:38 -07002078 } else if (deviceTypeString != "default") {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002079 LOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
2080 }
2081 }
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002082
Jeff Brownefd32662011-03-08 15:13:06 -08002083 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002084 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
2085 mParameters.orientationAware);
2086
Jeff Brownefd32662011-03-08 15:13:06 -08002087 mParameters.associatedDisplayId = mParameters.orientationAware
2088 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
Jeff Brownace13b12011-03-09 17:39:48 -08002089 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
Jeff Brownefd32662011-03-08 15:13:06 -08002090 ? 0 : -1;
Jeff Brown8d608662010-08-30 03:02:23 -07002091}
2092
Jeff Brownef3d7e82010-09-30 14:33:04 -07002093void TouchInputMapper::dumpParameters(String8& dump) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002094 dump.append(INDENT3 "Parameters:\n");
2095
Jeff Brown538881e2011-05-25 18:23:38 -07002096 switch (mParameters.gestureMode) {
2097 case Parameters::GESTURE_MODE_POINTER:
2098 dump.append(INDENT4 "GestureMode: pointer\n");
2099 break;
2100 case Parameters::GESTURE_MODE_SPOTS:
2101 dump.append(INDENT4 "GestureMode: spots\n");
2102 break;
2103 default:
2104 assert(false);
2105 }
2106
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002107 switch (mParameters.deviceType) {
2108 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
2109 dump.append(INDENT4 "DeviceType: touchScreen\n");
2110 break;
2111 case Parameters::DEVICE_TYPE_TOUCH_PAD:
2112 dump.append(INDENT4 "DeviceType: touchPad\n");
2113 break;
Jeff Brownace13b12011-03-09 17:39:48 -08002114 case Parameters::DEVICE_TYPE_POINTER:
2115 dump.append(INDENT4 "DeviceType: pointer\n");
2116 break;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002117 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002118 LOG_ASSERT(false);
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002119 }
2120
2121 dump.appendFormat(INDENT4 "AssociatedDisplayId: %d\n",
2122 mParameters.associatedDisplayId);
2123 dump.appendFormat(INDENT4 "OrientationAware: %s\n",
2124 toString(mParameters.orientationAware));
2125
2126 dump.appendFormat(INDENT4 "UseBadTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07002127 toString(mParameters.useBadTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002128 dump.appendFormat(INDENT4 "UseAveragingTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07002129 toString(mParameters.useAveragingTouchFilter));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002130 dump.appendFormat(INDENT4 "UseJumpyTouchFilter: %s\n",
Jeff Brownef3d7e82010-09-30 14:33:04 -07002131 toString(mParameters.useJumpyTouchFilter));
Jeff Brownb88102f2010-09-08 11:49:43 -07002132}
2133
Jeff Brown8d608662010-08-30 03:02:23 -07002134void TouchInputMapper::configureRawAxes() {
2135 mRawAxes.x.clear();
2136 mRawAxes.y.clear();
2137 mRawAxes.pressure.clear();
2138 mRawAxes.touchMajor.clear();
2139 mRawAxes.touchMinor.clear();
2140 mRawAxes.toolMajor.clear();
2141 mRawAxes.toolMinor.clear();
2142 mRawAxes.orientation.clear();
Jeff Brown80fd47c2011-05-24 01:07:44 -07002143 mRawAxes.distance.clear();
2144 mRawAxes.trackingId.clear();
2145 mRawAxes.slot.clear();
Jeff Brown8d608662010-08-30 03:02:23 -07002146}
2147
Jeff Brownef3d7e82010-09-30 14:33:04 -07002148void TouchInputMapper::dumpRawAxes(String8& dump) {
2149 dump.append(INDENT3 "Raw Axes:\n");
Jeff Browncb1404e2011-01-15 18:14:15 -08002150 dumpRawAbsoluteAxisInfo(dump, mRawAxes.x, "X");
2151 dumpRawAbsoluteAxisInfo(dump, mRawAxes.y, "Y");
2152 dumpRawAbsoluteAxisInfo(dump, mRawAxes.pressure, "Pressure");
2153 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMajor, "TouchMajor");
2154 dumpRawAbsoluteAxisInfo(dump, mRawAxes.touchMinor, "TouchMinor");
2155 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMajor, "ToolMajor");
2156 dumpRawAbsoluteAxisInfo(dump, mRawAxes.toolMinor, "ToolMinor");
2157 dumpRawAbsoluteAxisInfo(dump, mRawAxes.orientation, "Orientation");
Jeff Brown80fd47c2011-05-24 01:07:44 -07002158 dumpRawAbsoluteAxisInfo(dump, mRawAxes.distance, "Distance");
2159 dumpRawAbsoluteAxisInfo(dump, mRawAxes.trackingId, "TrackingId");
2160 dumpRawAbsoluteAxisInfo(dump, mRawAxes.slot, "Slot");
Jeff Brown6d0fec22010-07-23 21:28:06 -07002161}
2162
Jeff Brown6328cdc2010-07-29 18:18:33 -07002163bool TouchInputMapper::configureSurfaceLocked() {
Jeff Brown9626b142011-03-03 02:09:54 -08002164 // Ensure we have valid X and Y axes.
2165 if (!mRawAxes.x.valid || !mRawAxes.y.valid) {
2166 LOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
2167 "The device will be inoperable.", getDeviceName().string());
2168 return false;
2169 }
2170
Jeff Brown6d0fec22010-07-23 21:28:06 -07002171 // Update orientation and dimensions if needed.
Jeff Brownb4ff35d2011-01-02 16:37:43 -08002172 int32_t orientation = DISPLAY_ORIENTATION_0;
Jeff Brown9626b142011-03-03 02:09:54 -08002173 int32_t width = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2174 int32_t height = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002175
2176 if (mParameters.associatedDisplayId >= 0) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002177 // Note: getDisplayInfo is non-reentrant so we can continue holding the lock.
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002178 if (! getPolicy()->getDisplayInfo(mParameters.associatedDisplayId,
Jeff Brownefd32662011-03-08 15:13:06 -08002179 &mLocked.associatedDisplayWidth, &mLocked.associatedDisplayHeight,
2180 &mLocked.associatedDisplayOrientation)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07002181 return false;
2182 }
Jeff Brownefd32662011-03-08 15:13:06 -08002183
2184 // A touch screen inherits the dimensions of the display.
2185 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
2186 width = mLocked.associatedDisplayWidth;
2187 height = mLocked.associatedDisplayHeight;
2188 }
2189
2190 // The device inherits the orientation of the display if it is orientation aware.
2191 if (mParameters.orientationAware) {
2192 orientation = mLocked.associatedDisplayOrientation;
2193 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002194 }
2195
Jeff Brownace13b12011-03-09 17:39:48 -08002196 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
2197 && mPointerController == NULL) {
2198 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2199 }
2200
Jeff Brown6328cdc2010-07-29 18:18:33 -07002201 bool orientationChanged = mLocked.surfaceOrientation != orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002202 if (orientationChanged) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07002203 mLocked.surfaceOrientation = orientation;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002204 }
2205
Jeff Brown6328cdc2010-07-29 18:18:33 -07002206 bool sizeChanged = mLocked.surfaceWidth != width || mLocked.surfaceHeight != height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002207 if (sizeChanged) {
Jeff Brownefd32662011-03-08 15:13:06 -08002208 LOGI("Device reconfigured: id=%d, name='%s', surface size is now %dx%d",
Jeff Brownef3d7e82010-09-30 14:33:04 -07002209 getDeviceId(), getDeviceName().string(), width, height);
Jeff Brown8d608662010-08-30 03:02:23 -07002210
Jeff Brown6328cdc2010-07-29 18:18:33 -07002211 mLocked.surfaceWidth = width;
2212 mLocked.surfaceHeight = height;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002213
Jeff Brown8d608662010-08-30 03:02:23 -07002214 // Configure X and Y factors.
Jeff Brown9626b142011-03-03 02:09:54 -08002215 mLocked.xScale = float(width) / (mRawAxes.x.maxValue - mRawAxes.x.minValue + 1);
2216 mLocked.yScale = float(height) / (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1);
2217 mLocked.xPrecision = 1.0f / mLocked.xScale;
2218 mLocked.yPrecision = 1.0f / mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002219
Jeff Brownefd32662011-03-08 15:13:06 -08002220 mLocked.orientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
2221 mLocked.orientedRanges.x.source = mTouchSource;
2222 mLocked.orientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
2223 mLocked.orientedRanges.y.source = mTouchSource;
2224
Jeff Brown9626b142011-03-03 02:09:54 -08002225 configureVirtualKeysLocked();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002226
Jeff Brown8d608662010-08-30 03:02:23 -07002227 // Scale factor for terms that are not oriented in a particular axis.
2228 // If the pixels are square then xScale == yScale otherwise we fake it
2229 // by choosing an average.
2230 mLocked.geometricScale = avg(mLocked.xScale, mLocked.yScale);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002231
Jeff Brown8d608662010-08-30 03:02:23 -07002232 // Size of diagonal axis.
Jeff Brown2352b972011-04-12 22:39:53 -07002233 float diagonalSize = hypotf(width, height);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002234
Jeff Brown8d608662010-08-30 03:02:23 -07002235 // TouchMajor and TouchMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002236 if (mCalibration.touchSizeCalibration != Calibration::TOUCH_SIZE_CALIBRATION_NONE) {
2237 mLocked.orientedRanges.haveTouchSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002238
2239 mLocked.orientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
2240 mLocked.orientedRanges.touchMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002241 mLocked.orientedRanges.touchMajor.min = 0;
2242 mLocked.orientedRanges.touchMajor.max = diagonalSize;
2243 mLocked.orientedRanges.touchMajor.flat = 0;
2244 mLocked.orientedRanges.touchMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08002245
Jeff Brown8d608662010-08-30 03:02:23 -07002246 mLocked.orientedRanges.touchMinor = mLocked.orientedRanges.touchMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08002247 mLocked.orientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002248 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002249
Jeff Brown8d608662010-08-30 03:02:23 -07002250 // ToolMajor and ToolMinor factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002251 mLocked.toolSizeLinearScale = 0;
2252 mLocked.toolSizeLinearBias = 0;
2253 mLocked.toolSizeAreaScale = 0;
2254 mLocked.toolSizeAreaBias = 0;
2255 if (mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2256 if (mCalibration.toolSizeCalibration == Calibration::TOOL_SIZE_CALIBRATION_LINEAR) {
2257 if (mCalibration.haveToolSizeLinearScale) {
2258 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
Jeff Brown8d608662010-08-30 03:02:23 -07002259 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002260 mLocked.toolSizeLinearScale = float(min(width, height))
Jeff Brown8d608662010-08-30 03:02:23 -07002261 / mRawAxes.toolMajor.maxValue;
2262 }
2263
Jeff Brownc6d282b2010-10-14 21:42:15 -07002264 if (mCalibration.haveToolSizeLinearBias) {
2265 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2266 }
2267 } else if (mCalibration.toolSizeCalibration ==
2268 Calibration::TOOL_SIZE_CALIBRATION_AREA) {
2269 if (mCalibration.haveToolSizeLinearScale) {
2270 mLocked.toolSizeLinearScale = mCalibration.toolSizeLinearScale;
2271 } else {
2272 mLocked.toolSizeLinearScale = min(width, height);
2273 }
2274
2275 if (mCalibration.haveToolSizeLinearBias) {
2276 mLocked.toolSizeLinearBias = mCalibration.toolSizeLinearBias;
2277 }
2278
2279 if (mCalibration.haveToolSizeAreaScale) {
2280 mLocked.toolSizeAreaScale = mCalibration.toolSizeAreaScale;
2281 } else if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2282 mLocked.toolSizeAreaScale = 1.0f / mRawAxes.toolMajor.maxValue;
2283 }
2284
2285 if (mCalibration.haveToolSizeAreaBias) {
2286 mLocked.toolSizeAreaBias = mCalibration.toolSizeAreaBias;
Jeff Brown8d608662010-08-30 03:02:23 -07002287 }
2288 }
2289
Jeff Brownc6d282b2010-10-14 21:42:15 -07002290 mLocked.orientedRanges.haveToolSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002291
2292 mLocked.orientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
2293 mLocked.orientedRanges.toolMajor.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002294 mLocked.orientedRanges.toolMajor.min = 0;
2295 mLocked.orientedRanges.toolMajor.max = diagonalSize;
2296 mLocked.orientedRanges.toolMajor.flat = 0;
2297 mLocked.orientedRanges.toolMajor.fuzz = 0;
Jeff Brownefd32662011-03-08 15:13:06 -08002298
Jeff Brown8d608662010-08-30 03:02:23 -07002299 mLocked.orientedRanges.toolMinor = mLocked.orientedRanges.toolMajor;
Jeff Brownefd32662011-03-08 15:13:06 -08002300 mLocked.orientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002301 }
2302
2303 // Pressure factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002304 mLocked.pressureScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002305 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE) {
2306 RawAbsoluteAxisInfo rawPressureAxis;
2307 switch (mCalibration.pressureSource) {
2308 case Calibration::PRESSURE_SOURCE_PRESSURE:
2309 rawPressureAxis = mRawAxes.pressure;
2310 break;
2311 case Calibration::PRESSURE_SOURCE_TOUCH:
2312 rawPressureAxis = mRawAxes.touchMajor;
2313 break;
2314 default:
2315 rawPressureAxis.clear();
2316 }
2317
Jeff Brown8d608662010-08-30 03:02:23 -07002318 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
2319 || mCalibration.pressureCalibration
2320 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
2321 if (mCalibration.havePressureScale) {
2322 mLocked.pressureScale = mCalibration.pressureScale;
2323 } else if (rawPressureAxis.valid && rawPressureAxis.maxValue != 0) {
2324 mLocked.pressureScale = 1.0f / rawPressureAxis.maxValue;
2325 }
2326 }
2327
2328 mLocked.orientedRanges.havePressure = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002329
2330 mLocked.orientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
2331 mLocked.orientedRanges.pressure.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002332 mLocked.orientedRanges.pressure.min = 0;
2333 mLocked.orientedRanges.pressure.max = 1.0;
2334 mLocked.orientedRanges.pressure.flat = 0;
2335 mLocked.orientedRanges.pressure.fuzz = 0;
2336 }
2337
2338 // Size factors.
Jeff Brownc6d282b2010-10-14 21:42:15 -07002339 mLocked.sizeScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002340 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002341 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_NORMALIZED) {
2342 if (mRawAxes.toolMajor.valid && mRawAxes.toolMajor.maxValue != 0) {
2343 mLocked.sizeScale = 1.0f / mRawAxes.toolMajor.maxValue;
2344 }
2345 }
2346
2347 mLocked.orientedRanges.haveSize = true;
Jeff Brownefd32662011-03-08 15:13:06 -08002348
2349 mLocked.orientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
2350 mLocked.orientedRanges.size.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002351 mLocked.orientedRanges.size.min = 0;
2352 mLocked.orientedRanges.size.max = 1.0;
2353 mLocked.orientedRanges.size.flat = 0;
2354 mLocked.orientedRanges.size.fuzz = 0;
2355 }
2356
2357 // Orientation
Jeff Brownc6d282b2010-10-14 21:42:15 -07002358 mLocked.orientationScale = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07002359 if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) {
Jeff Brown8d608662010-08-30 03:02:23 -07002360 if (mCalibration.orientationCalibration
2361 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
2362 if (mRawAxes.orientation.valid && mRawAxes.orientation.maxValue != 0) {
2363 mLocked.orientationScale = float(M_PI_2) / mRawAxes.orientation.maxValue;
2364 }
2365 }
2366
Jeff Brown80fd47c2011-05-24 01:07:44 -07002367 mLocked.orientedRanges.haveOrientation = true;
2368
Jeff Brownefd32662011-03-08 15:13:06 -08002369 mLocked.orientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
2370 mLocked.orientedRanges.orientation.source = mTouchSource;
Jeff Brown8d608662010-08-30 03:02:23 -07002371 mLocked.orientedRanges.orientation.min = - M_PI_2;
2372 mLocked.orientedRanges.orientation.max = M_PI_2;
2373 mLocked.orientedRanges.orientation.flat = 0;
2374 mLocked.orientedRanges.orientation.fuzz = 0;
2375 }
Jeff Brown80fd47c2011-05-24 01:07:44 -07002376
2377 // Distance
2378 mLocked.distanceScale = 0;
2379 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
2380 if (mCalibration.distanceCalibration
2381 == Calibration::DISTANCE_CALIBRATION_SCALED) {
2382 if (mCalibration.haveDistanceScale) {
2383 mLocked.distanceScale = mCalibration.distanceScale;
2384 } else {
2385 mLocked.distanceScale = 1.0f;
2386 }
2387 }
2388
2389 mLocked.orientedRanges.haveDistance = true;
2390
2391 mLocked.orientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
2392 mLocked.orientedRanges.distance.source = mTouchSource;
2393 mLocked.orientedRanges.distance.min =
2394 mRawAxes.distance.minValue * mLocked.distanceScale;
2395 mLocked.orientedRanges.distance.max =
2396 mRawAxes.distance.minValue * mLocked.distanceScale;
2397 mLocked.orientedRanges.distance.flat = 0;
2398 mLocked.orientedRanges.distance.fuzz =
2399 mRawAxes.distance.fuzz * mLocked.distanceScale;
2400 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002401 }
2402
2403 if (orientationChanged || sizeChanged) {
Jeff Brown9626b142011-03-03 02:09:54 -08002404 // Compute oriented surface dimensions, precision, scales and ranges.
2405 // Note that the maximum value reported is an inclusive maximum value so it is one
2406 // unit less than the total width or height of surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07002407 switch (mLocked.surfaceOrientation) {
Jeff Brownb4ff35d2011-01-02 16:37:43 -08002408 case DISPLAY_ORIENTATION_90:
2409 case DISPLAY_ORIENTATION_270:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002410 mLocked.orientedSurfaceWidth = mLocked.surfaceHeight;
2411 mLocked.orientedSurfaceHeight = mLocked.surfaceWidth;
Jeff Brown9626b142011-03-03 02:09:54 -08002412
Jeff Brown6328cdc2010-07-29 18:18:33 -07002413 mLocked.orientedXPrecision = mLocked.yPrecision;
2414 mLocked.orientedYPrecision = mLocked.xPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002415
2416 mLocked.orientedRanges.x.min = 0;
2417 mLocked.orientedRanges.x.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2418 * mLocked.yScale;
2419 mLocked.orientedRanges.x.flat = 0;
2420 mLocked.orientedRanges.x.fuzz = mLocked.yScale;
2421
2422 mLocked.orientedRanges.y.min = 0;
2423 mLocked.orientedRanges.y.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2424 * mLocked.xScale;
2425 mLocked.orientedRanges.y.flat = 0;
2426 mLocked.orientedRanges.y.fuzz = mLocked.xScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002427 break;
Jeff Brown9626b142011-03-03 02:09:54 -08002428
Jeff Brown6d0fec22010-07-23 21:28:06 -07002429 default:
Jeff Brown6328cdc2010-07-29 18:18:33 -07002430 mLocked.orientedSurfaceWidth = mLocked.surfaceWidth;
2431 mLocked.orientedSurfaceHeight = mLocked.surfaceHeight;
Jeff Brown9626b142011-03-03 02:09:54 -08002432
Jeff Brown6328cdc2010-07-29 18:18:33 -07002433 mLocked.orientedXPrecision = mLocked.xPrecision;
2434 mLocked.orientedYPrecision = mLocked.yPrecision;
Jeff Brown9626b142011-03-03 02:09:54 -08002435
2436 mLocked.orientedRanges.x.min = 0;
2437 mLocked.orientedRanges.x.max = (mRawAxes.x.maxValue - mRawAxes.x.minValue)
2438 * mLocked.xScale;
2439 mLocked.orientedRanges.x.flat = 0;
2440 mLocked.orientedRanges.x.fuzz = mLocked.xScale;
2441
2442 mLocked.orientedRanges.y.min = 0;
2443 mLocked.orientedRanges.y.max = (mRawAxes.y.maxValue - mRawAxes.y.minValue)
2444 * mLocked.yScale;
2445 mLocked.orientedRanges.y.flat = 0;
2446 mLocked.orientedRanges.y.fuzz = mLocked.yScale;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002447 break;
2448 }
Jeff Brownace13b12011-03-09 17:39:48 -08002449
2450 // Compute pointer gesture detection parameters.
2451 // TODO: These factors should not be hardcoded.
2452 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
2453 int32_t rawWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2454 int32_t rawHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown2352b972011-04-12 22:39:53 -07002455 float rawDiagonal = hypotf(rawWidth, rawHeight);
2456 float displayDiagonal = hypotf(mLocked.associatedDisplayWidth,
2457 mLocked.associatedDisplayHeight);
Jeff Brownace13b12011-03-09 17:39:48 -08002458
Jeff Brown2352b972011-04-12 22:39:53 -07002459 // Scale movements such that one whole swipe of the touch pad covers a
Jeff Brown19c97d462011-06-01 12:33:19 -07002460 // given area relative to the diagonal size of the display when no acceleration
2461 // is applied.
Jeff Brownace13b12011-03-09 17:39:48 -08002462 // Assume that the touch pad has a square aspect ratio such that movements in
2463 // X and Y of the same number of raw units cover the same physical distance.
Jeff Brown474dcb52011-06-14 20:22:50 -07002464 mLocked.pointerGestureXMovementScale = mConfig.pointerGestureMovementSpeedRatio
Jeff Brown2352b972011-04-12 22:39:53 -07002465 * displayDiagonal / rawDiagonal;
Jeff Brownace13b12011-03-09 17:39:48 -08002466 mLocked.pointerGestureYMovementScale = mLocked.pointerGestureXMovementScale;
2467
2468 // Scale zooms to cover a smaller range of the display than movements do.
2469 // This value determines the area around the pointer that is affected by freeform
2470 // pointer gestures.
Jeff Brown474dcb52011-06-14 20:22:50 -07002471 mLocked.pointerGestureXZoomScale = mConfig.pointerGestureZoomSpeedRatio
Jeff Brown2352b972011-04-12 22:39:53 -07002472 * displayDiagonal / rawDiagonal;
2473 mLocked.pointerGestureYZoomScale = mLocked.pointerGestureXZoomScale;
Jeff Brownace13b12011-03-09 17:39:48 -08002474
Jeff Brown2352b972011-04-12 22:39:53 -07002475 // Max width between pointers to detect a swipe gesture is more than some fraction
2476 // of the diagonal axis of the touch pad. Touches that are wider than this are
2477 // translated into freeform gestures.
Jeff Brown214eaf42011-05-26 19:17:02 -07002478 mLocked.pointerGestureMaxSwipeWidth =
Jeff Brown474dcb52011-06-14 20:22:50 -07002479 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
Jeff Brown2352b972011-04-12 22:39:53 -07002480
2481 // Reset the current pointer gesture.
2482 mPointerGesture.reset();
2483
2484 // Remove any current spots.
2485 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
2486 mPointerController->clearSpots();
2487 }
Jeff Brownace13b12011-03-09 17:39:48 -08002488 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002489 }
2490
2491 return true;
2492}
2493
Jeff Brownef3d7e82010-09-30 14:33:04 -07002494void TouchInputMapper::dumpSurfaceLocked(String8& dump) {
2495 dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mLocked.surfaceWidth);
2496 dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mLocked.surfaceHeight);
2497 dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mLocked.surfaceOrientation);
Jeff Brownb88102f2010-09-08 11:49:43 -07002498}
2499
Jeff Brown6328cdc2010-07-29 18:18:33 -07002500void TouchInputMapper::configureVirtualKeysLocked() {
Jeff Brown8d608662010-08-30 03:02:23 -07002501 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
Jeff Brown90655042010-12-02 13:50:46 -08002502 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
Jeff Brown6d0fec22010-07-23 21:28:06 -07002503
Jeff Brown6328cdc2010-07-29 18:18:33 -07002504 mLocked.virtualKeys.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002505
Jeff Brown6328cdc2010-07-29 18:18:33 -07002506 if (virtualKeyDefinitions.size() == 0) {
2507 return;
2508 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002509
Jeff Brown6328cdc2010-07-29 18:18:33 -07002510 mLocked.virtualKeys.setCapacity(virtualKeyDefinitions.size());
2511
Jeff Brown8d608662010-08-30 03:02:23 -07002512 int32_t touchScreenLeft = mRawAxes.x.minValue;
2513 int32_t touchScreenTop = mRawAxes.y.minValue;
Jeff Brown9626b142011-03-03 02:09:54 -08002514 int32_t touchScreenWidth = mRawAxes.x.maxValue - mRawAxes.x.minValue + 1;
2515 int32_t touchScreenHeight = mRawAxes.y.maxValue - mRawAxes.y.minValue + 1;
Jeff Brown6328cdc2010-07-29 18:18:33 -07002516
2517 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
Jeff Brown8d608662010-08-30 03:02:23 -07002518 const VirtualKeyDefinition& virtualKeyDefinition =
Jeff Brown6328cdc2010-07-29 18:18:33 -07002519 virtualKeyDefinitions[i];
2520
2521 mLocked.virtualKeys.add();
2522 VirtualKey& virtualKey = mLocked.virtualKeys.editTop();
2523
2524 virtualKey.scanCode = virtualKeyDefinition.scanCode;
2525 int32_t keyCode;
2526 uint32_t flags;
Jeff Brown6f2fba42011-02-19 01:08:02 -08002527 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode,
Jeff Brown6328cdc2010-07-29 18:18:33 -07002528 & keyCode, & flags)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002529 LOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
2530 virtualKey.scanCode);
Jeff Brown6328cdc2010-07-29 18:18:33 -07002531 mLocked.virtualKeys.pop(); // drop the key
2532 continue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002533 }
2534
Jeff Brown6328cdc2010-07-29 18:18:33 -07002535 virtualKey.keyCode = keyCode;
2536 virtualKey.flags = flags;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002537
Jeff Brown6328cdc2010-07-29 18:18:33 -07002538 // convert the key definition's display coordinates into touch coordinates for a hit box
2539 int32_t halfWidth = virtualKeyDefinition.width / 2;
2540 int32_t halfHeight = virtualKeyDefinition.height / 2;
Jeff Brown6d0fec22010-07-23 21:28:06 -07002541
Jeff Brown6328cdc2010-07-29 18:18:33 -07002542 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
2543 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2544 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
2545 * touchScreenWidth / mLocked.surfaceWidth + touchScreenLeft;
2546 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
2547 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
2548 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
2549 * touchScreenHeight / mLocked.surfaceHeight + touchScreenTop;
Jeff Brownef3d7e82010-09-30 14:33:04 -07002550 }
2551}
2552
2553void TouchInputMapper::dumpVirtualKeysLocked(String8& dump) {
2554 if (!mLocked.virtualKeys.isEmpty()) {
2555 dump.append(INDENT3 "Virtual Keys:\n");
2556
2557 for (size_t i = 0; i < mLocked.virtualKeys.size(); i++) {
2558 const VirtualKey& virtualKey = mLocked.virtualKeys.itemAt(i);
2559 dump.appendFormat(INDENT4 "%d: scanCode=%d, keyCode=%d, "
2560 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
2561 i, virtualKey.scanCode, virtualKey.keyCode,
2562 virtualKey.hitLeft, virtualKey.hitRight,
2563 virtualKey.hitTop, virtualKey.hitBottom);
2564 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002565 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07002566}
2567
Jeff Brown8d608662010-08-30 03:02:23 -07002568void TouchInputMapper::parseCalibration() {
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002569 const PropertyMap& in = getDevice()->getConfiguration();
Jeff Brown8d608662010-08-30 03:02:23 -07002570 Calibration& out = mCalibration;
2571
Jeff Brownc6d282b2010-10-14 21:42:15 -07002572 // Touch Size
2573 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT;
2574 String8 touchSizeCalibrationString;
2575 if (in.tryGetProperty(String8("touch.touchSize.calibration"), touchSizeCalibrationString)) {
2576 if (touchSizeCalibrationString == "none") {
2577 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
2578 } else if (touchSizeCalibrationString == "geometric") {
2579 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC;
2580 } else if (touchSizeCalibrationString == "pressure") {
2581 out.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
2582 } else if (touchSizeCalibrationString != "default") {
2583 LOGW("Invalid value for touch.touchSize.calibration: '%s'",
2584 touchSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002585 }
2586 }
2587
Jeff Brownc6d282b2010-10-14 21:42:15 -07002588 // Tool Size
2589 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_DEFAULT;
2590 String8 toolSizeCalibrationString;
2591 if (in.tryGetProperty(String8("touch.toolSize.calibration"), toolSizeCalibrationString)) {
2592 if (toolSizeCalibrationString == "none") {
2593 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
2594 } else if (toolSizeCalibrationString == "geometric") {
2595 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC;
2596 } else if (toolSizeCalibrationString == "linear") {
2597 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
2598 } else if (toolSizeCalibrationString == "area") {
2599 out.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_AREA;
2600 } else if (toolSizeCalibrationString != "default") {
2601 LOGW("Invalid value for touch.toolSize.calibration: '%s'",
2602 toolSizeCalibrationString.string());
Jeff Brown8d608662010-08-30 03:02:23 -07002603 }
2604 }
2605
Jeff Brownc6d282b2010-10-14 21:42:15 -07002606 out.haveToolSizeLinearScale = in.tryGetProperty(String8("touch.toolSize.linearScale"),
2607 out.toolSizeLinearScale);
2608 out.haveToolSizeLinearBias = in.tryGetProperty(String8("touch.toolSize.linearBias"),
2609 out.toolSizeLinearBias);
2610 out.haveToolSizeAreaScale = in.tryGetProperty(String8("touch.toolSize.areaScale"),
2611 out.toolSizeAreaScale);
2612 out.haveToolSizeAreaBias = in.tryGetProperty(String8("touch.toolSize.areaBias"),
2613 out.toolSizeAreaBias);
2614 out.haveToolSizeIsSummed = in.tryGetProperty(String8("touch.toolSize.isSummed"),
2615 out.toolSizeIsSummed);
Jeff Brown8d608662010-08-30 03:02:23 -07002616
2617 // Pressure
2618 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
2619 String8 pressureCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002620 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002621 if (pressureCalibrationString == "none") {
2622 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2623 } else if (pressureCalibrationString == "physical") {
2624 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
2625 } else if (pressureCalibrationString == "amplitude") {
2626 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2627 } else if (pressureCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002628 LOGW("Invalid value for touch.pressure.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002629 pressureCalibrationString.string());
2630 }
2631 }
2632
2633 out.pressureSource = Calibration::PRESSURE_SOURCE_DEFAULT;
2634 String8 pressureSourceString;
2635 if (in.tryGetProperty(String8("touch.pressure.source"), pressureSourceString)) {
2636 if (pressureSourceString == "pressure") {
2637 out.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2638 } else if (pressureSourceString == "touch") {
2639 out.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2640 } else if (pressureSourceString != "default") {
2641 LOGW("Invalid value for touch.pressure.source: '%s'",
2642 pressureSourceString.string());
2643 }
2644 }
2645
2646 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
2647 out.pressureScale);
2648
2649 // Size
2650 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
2651 String8 sizeCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002652 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002653 if (sizeCalibrationString == "none") {
2654 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2655 } else if (sizeCalibrationString == "normalized") {
2656 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2657 } else if (sizeCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002658 LOGW("Invalid value for touch.size.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002659 sizeCalibrationString.string());
2660 }
2661 }
2662
2663 // Orientation
2664 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
2665 String8 orientationCalibrationString;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002666 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
Jeff Brown8d608662010-08-30 03:02:23 -07002667 if (orientationCalibrationString == "none") {
2668 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2669 } else if (orientationCalibrationString == "interpolated") {
2670 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002671 } else if (orientationCalibrationString == "vector") {
2672 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
Jeff Brown8d608662010-08-30 03:02:23 -07002673 } else if (orientationCalibrationString != "default") {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002674 LOGW("Invalid value for touch.orientation.calibration: '%s'",
Jeff Brown8d608662010-08-30 03:02:23 -07002675 orientationCalibrationString.string());
2676 }
2677 }
Jeff Brown80fd47c2011-05-24 01:07:44 -07002678
2679 // Distance
2680 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
2681 String8 distanceCalibrationString;
2682 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
2683 if (distanceCalibrationString == "none") {
2684 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
2685 } else if (distanceCalibrationString == "scaled") {
2686 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
2687 } else if (distanceCalibrationString != "default") {
2688 LOGW("Invalid value for touch.distance.calibration: '%s'",
2689 distanceCalibrationString.string());
2690 }
2691 }
2692
2693 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
2694 out.distanceScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002695}
2696
2697void TouchInputMapper::resolveCalibration() {
2698 // Pressure
2699 switch (mCalibration.pressureSource) {
2700 case Calibration::PRESSURE_SOURCE_DEFAULT:
2701 if (mRawAxes.pressure.valid) {
2702 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_PRESSURE;
2703 } else if (mRawAxes.touchMajor.valid) {
2704 mCalibration.pressureSource = Calibration::PRESSURE_SOURCE_TOUCH;
2705 }
2706 break;
2707
2708 case Calibration::PRESSURE_SOURCE_PRESSURE:
2709 if (! mRawAxes.pressure.valid) {
2710 LOGW("Calibration property touch.pressure.source is 'pressure' but "
2711 "the pressure axis is not available.");
2712 }
2713 break;
2714
2715 case Calibration::PRESSURE_SOURCE_TOUCH:
2716 if (! mRawAxes.touchMajor.valid) {
2717 LOGW("Calibration property touch.pressure.source is 'touch' but "
2718 "the touchMajor axis is not available.");
2719 }
2720 break;
2721
2722 default:
2723 break;
2724 }
2725
2726 switch (mCalibration.pressureCalibration) {
2727 case Calibration::PRESSURE_CALIBRATION_DEFAULT:
2728 if (mCalibration.pressureSource != Calibration::PRESSURE_SOURCE_DEFAULT) {
2729 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
2730 } else {
2731 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
2732 }
2733 break;
2734
2735 default:
2736 break;
2737 }
2738
Jeff Brownc6d282b2010-10-14 21:42:15 -07002739 // Tool Size
2740 switch (mCalibration.toolSizeCalibration) {
2741 case Calibration::TOOL_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002742 if (mRawAxes.toolMajor.valid) {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002743 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_LINEAR;
Jeff Brown8d608662010-08-30 03:02:23 -07002744 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002745 mCalibration.toolSizeCalibration = Calibration::TOOL_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002746 }
2747 break;
2748
2749 default:
2750 break;
2751 }
2752
Jeff Brownc6d282b2010-10-14 21:42:15 -07002753 // Touch Size
2754 switch (mCalibration.touchSizeCalibration) {
2755 case Calibration::TOUCH_SIZE_CALIBRATION_DEFAULT:
Jeff Brown8d608662010-08-30 03:02:23 -07002756 if (mCalibration.pressureCalibration != Calibration::PRESSURE_CALIBRATION_NONE
Jeff Brownc6d282b2010-10-14 21:42:15 -07002757 && mCalibration.toolSizeCalibration != Calibration::TOOL_SIZE_CALIBRATION_NONE) {
2758 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE;
Jeff Brown8d608662010-08-30 03:02:23 -07002759 } else {
Jeff Brownc6d282b2010-10-14 21:42:15 -07002760 mCalibration.touchSizeCalibration = Calibration::TOUCH_SIZE_CALIBRATION_NONE;
Jeff Brown8d608662010-08-30 03:02:23 -07002761 }
2762 break;
2763
2764 default:
2765 break;
2766 }
2767
2768 // Size
2769 switch (mCalibration.sizeCalibration) {
2770 case Calibration::SIZE_CALIBRATION_DEFAULT:
2771 if (mRawAxes.toolMajor.valid) {
2772 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NORMALIZED;
2773 } else {
2774 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
2775 }
2776 break;
2777
2778 default:
2779 break;
2780 }
2781
2782 // Orientation
2783 switch (mCalibration.orientationCalibration) {
2784 case Calibration::ORIENTATION_CALIBRATION_DEFAULT:
2785 if (mRawAxes.orientation.valid) {
2786 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
2787 } else {
2788 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
2789 }
2790 break;
2791
2792 default:
2793 break;
2794 }
Jeff Brown80fd47c2011-05-24 01:07:44 -07002795
2796 // Distance
2797 switch (mCalibration.distanceCalibration) {
2798 case Calibration::DISTANCE_CALIBRATION_DEFAULT:
2799 if (mRawAxes.distance.valid) {
2800 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
2801 } else {
2802 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
2803 }
2804 break;
2805
2806 default:
2807 break;
2808 }
Jeff Brown8d608662010-08-30 03:02:23 -07002809}
2810
Jeff Brownef3d7e82010-09-30 14:33:04 -07002811void TouchInputMapper::dumpCalibration(String8& dump) {
2812 dump.append(INDENT3 "Calibration:\n");
Jeff Brownb88102f2010-09-08 11:49:43 -07002813
Jeff Brownc6d282b2010-10-14 21:42:15 -07002814 // Touch Size
2815 switch (mCalibration.touchSizeCalibration) {
2816 case Calibration::TOUCH_SIZE_CALIBRATION_NONE:
2817 dump.append(INDENT4 "touch.touchSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002818 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002819 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
2820 dump.append(INDENT4 "touch.touchSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002821 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002822 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
2823 dump.append(INDENT4 "touch.touchSize.calibration: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002824 break;
2825 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002826 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002827 }
2828
Jeff Brownc6d282b2010-10-14 21:42:15 -07002829 // Tool Size
2830 switch (mCalibration.toolSizeCalibration) {
2831 case Calibration::TOOL_SIZE_CALIBRATION_NONE:
2832 dump.append(INDENT4 "touch.toolSize.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002833 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002834 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
2835 dump.append(INDENT4 "touch.toolSize.calibration: geometric\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002836 break;
Jeff Brownc6d282b2010-10-14 21:42:15 -07002837 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
2838 dump.append(INDENT4 "touch.toolSize.calibration: linear\n");
2839 break;
2840 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
2841 dump.append(INDENT4 "touch.toolSize.calibration: area\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002842 break;
2843 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002844 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002845 }
2846
Jeff Brownc6d282b2010-10-14 21:42:15 -07002847 if (mCalibration.haveToolSizeLinearScale) {
2848 dump.appendFormat(INDENT4 "touch.toolSize.linearScale: %0.3f\n",
2849 mCalibration.toolSizeLinearScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002850 }
2851
Jeff Brownc6d282b2010-10-14 21:42:15 -07002852 if (mCalibration.haveToolSizeLinearBias) {
2853 dump.appendFormat(INDENT4 "touch.toolSize.linearBias: %0.3f\n",
2854 mCalibration.toolSizeLinearBias);
Jeff Brown8d608662010-08-30 03:02:23 -07002855 }
2856
Jeff Brownc6d282b2010-10-14 21:42:15 -07002857 if (mCalibration.haveToolSizeAreaScale) {
2858 dump.appendFormat(INDENT4 "touch.toolSize.areaScale: %0.3f\n",
2859 mCalibration.toolSizeAreaScale);
2860 }
2861
2862 if (mCalibration.haveToolSizeAreaBias) {
2863 dump.appendFormat(INDENT4 "touch.toolSize.areaBias: %0.3f\n",
2864 mCalibration.toolSizeAreaBias);
2865 }
2866
2867 if (mCalibration.haveToolSizeIsSummed) {
Jeff Brown1f245102010-11-18 20:53:46 -08002868 dump.appendFormat(INDENT4 "touch.toolSize.isSummed: %s\n",
Jeff Brown47e6b1b2010-11-29 17:37:49 -08002869 toString(mCalibration.toolSizeIsSummed));
Jeff Brown8d608662010-08-30 03:02:23 -07002870 }
2871
2872 // Pressure
2873 switch (mCalibration.pressureCalibration) {
2874 case Calibration::PRESSURE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002875 dump.append(INDENT4 "touch.pressure.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002876 break;
2877 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002878 dump.append(INDENT4 "touch.pressure.calibration: physical\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002879 break;
2880 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002881 dump.append(INDENT4 "touch.pressure.calibration: amplitude\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002882 break;
2883 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002884 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002885 }
2886
2887 switch (mCalibration.pressureSource) {
2888 case Calibration::PRESSURE_SOURCE_PRESSURE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002889 dump.append(INDENT4 "touch.pressure.source: pressure\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002890 break;
2891 case Calibration::PRESSURE_SOURCE_TOUCH:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002892 dump.append(INDENT4 "touch.pressure.source: touch\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002893 break;
2894 case Calibration::PRESSURE_SOURCE_DEFAULT:
2895 break;
2896 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002897 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002898 }
2899
2900 if (mCalibration.havePressureScale) {
Jeff Brownef3d7e82010-09-30 14:33:04 -07002901 dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n",
2902 mCalibration.pressureScale);
Jeff Brown8d608662010-08-30 03:02:23 -07002903 }
2904
2905 // Size
2906 switch (mCalibration.sizeCalibration) {
2907 case Calibration::SIZE_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002908 dump.append(INDENT4 "touch.size.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002909 break;
2910 case Calibration::SIZE_CALIBRATION_NORMALIZED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002911 dump.append(INDENT4 "touch.size.calibration: normalized\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002912 break;
2913 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002914 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002915 }
2916
2917 // Orientation
2918 switch (mCalibration.orientationCalibration) {
2919 case Calibration::ORIENTATION_CALIBRATION_NONE:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002920 dump.append(INDENT4 "touch.orientation.calibration: none\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002921 break;
2922 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Jeff Brownef3d7e82010-09-30 14:33:04 -07002923 dump.append(INDENT4 "touch.orientation.calibration: interpolated\n");
Jeff Brown8d608662010-08-30 03:02:23 -07002924 break;
Jeff Brown517bb4c2011-01-14 19:09:23 -08002925 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
2926 dump.append(INDENT4 "touch.orientation.calibration: vector\n");
2927 break;
Jeff Brown8d608662010-08-30 03:02:23 -07002928 default:
Jeff Brownb6110c22011-04-01 16:15:13 -07002929 LOG_ASSERT(false);
Jeff Brown8d608662010-08-30 03:02:23 -07002930 }
Jeff Brown80fd47c2011-05-24 01:07:44 -07002931
2932 // Distance
2933 switch (mCalibration.distanceCalibration) {
2934 case Calibration::DISTANCE_CALIBRATION_NONE:
2935 dump.append(INDENT4 "touch.distance.calibration: none\n");
2936 break;
2937 case Calibration::DISTANCE_CALIBRATION_SCALED:
2938 dump.append(INDENT4 "touch.distance.calibration: scaled\n");
2939 break;
2940 default:
2941 LOG_ASSERT(false);
2942 }
2943
2944 if (mCalibration.haveDistanceScale) {
2945 dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n",
2946 mCalibration.distanceScale);
2947 }
Jeff Brown8d608662010-08-30 03:02:23 -07002948}
2949
Jeff Brown6d0fec22010-07-23 21:28:06 -07002950void TouchInputMapper::reset() {
2951 // Synthesize touch up event if touch is currently down.
2952 // This will also take care of finishing virtual key processing if needed.
2953 if (mLastTouch.pointerCount != 0) {
2954 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
2955 mCurrentTouch.clear();
2956 syncTouch(when, true);
2957 }
2958
Jeff Brown6328cdc2010-07-29 18:18:33 -07002959 { // acquire lock
2960 AutoMutex _l(mLock);
2961 initializeLocked();
Jeff Brown2352b972011-04-12 22:39:53 -07002962
2963 if (mPointerController != NULL
2964 && mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
Jeff Brown474dcb52011-06-14 20:22:50 -07002965 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
Jeff Brown2352b972011-04-12 22:39:53 -07002966 mPointerController->clearSpots();
2967 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07002968 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07002969
Jeff Brown6328cdc2010-07-29 18:18:33 -07002970 InputMapper::reset();
Jeff Brown6d0fec22010-07-23 21:28:06 -07002971}
2972
2973void TouchInputMapper::syncTouch(nsecs_t when, bool havePointerIds) {
Jeff Brownaa3855d2011-03-17 01:34:19 -07002974#if DEBUG_RAW_EVENTS
2975 if (!havePointerIds) {
2976 LOGD("syncTouch: pointerCount=%d, no pointer ids", mCurrentTouch.pointerCount);
2977 } else {
2978 LOGD("syncTouch: pointerCount=%d, up=0x%08x, down=0x%08x, move=0x%08x, "
2979 "last=0x%08x, current=0x%08x", mCurrentTouch.pointerCount,
2980 mLastTouch.idBits.value & ~mCurrentTouch.idBits.value,
2981 mCurrentTouch.idBits.value & ~mLastTouch.idBits.value,
2982 mLastTouch.idBits.value & mCurrentTouch.idBits.value,
2983 mLastTouch.idBits.value, mCurrentTouch.idBits.value);
2984 }
2985#endif
2986
Jeff Brown6328cdc2010-07-29 18:18:33 -07002987 // Preprocess pointer data.
Jeff Brown6d0fec22010-07-23 21:28:06 -07002988 if (mParameters.useBadTouchFilter) {
2989 if (applyBadTouchFilter()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002990 havePointerIds = false;
2991 }
2992 }
2993
Jeff Brown6d0fec22010-07-23 21:28:06 -07002994 if (mParameters.useJumpyTouchFilter) {
2995 if (applyJumpyTouchFilter()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07002996 havePointerIds = false;
2997 }
2998 }
2999
Jeff Brownaa3855d2011-03-17 01:34:19 -07003000 if (!havePointerIds) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07003001 calculatePointerIds();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003002 }
3003
Jeff Brown6d0fec22010-07-23 21:28:06 -07003004 TouchData temp;
3005 TouchData* savedTouch;
3006 if (mParameters.useAveragingTouchFilter) {
3007 temp.copyFrom(mCurrentTouch);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003008 savedTouch = & temp;
3009
Jeff Brown6d0fec22010-07-23 21:28:06 -07003010 applyAveragingTouchFilter();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003011 } else {
Jeff Brown6d0fec22010-07-23 21:28:06 -07003012 savedTouch = & mCurrentTouch;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003013 }
3014
Jeff Brown56194eb2011-03-02 19:23:13 -08003015 uint32_t policyFlags = 0;
Jeff Brown05dc66a2011-03-02 14:41:58 -08003016 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
Jeff Brownefd32662011-03-08 15:13:06 -08003017 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3018 // If this is a touch screen, hide the pointer on an initial down.
3019 getContext()->fadePointer();
3020 }
Jeff Brown56194eb2011-03-02 19:23:13 -08003021
3022 // Initial downs on external touch devices should wake the device.
3023 // We don't do this for internal touch screens to prevent them from waking
3024 // up in your pocket.
3025 // TODO: Use the input device configuration to control this behavior more finely.
3026 if (getDevice()->isExternal()) {
3027 policyFlags |= POLICY_FLAG_WAKE_DROPPED;
3028 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08003029 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003030
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003031 // Synthesize key down from buttons if needed.
3032 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mTouchSource,
3033 policyFlags, mLastTouch.buttonState, mCurrentTouch.buttonState);
3034
3035 // Send motion events.
Jeff Brown79ac9692011-04-19 21:20:10 -07003036 TouchResult touchResult;
3037 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount == 0
3038 && mLastTouch.buttonState == mCurrentTouch.buttonState) {
3039 // Drop spurious syncs.
3040 touchResult = DROP_STROKE;
3041 } else {
3042 // Process touches and virtual keys.
3043 touchResult = consumeOffScreenTouches(when, policyFlags);
3044 if (touchResult == DISPATCH_TOUCH) {
3045 suppressSwipeOntoVirtualKeys(when);
Jeff Brown474dcb52011-06-14 20:22:50 -07003046 if (mPointerController != NULL && mConfig.pointerGesturesEnabled) {
Jeff Brown79ac9692011-04-19 21:20:10 -07003047 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
3048 }
3049 dispatchTouches(when, policyFlags);
Jeff Brownace13b12011-03-09 17:39:48 -08003050 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003051 }
3052
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003053 // Synthesize key up from buttons if needed.
3054 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mTouchSource,
3055 policyFlags, mLastTouch.buttonState, mCurrentTouch.buttonState);
3056
Jeff Brown6328cdc2010-07-29 18:18:33 -07003057 // Copy current touch to last touch in preparation for the next cycle.
Jeff Brownace13b12011-03-09 17:39:48 -08003058 // Keep the button state so we can track edge-triggered button state changes.
Jeff Brown6d0fec22010-07-23 21:28:06 -07003059 if (touchResult == DROP_STROKE) {
3060 mLastTouch.clear();
Jeff Brownace13b12011-03-09 17:39:48 -08003061 mLastTouch.buttonState = savedTouch->buttonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07003062 } else {
3063 mLastTouch.copyFrom(*savedTouch);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003064 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003065}
3066
Jeff Brown79ac9692011-04-19 21:20:10 -07003067void TouchInputMapper::timeoutExpired(nsecs_t when) {
3068 if (mPointerController != NULL) {
3069 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
3070 }
3071}
3072
Jeff Brown6d0fec22010-07-23 21:28:06 -07003073TouchInputMapper::TouchResult TouchInputMapper::consumeOffScreenTouches(
3074 nsecs_t when, uint32_t policyFlags) {
3075 int32_t keyEventAction, keyEventFlags;
3076 int32_t keyCode, scanCode, downTime;
3077 TouchResult touchResult;
Jeff Brown349703e2010-06-22 01:27:15 -07003078
Jeff Brown6328cdc2010-07-29 18:18:33 -07003079 { // acquire lock
3080 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07003081
Jeff Brown6328cdc2010-07-29 18:18:33 -07003082 // Update surface size and orientation, including virtual key positions.
3083 if (! configureSurfaceLocked()) {
3084 return DROP_STROKE;
3085 }
3086
3087 // Check for virtual key press.
3088 if (mLocked.currentVirtualKey.down) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07003089 if (mCurrentTouch.pointerCount == 0) {
3090 // Pointer went up while virtual key was down.
Jeff Brown6328cdc2010-07-29 18:18:33 -07003091 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07003092#if DEBUG_VIRTUAL_KEYS
3093 LOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07003094 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07003095#endif
3096 keyEventAction = AKEY_EVENT_ACTION_UP;
3097 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3098 touchResult = SKIP_TOUCH;
3099 goto DispatchVirtualKey;
3100 }
3101
3102 if (mCurrentTouch.pointerCount == 1) {
3103 int32_t x = mCurrentTouch.pointers[0].x;
3104 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003105 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
3106 if (virtualKey && virtualKey->keyCode == mLocked.currentVirtualKey.keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07003107 // Pointer is still within the space of the virtual key.
3108 return SKIP_TOUCH;
3109 }
3110 }
3111
3112 // Pointer left virtual key area or another pointer also went down.
3113 // Send key cancellation and drop the stroke so subsequent motions will be
3114 // considered fresh downs. This is useful when the user swipes away from the
3115 // virtual key area into the main display surface.
Jeff Brown6328cdc2010-07-29 18:18:33 -07003116 mLocked.currentVirtualKey.down = false;
Jeff Brown6d0fec22010-07-23 21:28:06 -07003117#if DEBUG_VIRTUAL_KEYS
3118 LOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07003119 mLocked.currentVirtualKey.keyCode, mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07003120#endif
3121 keyEventAction = AKEY_EVENT_ACTION_UP;
3122 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
3123 | AKEY_EVENT_FLAG_CANCELED;
Jeff Brownc3db8582010-10-20 15:33:38 -07003124
3125 // Check whether the pointer moved inside the display area where we should
3126 // start a new stroke.
3127 int32_t x = mCurrentTouch.pointers[0].x;
3128 int32_t y = mCurrentTouch.pointers[0].y;
3129 if (isPointInsideSurfaceLocked(x, y)) {
3130 mLastTouch.clear();
3131 touchResult = DISPATCH_TOUCH;
3132 } else {
3133 touchResult = DROP_STROKE;
3134 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07003135 } else {
3136 if (mCurrentTouch.pointerCount >= 1 && mLastTouch.pointerCount == 0) {
3137 // Pointer just went down. Handle off-screen touches, if needed.
3138 int32_t x = mCurrentTouch.pointers[0].x;
3139 int32_t y = mCurrentTouch.pointers[0].y;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003140 if (! isPointInsideSurfaceLocked(x, y)) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07003141 // If exactly one pointer went down, check for virtual key hit.
3142 // Otherwise we will drop the entire stroke.
3143 if (mCurrentTouch.pointerCount == 1) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07003144 const VirtualKey* virtualKey = findVirtualKeyHitLocked(x, y);
Jeff Brown6d0fec22010-07-23 21:28:06 -07003145 if (virtualKey) {
Jeff Brownfe508922011-01-18 15:10:10 -08003146 if (mContext->shouldDropVirtualKey(when, getDevice(),
3147 virtualKey->keyCode, virtualKey->scanCode)) {
3148 return DROP_STROKE;
3149 }
3150
Jeff Brown6328cdc2010-07-29 18:18:33 -07003151 mLocked.currentVirtualKey.down = true;
3152 mLocked.currentVirtualKey.downTime = when;
3153 mLocked.currentVirtualKey.keyCode = virtualKey->keyCode;
3154 mLocked.currentVirtualKey.scanCode = virtualKey->scanCode;
Jeff Brown6d0fec22010-07-23 21:28:06 -07003155#if DEBUG_VIRTUAL_KEYS
3156 LOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
Jeff Brownc3db8582010-10-20 15:33:38 -07003157 mLocked.currentVirtualKey.keyCode,
3158 mLocked.currentVirtualKey.scanCode);
Jeff Brown6d0fec22010-07-23 21:28:06 -07003159#endif
3160 keyEventAction = AKEY_EVENT_ACTION_DOWN;
3161 keyEventFlags = AKEY_EVENT_FLAG_FROM_SYSTEM
3162 | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;
3163 touchResult = SKIP_TOUCH;
3164 goto DispatchVirtualKey;
3165 }
3166 }
3167 return DROP_STROKE;
3168 }
3169 }
3170 return DISPATCH_TOUCH;
3171 }
3172
3173 DispatchVirtualKey:
3174 // Collect remaining state needed to dispatch virtual key.
Jeff Brown6328cdc2010-07-29 18:18:33 -07003175 keyCode = mLocked.currentVirtualKey.keyCode;
3176 scanCode = mLocked.currentVirtualKey.scanCode;
3177 downTime = mLocked.currentVirtualKey.downTime;
3178 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07003179
3180 // Dispatch virtual key.
3181 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brown0eaf3932010-10-01 14:55:30 -07003182 policyFlags |= POLICY_FLAG_VIRTUAL;
Jeff Brownb6997262010-10-08 22:31:17 -07003183 getDispatcher()->notifyKey(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags,
3184 keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
3185 return touchResult;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003186}
3187
Jeff Brownefd32662011-03-08 15:13:06 -08003188void TouchInputMapper::suppressSwipeOntoVirtualKeys(nsecs_t when) {
Jeff Brownfe508922011-01-18 15:10:10 -08003189 // Disable all virtual key touches that happen within a short time interval of the
3190 // most recent touch. The idea is to filter out stray virtual key presses when
3191 // interacting with the touch screen.
3192 //
3193 // Problems we're trying to solve:
3194 //
3195 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
3196 // virtual key area that is implemented by a separate touch panel and accidentally
3197 // triggers a virtual key.
3198 //
3199 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
3200 // area and accidentally triggers a virtual key. This often happens when virtual keys
3201 // are layed out below the screen near to where the on screen keyboard's space bar
3202 // is displayed.
Jeff Brown474dcb52011-06-14 20:22:50 -07003203 if (mConfig.virtualKeyQuietTime > 0 && mCurrentTouch.pointerCount != 0) {
3204 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Jeff Brownfe508922011-01-18 15:10:10 -08003205 }
3206}
3207
Jeff Brown6d0fec22010-07-23 21:28:06 -07003208void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
3209 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
3210 uint32_t lastPointerCount = mLastTouch.pointerCount;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003211 if (currentPointerCount == 0 && lastPointerCount == 0) {
3212 return; // nothing to do!
3213 }
3214
Jeff Brownace13b12011-03-09 17:39:48 -08003215 // Update current touch coordinates.
3216 int32_t edgeFlags;
3217 float xPrecision, yPrecision;
3218 prepareTouches(&edgeFlags, &xPrecision, &yPrecision);
3219
3220 // Dispatch motions.
Jeff Brown6d0fec22010-07-23 21:28:06 -07003221 BitSet32 currentIdBits = mCurrentTouch.idBits;
3222 BitSet32 lastIdBits = mLastTouch.idBits;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003223 int32_t metaState = getContext()->getGlobalMetaState();
3224 int32_t buttonState = mCurrentTouch.buttonState;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003225
3226 if (currentIdBits == lastIdBits) {
3227 // No pointer id changes so this is a move event.
3228 // The dispatcher takes care of batching moves so we don't have to deal with that here.
Jeff Brownace13b12011-03-09 17:39:48 -08003229 dispatchMotion(when, policyFlags, mTouchSource,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003230 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState,
3231 AMOTION_EVENT_EDGE_FLAG_NONE,
3232 mCurrentTouchProperties, mCurrentTouchCoords,
3233 mCurrentTouch.idToIndex, currentIdBits, -1,
Jeff Brownace13b12011-03-09 17:39:48 -08003234 xPrecision, yPrecision, mDownTime);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003235 } else {
Jeff Brownc3db8582010-10-20 15:33:38 -07003236 // There may be pointers going up and pointers going down and pointers moving
3237 // all at the same time.
Jeff Brownace13b12011-03-09 17:39:48 -08003238 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
3239 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07003240 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
Jeff Brownace13b12011-03-09 17:39:48 -08003241 BitSet32 dispatchedIdBits(lastIdBits.value);
Jeff Brownc3db8582010-10-20 15:33:38 -07003242
Jeff Brownace13b12011-03-09 17:39:48 -08003243 // Update last coordinates of pointers that have moved so that we observe the new
3244 // pointer positions at the same time as other pointers that have just gone up.
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003245 bool moveNeeded = updateMovedPointers(
3246 mCurrentTouchProperties, mCurrentTouchCoords, mCurrentTouch.idToIndex,
3247 mLastTouchProperties, mLastTouchCoords, mLastTouch.idToIndex,
Jeff Brownace13b12011-03-09 17:39:48 -08003248 moveIdBits);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003249 if (buttonState != mLastTouch.buttonState) {
3250 moveNeeded = true;
3251 }
Jeff Brownc3db8582010-10-20 15:33:38 -07003252
Jeff Brownace13b12011-03-09 17:39:48 -08003253 // Dispatch pointer up events.
Jeff Brownc3db8582010-10-20 15:33:38 -07003254 while (!upIdBits.isEmpty()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003255 uint32_t upId = upIdBits.firstMarkedBit();
3256 upIdBits.clearBit(upId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003257
Jeff Brownace13b12011-03-09 17:39:48 -08003258 dispatchMotion(when, policyFlags, mTouchSource,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003259 AMOTION_EVENT_ACTION_POINTER_UP, 0, metaState, buttonState, 0,
3260 mLastTouchProperties, mLastTouchCoords,
3261 mLastTouch.idToIndex, dispatchedIdBits, upId,
Jeff Brownace13b12011-03-09 17:39:48 -08003262 xPrecision, yPrecision, mDownTime);
3263 dispatchedIdBits.clearBit(upId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003264 }
3265
Jeff Brownc3db8582010-10-20 15:33:38 -07003266 // Dispatch move events if any of the remaining pointers moved from their old locations.
3267 // Although applications receive new locations as part of individual pointer up
3268 // events, they do not generally handle them except when presented in a move event.
3269 if (moveNeeded) {
Jeff Brownb6110c22011-04-01 16:15:13 -07003270 LOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Jeff Brownace13b12011-03-09 17:39:48 -08003271 dispatchMotion(when, policyFlags, mTouchSource,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003272 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, 0,
3273 mCurrentTouchProperties, mCurrentTouchCoords,
3274 mCurrentTouch.idToIndex, dispatchedIdBits, -1,
Jeff Brownace13b12011-03-09 17:39:48 -08003275 xPrecision, yPrecision, mDownTime);
Jeff Brownc3db8582010-10-20 15:33:38 -07003276 }
3277
3278 // Dispatch pointer down events using the new pointer locations.
3279 while (!downIdBits.isEmpty()) {
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003280 uint32_t downId = downIdBits.firstMarkedBit();
3281 downIdBits.clearBit(downId);
Jeff Brownace13b12011-03-09 17:39:48 -08003282 dispatchedIdBits.markBit(downId);
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003283
Jeff Brownace13b12011-03-09 17:39:48 -08003284 if (dispatchedIdBits.count() == 1) {
3285 // First pointer is going down. Set down time.
Jeff Brown6d0fec22010-07-23 21:28:06 -07003286 mDownTime = when;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003287 } else {
Jeff Brownace13b12011-03-09 17:39:48 -08003288 // Only send edge flags with first pointer down.
3289 edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003290 }
3291
Jeff Brownace13b12011-03-09 17:39:48 -08003292 dispatchMotion(when, policyFlags, mTouchSource,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003293 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, edgeFlags,
3294 mCurrentTouchProperties, mCurrentTouchCoords,
3295 mCurrentTouch.idToIndex, dispatchedIdBits, downId,
Jeff Brownace13b12011-03-09 17:39:48 -08003296 xPrecision, yPrecision, mDownTime);
3297 }
3298 }
3299
3300 // Update state for next time.
3301 for (uint32_t i = 0; i < currentPointerCount; i++) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003302 mLastTouchProperties[i].copyFrom(mCurrentTouchProperties[i]);
Jeff Brownace13b12011-03-09 17:39:48 -08003303 mLastTouchCoords[i].copyFrom(mCurrentTouchCoords[i]);
3304 }
3305}
3306
3307void TouchInputMapper::prepareTouches(int32_t* outEdgeFlags,
3308 float* outXPrecision, float* outYPrecision) {
3309 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
3310 uint32_t lastPointerCount = mLastTouch.pointerCount;
3311
3312 AutoMutex _l(mLock);
3313
3314 // Walk through the the active pointers and map touch screen coordinates (TouchData) into
3315 // display or surface coordinates (PointerCoords) and adjust for display orientation.
3316 for (uint32_t i = 0; i < currentPointerCount; i++) {
3317 const PointerData& in = mCurrentTouch.pointers[i];
3318
3319 // ToolMajor and ToolMinor
3320 float toolMajor, toolMinor;
3321 switch (mCalibration.toolSizeCalibration) {
3322 case Calibration::TOOL_SIZE_CALIBRATION_GEOMETRIC:
3323 toolMajor = in.toolMajor * mLocked.geometricScale;
3324 if (mRawAxes.toolMinor.valid) {
3325 toolMinor = in.toolMinor * mLocked.geometricScale;
3326 } else {
3327 toolMinor = toolMajor;
3328 }
3329 break;
3330 case Calibration::TOOL_SIZE_CALIBRATION_LINEAR:
3331 toolMajor = in.toolMajor != 0
3332 ? in.toolMajor * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias
3333 : 0;
3334 if (mRawAxes.toolMinor.valid) {
3335 toolMinor = in.toolMinor != 0
3336 ? in.toolMinor * mLocked.toolSizeLinearScale
3337 + mLocked.toolSizeLinearBias
3338 : 0;
3339 } else {
3340 toolMinor = toolMajor;
3341 }
3342 break;
3343 case Calibration::TOOL_SIZE_CALIBRATION_AREA:
3344 if (in.toolMajor != 0) {
3345 float diameter = sqrtf(in.toolMajor
3346 * mLocked.toolSizeAreaScale + mLocked.toolSizeAreaBias);
3347 toolMajor = diameter * mLocked.toolSizeLinearScale + mLocked.toolSizeLinearBias;
3348 } else {
3349 toolMajor = 0;
3350 }
3351 toolMinor = toolMajor;
3352 break;
3353 default:
3354 toolMajor = 0;
3355 toolMinor = 0;
3356 break;
3357 }
3358
3359 if (mCalibration.haveToolSizeIsSummed && mCalibration.toolSizeIsSummed) {
3360 toolMajor /= currentPointerCount;
3361 toolMinor /= currentPointerCount;
3362 }
3363
3364 // Pressure
3365 float rawPressure;
3366 switch (mCalibration.pressureSource) {
3367 case Calibration::PRESSURE_SOURCE_PRESSURE:
3368 rawPressure = in.pressure;
3369 break;
3370 case Calibration::PRESSURE_SOURCE_TOUCH:
3371 rawPressure = in.touchMajor;
3372 break;
3373 default:
3374 rawPressure = 0;
3375 }
3376
3377 float pressure;
3378 switch (mCalibration.pressureCalibration) {
3379 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
3380 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
3381 pressure = rawPressure * mLocked.pressureScale;
3382 break;
3383 default:
3384 pressure = 1;
3385 break;
3386 }
3387
3388 // TouchMajor and TouchMinor
3389 float touchMajor, touchMinor;
3390 switch (mCalibration.touchSizeCalibration) {
3391 case Calibration::TOUCH_SIZE_CALIBRATION_GEOMETRIC:
3392 touchMajor = in.touchMajor * mLocked.geometricScale;
3393 if (mRawAxes.touchMinor.valid) {
3394 touchMinor = in.touchMinor * mLocked.geometricScale;
3395 } else {
3396 touchMinor = touchMajor;
3397 }
3398 break;
3399 case Calibration::TOUCH_SIZE_CALIBRATION_PRESSURE:
3400 touchMajor = toolMajor * pressure;
3401 touchMinor = toolMinor * pressure;
3402 break;
3403 default:
3404 touchMajor = 0;
3405 touchMinor = 0;
3406 break;
3407 }
3408
3409 if (touchMajor > toolMajor) {
3410 touchMajor = toolMajor;
3411 }
3412 if (touchMinor > toolMinor) {
3413 touchMinor = toolMinor;
3414 }
3415
3416 // Size
3417 float size;
3418 switch (mCalibration.sizeCalibration) {
3419 case Calibration::SIZE_CALIBRATION_NORMALIZED: {
3420 float rawSize = mRawAxes.toolMinor.valid
3421 ? avg(in.toolMajor, in.toolMinor)
3422 : in.toolMajor;
3423 size = rawSize * mLocked.sizeScale;
3424 break;
3425 }
3426 default:
3427 size = 0;
3428 break;
3429 }
3430
3431 // Orientation
3432 float orientation;
3433 switch (mCalibration.orientationCalibration) {
3434 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
3435 orientation = in.orientation * mLocked.orientationScale;
3436 break;
3437 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
3438 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
3439 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
3440 if (c1 != 0 || c2 != 0) {
3441 orientation = atan2f(c1, c2) * 0.5f;
Jeff Brown2352b972011-04-12 22:39:53 -07003442 float scale = 1.0f + hypotf(c1, c2) / 16.0f;
Jeff Brownace13b12011-03-09 17:39:48 -08003443 touchMajor *= scale;
3444 touchMinor /= scale;
3445 toolMajor *= scale;
3446 toolMinor /= scale;
3447 } else {
3448 orientation = 0;
3449 }
3450 break;
3451 }
3452 default:
3453 orientation = 0;
3454 }
3455
Jeff Brown80fd47c2011-05-24 01:07:44 -07003456 // Distance
3457 float distance;
3458 switch (mCalibration.distanceCalibration) {
3459 case Calibration::DISTANCE_CALIBRATION_SCALED:
3460 distance = in.distance * mLocked.distanceScale;
3461 break;
3462 default:
3463 distance = 0;
3464 }
3465
Jeff Brownace13b12011-03-09 17:39:48 -08003466 // X and Y
3467 // Adjust coords for surface orientation.
3468 float x, y;
3469 switch (mLocked.surfaceOrientation) {
3470 case DISPLAY_ORIENTATION_90:
3471 x = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3472 y = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3473 orientation -= M_PI_2;
3474 if (orientation < - M_PI_2) {
3475 orientation += M_PI;
3476 }
3477 break;
3478 case DISPLAY_ORIENTATION_180:
3479 x = float(mRawAxes.x.maxValue - in.x) * mLocked.xScale;
3480 y = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3481 break;
3482 case DISPLAY_ORIENTATION_270:
3483 x = float(mRawAxes.y.maxValue - in.y) * mLocked.yScale;
3484 y = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3485 orientation += M_PI_2;
3486 if (orientation > M_PI_2) {
3487 orientation -= M_PI;
3488 }
3489 break;
3490 default:
3491 x = float(in.x - mRawAxes.x.minValue) * mLocked.xScale;
3492 y = float(in.y - mRawAxes.y.minValue) * mLocked.yScale;
3493 break;
3494 }
3495
3496 // Write output coords.
3497 PointerCoords& out = mCurrentTouchCoords[i];
3498 out.clear();
3499 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3500 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3501 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
3502 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
3503 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
3504 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
3505 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
3506 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
3507 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
Jeff Brown80fd47c2011-05-24 01:07:44 -07003508 if (distance != 0) {
3509 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
3510 }
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003511
3512 // Write output properties.
3513 PointerProperties& properties = mCurrentTouchProperties[i];
3514 properties.clear();
3515 properties.id = mCurrentTouch.pointers[i].id;
3516 properties.toolType = getTouchToolType(mCurrentTouch.pointers[i].isStylus);
Jeff Brownace13b12011-03-09 17:39:48 -08003517 }
3518
3519 // Check edge flags by looking only at the first pointer since the flags are
3520 // global to the event.
3521 *outEdgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3522 if (lastPointerCount == 0 && currentPointerCount > 0) {
3523 const PointerData& in = mCurrentTouch.pointers[0];
3524
3525 if (in.x <= mRawAxes.x.minValue) {
3526 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_LEFT,
3527 mLocked.surfaceOrientation);
3528 } else if (in.x >= mRawAxes.x.maxValue) {
3529 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_RIGHT,
3530 mLocked.surfaceOrientation);
3531 }
3532 if (in.y <= mRawAxes.y.minValue) {
3533 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_TOP,
3534 mLocked.surfaceOrientation);
3535 } else if (in.y >= mRawAxes.y.maxValue) {
3536 *outEdgeFlags |= rotateEdgeFlag(AMOTION_EVENT_EDGE_FLAG_BOTTOM,
3537 mLocked.surfaceOrientation);
3538 }
3539 }
3540
3541 *outXPrecision = mLocked.orientedXPrecision;
3542 *outYPrecision = mLocked.orientedYPrecision;
3543}
3544
Jeff Brown79ac9692011-04-19 21:20:10 -07003545void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
3546 bool isTimeout) {
Jeff Brownace13b12011-03-09 17:39:48 -08003547 // Update current gesture coordinates.
3548 bool cancelPreviousGesture, finishPreviousGesture;
Jeff Brown79ac9692011-04-19 21:20:10 -07003549 bool sendEvents = preparePointerGestures(when,
3550 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
3551 if (!sendEvents) {
3552 return;
3553 }
Jeff Brown19c97d462011-06-01 12:33:19 -07003554 if (finishPreviousGesture) {
3555 cancelPreviousGesture = false;
3556 }
Jeff Brownace13b12011-03-09 17:39:48 -08003557
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07003558 // Update the pointer presentation and spots.
3559 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3560 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
3561 if (finishPreviousGesture || cancelPreviousGesture) {
3562 mPointerController->clearSpots();
3563 }
Jeff Browncb5ffcf2011-06-06 20:03:18 -07003564 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
3565 mPointerGesture.currentGestureIdToIndex,
3566 mPointerGesture.currentGestureIdBits);
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07003567 } else {
3568 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
3569 }
Jeff Brown214eaf42011-05-26 19:17:02 -07003570
Jeff Brown538881e2011-05-25 18:23:38 -07003571 // Show or hide the pointer if needed.
3572 switch (mPointerGesture.currentGestureMode) {
3573 case PointerGesture::NEUTRAL:
3574 case PointerGesture::QUIET:
3575 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS
3576 && (mPointerGesture.lastGestureMode == PointerGesture::SWIPE
3577 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)) {
3578 // Remind the user of where the pointer is after finishing a gesture with spots.
3579 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
3580 }
3581 break;
3582 case PointerGesture::TAP:
3583 case PointerGesture::TAP_DRAG:
3584 case PointerGesture::BUTTON_CLICK_OR_DRAG:
3585 case PointerGesture::HOVER:
3586 case PointerGesture::PRESS:
3587 // Unfade the pointer when the current gesture manipulates the
3588 // area directly under the pointer.
3589 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
3590 break;
3591 case PointerGesture::SWIPE:
3592 case PointerGesture::FREEFORM:
3593 // Fade the pointer when the current gesture manipulates a different
3594 // area and there are spots to guide the user experience.
3595 if (mParameters.gestureMode == Parameters::GESTURE_MODE_SPOTS) {
3596 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
3597 } else {
3598 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
3599 }
3600 break;
Jeff Brown2352b972011-04-12 22:39:53 -07003601 }
3602
Jeff Brownace13b12011-03-09 17:39:48 -08003603 // Send events!
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003604 int32_t metaState = getContext()->getGlobalMetaState();
3605 int32_t buttonState = mCurrentTouch.buttonState;
Jeff Brownace13b12011-03-09 17:39:48 -08003606
3607 // Update last coordinates of pointers that have moved so that we observe the new
3608 // pointer positions at the same time as other pointers that have just gone up.
Jeff Brown79ac9692011-04-19 21:20:10 -07003609 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
3610 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
3611 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
Jeff Brown2352b972011-04-12 22:39:53 -07003612 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
Jeff Brownace13b12011-03-09 17:39:48 -08003613 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
3614 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
3615 bool moveNeeded = false;
3616 if (down && !cancelPreviousGesture && !finishPreviousGesture
Jeff Brown2352b972011-04-12 22:39:53 -07003617 && !mPointerGesture.lastGestureIdBits.isEmpty()
3618 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
Jeff Brownace13b12011-03-09 17:39:48 -08003619 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
3620 & mPointerGesture.lastGestureIdBits.value);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003621 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
Jeff Brownace13b12011-03-09 17:39:48 -08003622 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003623 mPointerGesture.lastGestureProperties,
Jeff Brownace13b12011-03-09 17:39:48 -08003624 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3625 movedGestureIdBits);
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003626 if (buttonState != mLastTouch.buttonState) {
3627 moveNeeded = true;
3628 }
Jeff Brownace13b12011-03-09 17:39:48 -08003629 }
3630
3631 // Send motion events for all pointers that went up or were canceled.
3632 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
3633 if (!dispatchedGestureIdBits.isEmpty()) {
3634 if (cancelPreviousGesture) {
3635 dispatchMotion(when, policyFlags, mPointerSource,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003636 AMOTION_EVENT_ACTION_CANCEL, 0, metaState, buttonState,
3637 AMOTION_EVENT_EDGE_FLAG_NONE,
3638 mPointerGesture.lastGestureProperties,
Jeff Brownace13b12011-03-09 17:39:48 -08003639 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3640 dispatchedGestureIdBits, -1,
3641 0, 0, mPointerGesture.downTime);
3642
3643 dispatchedGestureIdBits.clear();
3644 } else {
3645 BitSet32 upGestureIdBits;
3646 if (finishPreviousGesture) {
3647 upGestureIdBits = dispatchedGestureIdBits;
3648 } else {
3649 upGestureIdBits.value = dispatchedGestureIdBits.value
3650 & ~mPointerGesture.currentGestureIdBits.value;
3651 }
3652 while (!upGestureIdBits.isEmpty()) {
3653 uint32_t id = upGestureIdBits.firstMarkedBit();
3654 upGestureIdBits.clearBit(id);
3655
3656 dispatchMotion(when, policyFlags, mPointerSource,
3657 AMOTION_EVENT_ACTION_POINTER_UP, 0,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003658 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
3659 mPointerGesture.lastGestureProperties,
Jeff Brownace13b12011-03-09 17:39:48 -08003660 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
3661 dispatchedGestureIdBits, id,
3662 0, 0, mPointerGesture.downTime);
3663
3664 dispatchedGestureIdBits.clearBit(id);
3665 }
3666 }
3667 }
3668
3669 // Send motion events for all pointers that moved.
3670 if (moveNeeded) {
3671 dispatchMotion(when, policyFlags, mPointerSource,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003672 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
3673 mPointerGesture.currentGestureProperties,
Jeff Brownace13b12011-03-09 17:39:48 -08003674 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3675 dispatchedGestureIdBits, -1,
3676 0, 0, mPointerGesture.downTime);
3677 }
3678
3679 // Send motion events for all pointers that went down.
3680 if (down) {
3681 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
3682 & ~dispatchedGestureIdBits.value);
3683 while (!downGestureIdBits.isEmpty()) {
3684 uint32_t id = downGestureIdBits.firstMarkedBit();
3685 downGestureIdBits.clearBit(id);
3686 dispatchedGestureIdBits.markBit(id);
3687
3688 int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
3689 if (dispatchedGestureIdBits.count() == 1) {
3690 // First pointer is going down. Calculate edge flags and set down time.
3691 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3692 const PointerCoords& downCoords = mPointerGesture.currentGestureCoords[index];
3693 edgeFlags = calculateEdgeFlagsUsingPointerBounds(mPointerController,
3694 downCoords.getAxisValue(AMOTION_EVENT_AXIS_X),
3695 downCoords.getAxisValue(AMOTION_EVENT_AXIS_Y));
3696 mPointerGesture.downTime = when;
3697 }
3698
3699 dispatchMotion(when, policyFlags, mPointerSource,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003700 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, metaState, buttonState, edgeFlags,
3701 mPointerGesture.currentGestureProperties,
Jeff Brownace13b12011-03-09 17:39:48 -08003702 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3703 dispatchedGestureIdBits, id,
3704 0, 0, mPointerGesture.downTime);
3705 }
3706 }
3707
Jeff Brownace13b12011-03-09 17:39:48 -08003708 // Send motion events for hover.
3709 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
3710 dispatchMotion(when, policyFlags, mPointerSource,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003711 AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
3712 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
3713 mPointerGesture.currentGestureProperties,
Jeff Brownace13b12011-03-09 17:39:48 -08003714 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
3715 mPointerGesture.currentGestureIdBits, -1,
3716 0, 0, mPointerGesture.downTime);
Jeff Brown81346812011-06-28 20:08:48 -07003717 } else if (dispatchedGestureIdBits.isEmpty()
3718 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
3719 // Synthesize a hover move event after all pointers go up to indicate that
3720 // the pointer is hovering again even if the user is not currently touching
3721 // the touch pad. This ensures that a view will receive a fresh hover enter
3722 // event after a tap.
3723 float x, y;
3724 mPointerController->getPosition(&x, &y);
3725
3726 PointerProperties pointerProperties;
3727 pointerProperties.clear();
3728 pointerProperties.id = 0;
3729 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
3730
3731 PointerCoords pointerCoords;
3732 pointerCoords.clear();
3733 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3734 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3735
3736 getDispatcher()->notifyMotion(when, getDeviceId(), mPointerSource, policyFlags,
3737 AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
3738 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
3739 1, &pointerProperties, &pointerCoords, 0, 0, mPointerGesture.downTime);
Jeff Brownace13b12011-03-09 17:39:48 -08003740 }
3741
3742 // Update state.
3743 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
3744 if (!down) {
Jeff Brownace13b12011-03-09 17:39:48 -08003745 mPointerGesture.lastGestureIdBits.clear();
3746 } else {
Jeff Brownace13b12011-03-09 17:39:48 -08003747 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
3748 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
3749 uint32_t id = idBits.firstMarkedBit();
3750 idBits.clearBit(id);
3751 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003752 mPointerGesture.lastGestureProperties[index].copyFrom(
3753 mPointerGesture.currentGestureProperties[index]);
Jeff Brownace13b12011-03-09 17:39:48 -08003754 mPointerGesture.lastGestureCoords[index].copyFrom(
3755 mPointerGesture.currentGestureCoords[index]);
3756 mPointerGesture.lastGestureIdToIndex[id] = index;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003757 }
3758 }
3759}
3760
Jeff Brown79ac9692011-04-19 21:20:10 -07003761bool TouchInputMapper::preparePointerGestures(nsecs_t when,
3762 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
Jeff Brownace13b12011-03-09 17:39:48 -08003763 *outCancelPreviousGesture = false;
3764 *outFinishPreviousGesture = false;
Jeff Brown6328cdc2010-07-29 18:18:33 -07003765
Jeff Brownace13b12011-03-09 17:39:48 -08003766 AutoMutex _l(mLock);
Jeff Brown6328cdc2010-07-29 18:18:33 -07003767
Jeff Brown79ac9692011-04-19 21:20:10 -07003768 // Handle TAP timeout.
3769 if (isTimeout) {
3770#if DEBUG_GESTURES
3771 LOGD("Gestures: Processing timeout");
3772#endif
3773
3774 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
Jeff Brown474dcb52011-06-14 20:22:50 -07003775 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Jeff Brown79ac9692011-04-19 21:20:10 -07003776 // The tap/drag timeout has not yet expired.
Jeff Brown214eaf42011-05-26 19:17:02 -07003777 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
Jeff Brown474dcb52011-06-14 20:22:50 -07003778 + mConfig.pointerGestureTapDragInterval);
Jeff Brown79ac9692011-04-19 21:20:10 -07003779 } else {
3780 // The tap is finished.
3781#if DEBUG_GESTURES
3782 LOGD("Gestures: TAP finished");
3783#endif
3784 *outFinishPreviousGesture = true;
3785
3786 mPointerGesture.activeGestureId = -1;
3787 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
3788 mPointerGesture.currentGestureIdBits.clear();
3789
Jeff Brown19c97d462011-06-01 12:33:19 -07003790 mPointerGesture.pointerVelocityControl.reset();
Jeff Brown79ac9692011-04-19 21:20:10 -07003791 return true;
3792 }
3793 }
3794
3795 // We did not handle this timeout.
3796 return false;
3797 }
3798
Jeff Brownace13b12011-03-09 17:39:48 -08003799 // Update the velocity tracker.
3800 {
3801 VelocityTracker::Position positions[MAX_POINTERS];
3802 uint32_t count = 0;
3803 for (BitSet32 idBits(mCurrentTouch.idBits); !idBits.isEmpty(); count++) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07003804 uint32_t id = idBits.firstMarkedBit();
3805 idBits.clearBit(id);
Jeff Brownace13b12011-03-09 17:39:48 -08003806 uint32_t index = mCurrentTouch.idToIndex[id];
3807 positions[count].x = mCurrentTouch.pointers[index].x
3808 * mLocked.pointerGestureXMovementScale;
3809 positions[count].y = mCurrentTouch.pointers[index].y
3810 * mLocked.pointerGestureYMovementScale;
3811 }
3812 mPointerGesture.velocityTracker.addMovement(when, mCurrentTouch.idBits, positions);
3813 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003814
Jeff Brownace13b12011-03-09 17:39:48 -08003815 // Pick a new active touch id if needed.
3816 // Choose an arbitrary pointer that just went down, if there is one.
3817 // Otherwise choose an arbitrary remaining pointer.
3818 // This guarantees we always have an active touch id when there is at least one pointer.
Jeff Brown2352b972011-04-12 22:39:53 -07003819 // We keep the same active touch id for as long as possible.
3820 bool activeTouchChanged = false;
3821 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
3822 int32_t activeTouchId = lastActiveTouchId;
3823 if (activeTouchId < 0) {
3824 if (!mCurrentTouch.idBits.isEmpty()) {
3825 activeTouchChanged = true;
3826 activeTouchId = mPointerGesture.activeTouchId = mCurrentTouch.idBits.firstMarkedBit();
3827 mPointerGesture.firstTouchTime = when;
Jeff Brownace13b12011-03-09 17:39:48 -08003828 }
Jeff Brown2352b972011-04-12 22:39:53 -07003829 } else if (!mCurrentTouch.idBits.hasBit(activeTouchId)) {
3830 activeTouchChanged = true;
3831 if (!mCurrentTouch.idBits.isEmpty()) {
3832 activeTouchId = mPointerGesture.activeTouchId = mCurrentTouch.idBits.firstMarkedBit();
3833 } else {
3834 activeTouchId = mPointerGesture.activeTouchId = -1;
Jeff Brownace13b12011-03-09 17:39:48 -08003835 }
3836 }
3837
3838 // Determine whether we are in quiet time.
Jeff Brown2352b972011-04-12 22:39:53 -07003839 bool isQuietTime = false;
3840 if (activeTouchId < 0) {
3841 mPointerGesture.resetQuietTime();
3842 } else {
Jeff Brown474dcb52011-06-14 20:22:50 -07003843 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
Jeff Brown2352b972011-04-12 22:39:53 -07003844 if (!isQuietTime) {
3845 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
3846 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
3847 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
3848 && mCurrentTouch.pointerCount < 2) {
3849 // Enter quiet time when exiting swipe or freeform state.
3850 // This is to prevent accidentally entering the hover state and flinging the
3851 // pointer when finishing a swipe and there is still one pointer left onscreen.
3852 isQuietTime = true;
Jeff Brown79ac9692011-04-19 21:20:10 -07003853 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
Jeff Brown2352b972011-04-12 22:39:53 -07003854 && mCurrentTouch.pointerCount >= 2
3855 && !isPointerDown(mCurrentTouch.buttonState)) {
3856 // Enter quiet time when releasing the button and there are still two or more
3857 // fingers down. This may indicate that one finger was used to press the button
3858 // but it has not gone up yet.
3859 isQuietTime = true;
3860 }
3861 if (isQuietTime) {
3862 mPointerGesture.quietTime = when;
3863 }
Jeff Brownace13b12011-03-09 17:39:48 -08003864 }
3865 }
3866
3867 // Switch states based on button and pointer state.
3868 if (isQuietTime) {
3869 // Case 1: Quiet time. (QUIET)
3870#if DEBUG_GESTURES
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07003871 LOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
Jeff Brown474dcb52011-06-14 20:22:50 -07003872 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
Jeff Brownace13b12011-03-09 17:39:48 -08003873#endif
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07003874 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
3875 *outFinishPreviousGesture = true;
3876 }
Jeff Brownace13b12011-03-09 17:39:48 -08003877
3878 mPointerGesture.activeGestureId = -1;
3879 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
Jeff Brownace13b12011-03-09 17:39:48 -08003880 mPointerGesture.currentGestureIdBits.clear();
Jeff Brown2352b972011-04-12 22:39:53 -07003881
Jeff Brown19c97d462011-06-01 12:33:19 -07003882 mPointerGesture.pointerVelocityControl.reset();
Jeff Brownace13b12011-03-09 17:39:48 -08003883 } else if (isPointerDown(mCurrentTouch.buttonState)) {
Jeff Brown79ac9692011-04-19 21:20:10 -07003884 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
Jeff Brownace13b12011-03-09 17:39:48 -08003885 // The pointer follows the active touch point.
3886 // Emit DOWN, MOVE, UP events at the pointer location.
3887 //
3888 // Only the active touch matters; other fingers are ignored. This policy helps
3889 // to handle the case where the user places a second finger on the touch pad
3890 // to apply the necessary force to depress an integrated button below the surface.
3891 // We don't want the second finger to be delivered to applications.
3892 //
3893 // For this to work well, we need to make sure to track the pointer that is really
3894 // active. If the user first puts one finger down to click then adds another
3895 // finger to drag then the active pointer should switch to the finger that is
3896 // being dragged.
3897#if DEBUG_GESTURES
Jeff Brown79ac9692011-04-19 21:20:10 -07003898 LOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
Jeff Brownace13b12011-03-09 17:39:48 -08003899 "currentTouchPointerCount=%d", activeTouchId, mCurrentTouch.pointerCount);
3900#endif
3901 // Reset state when just starting.
Jeff Brown79ac9692011-04-19 21:20:10 -07003902 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
Jeff Brownace13b12011-03-09 17:39:48 -08003903 *outFinishPreviousGesture = true;
3904 mPointerGesture.activeGestureId = 0;
3905 }
3906
3907 // Switch pointers if needed.
3908 // Find the fastest pointer and follow it.
Jeff Brown19c97d462011-06-01 12:33:19 -07003909 if (activeTouchId >= 0 && mCurrentTouch.pointerCount > 1) {
3910 int32_t bestId = -1;
Jeff Brown474dcb52011-06-14 20:22:50 -07003911 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Jeff Brown19c97d462011-06-01 12:33:19 -07003912 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
3913 uint32_t id = mCurrentTouch.pointers[i].id;
3914 float vx, vy;
3915 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
3916 float speed = hypotf(vx, vy);
3917 if (speed > bestSpeed) {
3918 bestId = id;
3919 bestSpeed = speed;
Jeff Brownace13b12011-03-09 17:39:48 -08003920 }
Jeff Brown8d608662010-08-30 03:02:23 -07003921 }
Jeff Brown19c97d462011-06-01 12:33:19 -07003922 }
3923 if (bestId >= 0 && bestId != activeTouchId) {
3924 mPointerGesture.activeTouchId = activeTouchId = bestId;
3925 activeTouchChanged = true;
Jeff Brownace13b12011-03-09 17:39:48 -08003926#if DEBUG_GESTURES
Jeff Brown19c97d462011-06-01 12:33:19 -07003927 LOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
3928 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
Jeff Brownace13b12011-03-09 17:39:48 -08003929#endif
Jeff Brown6328cdc2010-07-29 18:18:33 -07003930 }
Jeff Brown19c97d462011-06-01 12:33:19 -07003931 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003932
Jeff Brown19c97d462011-06-01 12:33:19 -07003933 if (activeTouchId >= 0 && mLastTouch.idBits.hasBit(activeTouchId)) {
3934 const PointerData& currentPointer =
3935 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
3936 const PointerData& lastPointer =
3937 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
3938 float deltaX = (currentPointer.x - lastPointer.x)
3939 * mLocked.pointerGestureXMovementScale;
3940 float deltaY = (currentPointer.y - lastPointer.y)
3941 * mLocked.pointerGestureYMovementScale;
Jeff Brown2352b972011-04-12 22:39:53 -07003942
Jeff Brown19c97d462011-06-01 12:33:19 -07003943 mPointerGesture.pointerVelocityControl.move(when, &deltaX, &deltaY);
3944
3945 // Move the pointer using a relative motion.
3946 // When using spots, the click will occur at the position of the anchor
3947 // spot and all other spots will move there.
3948 mPointerController->move(deltaX, deltaY);
3949 } else {
3950 mPointerGesture.pointerVelocityControl.reset();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07003951 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07003952
Jeff Brownace13b12011-03-09 17:39:48 -08003953 float x, y;
3954 mPointerController->getPosition(&x, &y);
Jeff Brown91c69ab2011-02-14 17:03:18 -08003955
Jeff Brown79ac9692011-04-19 21:20:10 -07003956 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
Jeff Brownace13b12011-03-09 17:39:48 -08003957 mPointerGesture.currentGestureIdBits.clear();
3958 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3959 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07003960 mPointerGesture.currentGestureProperties[0].clear();
3961 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3962 mPointerGesture.currentGestureProperties[0].toolType =
3963 AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
Jeff Brownace13b12011-03-09 17:39:48 -08003964 mPointerGesture.currentGestureCoords[0].clear();
3965 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3966 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3967 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3968 } else if (mCurrentTouch.pointerCount == 0) {
3969 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07003970 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
3971 *outFinishPreviousGesture = true;
3972 }
Jeff Brownace13b12011-03-09 17:39:48 -08003973
Jeff Brown79ac9692011-04-19 21:20:10 -07003974 // Watch for taps coming out of HOVER or TAP_DRAG mode.
Jeff Brown214eaf42011-05-26 19:17:02 -07003975 // Checking for taps after TAP_DRAG allows us to detect double-taps.
Jeff Brownace13b12011-03-09 17:39:48 -08003976 bool tapped = false;
Jeff Brown79ac9692011-04-19 21:20:10 -07003977 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
3978 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
Jeff Brown2352b972011-04-12 22:39:53 -07003979 && mLastTouch.pointerCount == 1) {
Jeff Brown474dcb52011-06-14 20:22:50 -07003980 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Jeff Brownace13b12011-03-09 17:39:48 -08003981 float x, y;
3982 mPointerController->getPosition(&x, &y);
Jeff Brown474dcb52011-06-14 20:22:50 -07003983 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
3984 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Jeff Brownace13b12011-03-09 17:39:48 -08003985#if DEBUG_GESTURES
3986 LOGD("Gestures: TAP");
3987#endif
Jeff Brown79ac9692011-04-19 21:20:10 -07003988
3989 mPointerGesture.tapUpTime = when;
Jeff Brown214eaf42011-05-26 19:17:02 -07003990 getContext()->requestTimeoutAtTime(when
Jeff Brown474dcb52011-06-14 20:22:50 -07003991 + mConfig.pointerGestureTapDragInterval);
Jeff Brown79ac9692011-04-19 21:20:10 -07003992
Jeff Brownace13b12011-03-09 17:39:48 -08003993 mPointerGesture.activeGestureId = 0;
3994 mPointerGesture.currentGestureMode = PointerGesture::TAP;
Jeff Brownace13b12011-03-09 17:39:48 -08003995 mPointerGesture.currentGestureIdBits.clear();
3996 mPointerGesture.currentGestureIdBits.markBit(
3997 mPointerGesture.activeGestureId);
3998 mPointerGesture.currentGestureIdToIndex[
3999 mPointerGesture.activeGestureId] = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004000 mPointerGesture.currentGestureProperties[0].clear();
4001 mPointerGesture.currentGestureProperties[0].id =
4002 mPointerGesture.activeGestureId;
4003 mPointerGesture.currentGestureProperties[0].toolType =
4004 AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
Jeff Brownace13b12011-03-09 17:39:48 -08004005 mPointerGesture.currentGestureCoords[0].clear();
4006 mPointerGesture.currentGestureCoords[0].setAxisValue(
Jeff Brown2352b972011-04-12 22:39:53 -07004007 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
Jeff Brownace13b12011-03-09 17:39:48 -08004008 mPointerGesture.currentGestureCoords[0].setAxisValue(
Jeff Brown2352b972011-04-12 22:39:53 -07004009 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
Jeff Brownace13b12011-03-09 17:39:48 -08004010 mPointerGesture.currentGestureCoords[0].setAxisValue(
4011 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown2352b972011-04-12 22:39:53 -07004012
Jeff Brownace13b12011-03-09 17:39:48 -08004013 tapped = true;
4014 } else {
4015#if DEBUG_GESTURES
4016 LOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
Jeff Brown2352b972011-04-12 22:39:53 -07004017 x - mPointerGesture.tapX,
4018 y - mPointerGesture.tapY);
Jeff Brownace13b12011-03-09 17:39:48 -08004019#endif
4020 }
4021 } else {
4022#if DEBUG_GESTURES
Jeff Brown79ac9692011-04-19 21:20:10 -07004023 LOGD("Gestures: Not a TAP, %0.3fms since down",
4024 (when - mPointerGesture.tapDownTime) * 0.000001f);
Jeff Brownace13b12011-03-09 17:39:48 -08004025#endif
Jeff Brown6328cdc2010-07-29 18:18:33 -07004026 }
Jeff Brownace13b12011-03-09 17:39:48 -08004027 }
Jeff Brown2352b972011-04-12 22:39:53 -07004028
Jeff Brown19c97d462011-06-01 12:33:19 -07004029 mPointerGesture.pointerVelocityControl.reset();
4030
Jeff Brownace13b12011-03-09 17:39:48 -08004031 if (!tapped) {
4032#if DEBUG_GESTURES
4033 LOGD("Gestures: NEUTRAL");
4034#endif
4035 mPointerGesture.activeGestureId = -1;
4036 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
Jeff Brownace13b12011-03-09 17:39:48 -08004037 mPointerGesture.currentGestureIdBits.clear();
4038 }
4039 } else if (mCurrentTouch.pointerCount == 1) {
Jeff Brown79ac9692011-04-19 21:20:10 -07004040 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
Jeff Brownace13b12011-03-09 17:39:48 -08004041 // The pointer follows the active touch point.
Jeff Brown79ac9692011-04-19 21:20:10 -07004042 // When in HOVER, emit HOVER_MOVE events at the pointer location.
4043 // When in TAP_DRAG, emit MOVE events at the pointer location.
Jeff Brownb6110c22011-04-01 16:15:13 -07004044 LOG_ASSERT(activeTouchId >= 0);
Jeff Brownace13b12011-03-09 17:39:48 -08004045
Jeff Brown79ac9692011-04-19 21:20:10 -07004046 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
4047 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
Jeff Brown474dcb52011-06-14 20:22:50 -07004048 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Jeff Brown79ac9692011-04-19 21:20:10 -07004049 float x, y;
4050 mPointerController->getPosition(&x, &y);
Jeff Brown474dcb52011-06-14 20:22:50 -07004051 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
4052 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Jeff Brown79ac9692011-04-19 21:20:10 -07004053 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
4054 } else {
Jeff Brownace13b12011-03-09 17:39:48 -08004055#if DEBUG_GESTURES
Jeff Brown79ac9692011-04-19 21:20:10 -07004056 LOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
4057 x - mPointerGesture.tapX,
4058 y - mPointerGesture.tapY);
Jeff Brownace13b12011-03-09 17:39:48 -08004059#endif
Jeff Brown79ac9692011-04-19 21:20:10 -07004060 }
4061 } else {
4062#if DEBUG_GESTURES
4063 LOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
4064 (when - mPointerGesture.tapUpTime) * 0.000001f);
4065#endif
4066 }
4067 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
4068 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
4069 }
Jeff Brownace13b12011-03-09 17:39:48 -08004070
4071 if (mLastTouch.idBits.hasBit(activeTouchId)) {
4072 const PointerData& currentPointer =
4073 mCurrentTouch.pointers[mCurrentTouch.idToIndex[activeTouchId]];
4074 const PointerData& lastPointer =
4075 mLastTouch.pointers[mLastTouch.idToIndex[activeTouchId]];
4076 float deltaX = (currentPointer.x - lastPointer.x)
4077 * mLocked.pointerGestureXMovementScale;
4078 float deltaY = (currentPointer.y - lastPointer.y)
4079 * mLocked.pointerGestureYMovementScale;
Jeff Brown2352b972011-04-12 22:39:53 -07004080
Jeff Brown19c97d462011-06-01 12:33:19 -07004081 mPointerGesture.pointerVelocityControl.move(when, &deltaX, &deltaY);
4082
Jeff Brown2352b972011-04-12 22:39:53 -07004083 // Move the pointer using a relative motion.
Jeff Brown79ac9692011-04-19 21:20:10 -07004084 // When using spots, the hover or drag will occur at the position of the anchor spot.
Jeff Brownace13b12011-03-09 17:39:48 -08004085 mPointerController->move(deltaX, deltaY);
Jeff Brown19c97d462011-06-01 12:33:19 -07004086 } else {
4087 mPointerGesture.pointerVelocityControl.reset();
Jeff Brownace13b12011-03-09 17:39:48 -08004088 }
4089
Jeff Brown79ac9692011-04-19 21:20:10 -07004090 bool down;
4091 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
4092#if DEBUG_GESTURES
4093 LOGD("Gestures: TAP_DRAG");
4094#endif
4095 down = true;
4096 } else {
4097#if DEBUG_GESTURES
4098 LOGD("Gestures: HOVER");
4099#endif
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004100 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
4101 *outFinishPreviousGesture = true;
4102 }
Jeff Brown79ac9692011-04-19 21:20:10 -07004103 mPointerGesture.activeGestureId = 0;
4104 down = false;
4105 }
Jeff Brownace13b12011-03-09 17:39:48 -08004106
4107 float x, y;
4108 mPointerController->getPosition(&x, &y);
4109
Jeff Brownace13b12011-03-09 17:39:48 -08004110 mPointerGesture.currentGestureIdBits.clear();
4111 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
4112 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004113 mPointerGesture.currentGestureProperties[0].clear();
4114 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
4115 mPointerGesture.currentGestureProperties[0].toolType =
4116 AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
Jeff Brownace13b12011-03-09 17:39:48 -08004117 mPointerGesture.currentGestureCoords[0].clear();
4118 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4119 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jeff Brown79ac9692011-04-19 21:20:10 -07004120 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
4121 down ? 1.0f : 0.0f);
4122
Jeff Brownace13b12011-03-09 17:39:48 -08004123 if (mLastTouch.pointerCount == 0 && mCurrentTouch.pointerCount != 0) {
Jeff Brown79ac9692011-04-19 21:20:10 -07004124 mPointerGesture.resetTap();
4125 mPointerGesture.tapDownTime = when;
Jeff Brown2352b972011-04-12 22:39:53 -07004126 mPointerGesture.tapX = x;
4127 mPointerGesture.tapY = y;
4128 }
Jeff Brownace13b12011-03-09 17:39:48 -08004129 } else {
Jeff Brown2352b972011-04-12 22:39:53 -07004130 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
4131 // We need to provide feedback for each finger that goes down so we cannot wait
4132 // for the fingers to move before deciding what to do.
Jeff Brownace13b12011-03-09 17:39:48 -08004133 //
Jeff Brown2352b972011-04-12 22:39:53 -07004134 // The ambiguous case is deciding what to do when there are two fingers down but they
4135 // have not moved enough to determine whether they are part of a drag or part of a
4136 // freeform gesture, or just a press or long-press at the pointer location.
4137 //
4138 // When there are two fingers we start with the PRESS hypothesis and we generate a
4139 // down at the pointer location.
4140 //
4141 // When the two fingers move enough or when additional fingers are added, we make
4142 // a decision to transition into SWIPE or FREEFORM mode accordingly.
Jeff Brownb6110c22011-04-01 16:15:13 -07004143 LOG_ASSERT(activeTouchId >= 0);
Jeff Brownace13b12011-03-09 17:39:48 -08004144
Jeff Brown214eaf42011-05-26 19:17:02 -07004145 bool settled = when >= mPointerGesture.firstTouchTime
Jeff Brown474dcb52011-06-14 20:22:50 -07004146 + mConfig.pointerGestureMultitouchSettleInterval;
Jeff Brown2352b972011-04-12 22:39:53 -07004147 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
Jeff Brownace13b12011-03-09 17:39:48 -08004148 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
4149 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
Jeff Brownace13b12011-03-09 17:39:48 -08004150 *outFinishPreviousGesture = true;
Jeff Brown19c97d462011-06-01 12:33:19 -07004151 } else if (!settled && mCurrentTouch.pointerCount > mLastTouch.pointerCount) {
4152 // Additional pointers have gone down but not yet settled.
4153 // Reset the gesture.
4154#if DEBUG_GESTURES
4155 LOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004156 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
Jeff Brown474dcb52011-06-14 20:22:50 -07004157 + mConfig.pointerGestureMultitouchSettleInterval - when)
Jeff Brown19c97d462011-06-01 12:33:19 -07004158 * 0.000001f);
4159#endif
4160 *outCancelPreviousGesture = true;
4161 } else {
4162 // Continue previous gesture.
4163 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
4164 }
4165
4166 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Jeff Brown2352b972011-04-12 22:39:53 -07004167 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
4168 mPointerGesture.activeGestureId = 0;
Jeff Brown538881e2011-05-25 18:23:38 -07004169 mPointerGesture.referenceIdBits.clear();
Jeff Brown19c97d462011-06-01 12:33:19 -07004170 mPointerGesture.pointerVelocityControl.reset();
Jeff Brownace13b12011-03-09 17:39:48 -08004171
Jeff Browncb5ffcf2011-06-06 20:03:18 -07004172 // Use the centroid and pointer location as the reference points for the gesture.
Jeff Brown2352b972011-04-12 22:39:53 -07004173#if DEBUG_GESTURES
Jeff Browncb5ffcf2011-06-06 20:03:18 -07004174 LOGD("Gestures: Using centroid as reference for MULTITOUCH, "
4175 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
Jeff Brown474dcb52011-06-14 20:22:50 -07004176 + mConfig.pointerGestureMultitouchSettleInterval - when)
Jeff Browncb5ffcf2011-06-06 20:03:18 -07004177 * 0.000001f);
Jeff Brown2352b972011-04-12 22:39:53 -07004178#endif
Jeff Browncb5ffcf2011-06-06 20:03:18 -07004179 mCurrentTouch.getCentroid(&mPointerGesture.referenceTouchX,
4180 &mPointerGesture.referenceTouchY);
4181 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
4182 &mPointerGesture.referenceGestureY);
Jeff Brown2352b972011-04-12 22:39:53 -07004183 }
Jeff Brownace13b12011-03-09 17:39:48 -08004184
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004185 // Clear the reference deltas for fingers not yet included in the reference calculation.
4186 for (BitSet32 idBits(mCurrentTouch.idBits.value & ~mPointerGesture.referenceIdBits.value);
4187 !idBits.isEmpty(); ) {
4188 uint32_t id = idBits.firstMarkedBit();
4189 idBits.clearBit(id);
4190
4191 mPointerGesture.referenceDeltas[id].dx = 0;
4192 mPointerGesture.referenceDeltas[id].dy = 0;
4193 }
4194 mPointerGesture.referenceIdBits = mCurrentTouch.idBits;
4195
4196 // Add delta for all fingers and calculate a common movement delta.
4197 float commonDeltaX = 0, commonDeltaY = 0;
4198 BitSet32 commonIdBits(mLastTouch.idBits.value & mCurrentTouch.idBits.value);
4199 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
4200 bool first = (idBits == commonIdBits);
4201 uint32_t id = idBits.firstMarkedBit();
4202 idBits.clearBit(id);
4203
4204 const PointerData& cpd = mCurrentTouch.pointers[mCurrentTouch.idToIndex[id]];
4205 const PointerData& lpd = mLastTouch.pointers[mLastTouch.idToIndex[id]];
4206 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
4207 delta.dx += cpd.x - lpd.x;
4208 delta.dy += cpd.y - lpd.y;
4209
4210 if (first) {
4211 commonDeltaX = delta.dx;
4212 commonDeltaY = delta.dy;
Jeff Brown2352b972011-04-12 22:39:53 -07004213 } else {
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004214 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
4215 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
4216 }
4217 }
Jeff Brownace13b12011-03-09 17:39:48 -08004218
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004219 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
4220 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
4221 float dist[MAX_POINTER_ID + 1];
4222 int32_t distOverThreshold = 0;
4223 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
4224 uint32_t id = idBits.firstMarkedBit();
4225 idBits.clearBit(id);
Jeff Brownace13b12011-03-09 17:39:48 -08004226
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004227 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
4228 dist[id] = hypotf(delta.dx * mLocked.pointerGestureXZoomScale,
4229 delta.dy * mLocked.pointerGestureYZoomScale);
Jeff Brown474dcb52011-06-14 20:22:50 -07004230 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004231 distOverThreshold += 1;
4232 }
4233 }
4234
4235 // Only transition when at least two pointers have moved further than
4236 // the minimum distance threshold.
4237 if (distOverThreshold >= 2) {
4238 float d;
4239 if (mCurrentTouch.pointerCount > 2) {
4240 // There are more than two pointers, switch to FREEFORM.
Jeff Brown2352b972011-04-12 22:39:53 -07004241#if DEBUG_GESTURES
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004242 LOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
4243 mCurrentTouch.pointerCount);
Jeff Brown2352b972011-04-12 22:39:53 -07004244#endif
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004245 *outCancelPreviousGesture = true;
4246 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
4247 } else if (((d = distance(
4248 mCurrentTouch.pointers[0].x, mCurrentTouch.pointers[0].y,
4249 mCurrentTouch.pointers[1].x, mCurrentTouch.pointers[1].y))
4250 > mLocked.pointerGestureMaxSwipeWidth)) {
4251 // There are two pointers but they are too far apart for a SWIPE,
4252 // switch to FREEFORM.
Jeff Brown2352b972011-04-12 22:39:53 -07004253#if DEBUG_GESTURES
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004254 LOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
4255 d, mLocked.pointerGestureMaxSwipeWidth);
Jeff Brown2352b972011-04-12 22:39:53 -07004256#endif
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004257 *outCancelPreviousGesture = true;
4258 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
4259 } else {
4260 // There are two pointers. Wait for both pointers to start moving
4261 // before deciding whether this is a SWIPE or FREEFORM gesture.
4262 uint32_t id1 = mCurrentTouch.pointers[0].id;
4263 uint32_t id2 = mCurrentTouch.pointers[1].id;
4264 float dist1 = dist[id1];
4265 float dist2 = dist[id2];
Jeff Brown474dcb52011-06-14 20:22:50 -07004266 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
4267 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004268 // Calculate the dot product of the displacement vectors.
4269 // When the vectors are oriented in approximately the same direction,
4270 // the angle betweeen them is near zero and the cosine of the angle
4271 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
4272 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
4273 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
Jeff Brown6674d9b2011-06-07 16:50:14 -07004274 float dx1 = delta1.dx * mLocked.pointerGestureXZoomScale;
4275 float dy1 = delta1.dy * mLocked.pointerGestureYZoomScale;
4276 float dx2 = delta2.dx * mLocked.pointerGestureXZoomScale;
4277 float dy2 = delta2.dy * mLocked.pointerGestureYZoomScale;
4278 float dot = dx1 * dx2 + dy1 * dy2;
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004279 float cosine = dot / (dist1 * dist2); // denominator always > 0
Jeff Brown474dcb52011-06-14 20:22:50 -07004280 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004281 // Pointers are moving in the same direction. Switch to SWIPE.
4282#if DEBUG_GESTURES
4283 LOGD("Gestures: PRESS transitioned to SWIPE, "
4284 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
4285 "cosine %0.3f >= %0.3f",
Jeff Brown474dcb52011-06-14 20:22:50 -07004286 dist1, mConfig.pointerGestureMultitouchMinDistance,
4287 dist2, mConfig.pointerGestureMultitouchMinDistance,
4288 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004289#endif
4290 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
4291 } else {
4292 // Pointers are moving in different directions. Switch to FREEFORM.
4293#if DEBUG_GESTURES
4294 LOGD("Gestures: PRESS transitioned to FREEFORM, "
4295 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
4296 "cosine %0.3f < %0.3f",
Jeff Brown474dcb52011-06-14 20:22:50 -07004297 dist1, mConfig.pointerGestureMultitouchMinDistance,
4298 dist2, mConfig.pointerGestureMultitouchMinDistance,
4299 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004300#endif
4301 *outCancelPreviousGesture = true;
4302 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
4303 }
Jeff Brownace13b12011-03-09 17:39:48 -08004304 }
4305 }
Jeff Brownace13b12011-03-09 17:39:48 -08004306 }
4307 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
Jeff Brown2352b972011-04-12 22:39:53 -07004308 // Switch from SWIPE to FREEFORM if additional pointers go down.
4309 // Cancel previous gesture.
4310 if (mCurrentTouch.pointerCount > 2) {
4311#if DEBUG_GESTURES
4312 LOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
4313 mCurrentTouch.pointerCount);
4314#endif
Jeff Brownace13b12011-03-09 17:39:48 -08004315 *outCancelPreviousGesture = true;
4316 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
Jeff Brown6328cdc2010-07-29 18:18:33 -07004317 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004318 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004319
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004320 // Move the reference points based on the overall group motion of the fingers
4321 // except in PRESS mode while waiting for a transition to occur.
4322 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
4323 && (commonDeltaX || commonDeltaY)) {
4324 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
Jeff Brown2352b972011-04-12 22:39:53 -07004325 uint32_t id = idBits.firstMarkedBit();
4326 idBits.clearBit(id);
4327
Jeff Brown538881e2011-05-25 18:23:38 -07004328 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004329 delta.dx = 0;
4330 delta.dy = 0;
Jeff Brown2352b972011-04-12 22:39:53 -07004331 }
4332
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004333 mPointerGesture.referenceTouchX += commonDeltaX;
4334 mPointerGesture.referenceTouchY += commonDeltaY;
Jeff Brown538881e2011-05-25 18:23:38 -07004335
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004336 commonDeltaX *= mLocked.pointerGestureXMovementScale;
4337 commonDeltaY *= mLocked.pointerGestureYMovementScale;
4338 mPointerGesture.pointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
Jeff Brown538881e2011-05-25 18:23:38 -07004339
Jeff Brownbb3fcba0c2011-06-06 19:23:05 -07004340 mPointerGesture.referenceGestureX += commonDeltaX;
4341 mPointerGesture.referenceGestureY += commonDeltaY;
Jeff Brown2352b972011-04-12 22:39:53 -07004342 }
4343
4344 // Report gestures.
4345 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
4346 // PRESS mode.
Jeff Brownace13b12011-03-09 17:39:48 -08004347#if DEBUG_GESTURES
Jeff Brown2352b972011-04-12 22:39:53 -07004348 LOGD("Gestures: PRESS activeTouchId=%d,"
Jeff Brownace13b12011-03-09 17:39:48 -08004349 "activeGestureId=%d, currentTouchPointerCount=%d",
Jeff Brown2352b972011-04-12 22:39:53 -07004350 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
Jeff Brownace13b12011-03-09 17:39:48 -08004351#endif
Jeff Brownb6110c22011-04-01 16:15:13 -07004352 LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
Jeff Brownace13b12011-03-09 17:39:48 -08004353
Jeff Brownace13b12011-03-09 17:39:48 -08004354 mPointerGesture.currentGestureIdBits.clear();
4355 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
4356 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004357 mPointerGesture.currentGestureProperties[0].clear();
4358 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
4359 mPointerGesture.currentGestureProperties[0].toolType =
4360 AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
Jeff Brownace13b12011-03-09 17:39:48 -08004361 mPointerGesture.currentGestureCoords[0].clear();
Jeff Brown2352b972011-04-12 22:39:53 -07004362 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4363 mPointerGesture.referenceGestureX);
4364 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
4365 mPointerGesture.referenceGestureY);
Jeff Brownace13b12011-03-09 17:39:48 -08004366 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brown2352b972011-04-12 22:39:53 -07004367 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
4368 // SWIPE mode.
4369#if DEBUG_GESTURES
4370 LOGD("Gestures: SWIPE activeTouchId=%d,"
4371 "activeGestureId=%d, currentTouchPointerCount=%d",
4372 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
4373#endif
4374 LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
4375
4376 mPointerGesture.currentGestureIdBits.clear();
4377 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
4378 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004379 mPointerGesture.currentGestureProperties[0].clear();
4380 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
4381 mPointerGesture.currentGestureProperties[0].toolType =
4382 AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
Jeff Brown2352b972011-04-12 22:39:53 -07004383 mPointerGesture.currentGestureCoords[0].clear();
4384 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
4385 mPointerGesture.referenceGestureX);
4386 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
4387 mPointerGesture.referenceGestureY);
4388 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Jeff Brownace13b12011-03-09 17:39:48 -08004389 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
4390 // FREEFORM mode.
4391#if DEBUG_GESTURES
4392 LOGD("Gestures: FREEFORM activeTouchId=%d,"
4393 "activeGestureId=%d, currentTouchPointerCount=%d",
Jeff Brown2352b972011-04-12 22:39:53 -07004394 activeTouchId, mPointerGesture.activeGestureId, mCurrentTouch.pointerCount);
Jeff Brownace13b12011-03-09 17:39:48 -08004395#endif
Jeff Brownb6110c22011-04-01 16:15:13 -07004396 LOG_ASSERT(mPointerGesture.activeGestureId >= 0);
Jeff Brownace13b12011-03-09 17:39:48 -08004397
Jeff Brownace13b12011-03-09 17:39:48 -08004398 mPointerGesture.currentGestureIdBits.clear();
4399
4400 BitSet32 mappedTouchIdBits;
4401 BitSet32 usedGestureIdBits;
4402 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
4403 // Initially, assign the active gesture id to the active touch point
4404 // if there is one. No other touch id bits are mapped yet.
4405 if (!*outCancelPreviousGesture) {
4406 mappedTouchIdBits.markBit(activeTouchId);
4407 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
4408 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
4409 mPointerGesture.activeGestureId;
4410 } else {
4411 mPointerGesture.activeGestureId = -1;
4412 }
4413 } else {
4414 // Otherwise, assume we mapped all touches from the previous frame.
4415 // Reuse all mappings that are still applicable.
4416 mappedTouchIdBits.value = mLastTouch.idBits.value & mCurrentTouch.idBits.value;
4417 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
4418
4419 // Check whether we need to choose a new active gesture id because the
4420 // current went went up.
4421 for (BitSet32 upTouchIdBits(mLastTouch.idBits.value & ~mCurrentTouch.idBits.value);
4422 !upTouchIdBits.isEmpty(); ) {
4423 uint32_t upTouchId = upTouchIdBits.firstMarkedBit();
4424 upTouchIdBits.clearBit(upTouchId);
4425 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
4426 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
4427 mPointerGesture.activeGestureId = -1;
4428 break;
4429 }
4430 }
4431 }
4432
4433#if DEBUG_GESTURES
4434 LOGD("Gestures: FREEFORM follow up "
4435 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
4436 "activeGestureId=%d",
4437 mappedTouchIdBits.value, usedGestureIdBits.value,
4438 mPointerGesture.activeGestureId);
4439#endif
4440
Jeff Brown2352b972011-04-12 22:39:53 -07004441 for (uint32_t i = 0; i < mCurrentTouch.pointerCount; i++) {
Jeff Brownace13b12011-03-09 17:39:48 -08004442 uint32_t touchId = mCurrentTouch.pointers[i].id;
4443 uint32_t gestureId;
4444 if (!mappedTouchIdBits.hasBit(touchId)) {
4445 gestureId = usedGestureIdBits.firstUnmarkedBit();
4446 usedGestureIdBits.markBit(gestureId);
4447 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
4448#if DEBUG_GESTURES
4449 LOGD("Gestures: FREEFORM "
4450 "new mapping for touch id %d -> gesture id %d",
4451 touchId, gestureId);
4452#endif
4453 } else {
4454 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
4455#if DEBUG_GESTURES
4456 LOGD("Gestures: FREEFORM "
4457 "existing mapping for touch id %d -> gesture id %d",
4458 touchId, gestureId);
4459#endif
4460 }
4461 mPointerGesture.currentGestureIdBits.markBit(gestureId);
4462 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
4463
Jeff Brown2352b972011-04-12 22:39:53 -07004464 float x = (mCurrentTouch.pointers[i].x - mPointerGesture.referenceTouchX)
4465 * mLocked.pointerGestureXZoomScale + mPointerGesture.referenceGestureX;
4466 float y = (mCurrentTouch.pointers[i].y - mPointerGesture.referenceTouchY)
4467 * mLocked.pointerGestureYZoomScale + mPointerGesture.referenceGestureY;
Jeff Brownace13b12011-03-09 17:39:48 -08004468
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004469 mPointerGesture.currentGestureProperties[i].clear();
4470 mPointerGesture.currentGestureProperties[i].id = gestureId;
4471 mPointerGesture.currentGestureProperties[i].toolType =
4472 AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
Jeff Brownace13b12011-03-09 17:39:48 -08004473 mPointerGesture.currentGestureCoords[i].clear();
4474 mPointerGesture.currentGestureCoords[i].setAxisValue(
4475 AMOTION_EVENT_AXIS_X, x);
4476 mPointerGesture.currentGestureCoords[i].setAxisValue(
4477 AMOTION_EVENT_AXIS_Y, y);
4478 mPointerGesture.currentGestureCoords[i].setAxisValue(
4479 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
4480 }
4481
4482 if (mPointerGesture.activeGestureId < 0) {
4483 mPointerGesture.activeGestureId =
4484 mPointerGesture.currentGestureIdBits.firstMarkedBit();
4485#if DEBUG_GESTURES
4486 LOGD("Gestures: FREEFORM new "
4487 "activeGestureId=%d", mPointerGesture.activeGestureId);
4488#endif
4489 }
Jeff Brown2352b972011-04-12 22:39:53 -07004490 }
Jeff Brownace13b12011-03-09 17:39:48 -08004491 }
4492
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004493 mPointerController->setButtonState(mCurrentTouch.buttonState);
4494
Jeff Brownace13b12011-03-09 17:39:48 -08004495#if DEBUG_GESTURES
4496 LOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
Jeff Brown2352b972011-04-12 22:39:53 -07004497 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
4498 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
Jeff Brownace13b12011-03-09 17:39:48 -08004499 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
Jeff Brown2352b972011-04-12 22:39:53 -07004500 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
4501 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
Jeff Brownace13b12011-03-09 17:39:48 -08004502 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
4503 uint32_t id = idBits.firstMarkedBit();
4504 idBits.clearBit(id);
4505 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004506 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
Jeff Brownace13b12011-03-09 17:39:48 -08004507 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004508 LOGD(" currentGesture[%d]: index=%d, toolType=%d, "
4509 "x=%0.3f, y=%0.3f, pressure=%0.3f",
4510 id, index, properties.toolType,
4511 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Jeff Brownace13b12011-03-09 17:39:48 -08004512 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
4513 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
4514 }
4515 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
4516 uint32_t id = idBits.firstMarkedBit();
4517 idBits.clearBit(id);
4518 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004519 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
Jeff Brownace13b12011-03-09 17:39:48 -08004520 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004521 LOGD(" lastGesture[%d]: index=%d, toolType=%d, "
4522 "x=%0.3f, y=%0.3f, pressure=%0.3f",
4523 id, index, properties.toolType,
4524 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
Jeff Brownace13b12011-03-09 17:39:48 -08004525 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
4526 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
4527 }
4528#endif
Jeff Brown79ac9692011-04-19 21:20:10 -07004529 return true;
Jeff Brownace13b12011-03-09 17:39:48 -08004530}
4531
4532void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004533 int32_t action, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
4534 const PointerProperties* properties, const PointerCoords* coords,
4535 const uint32_t* idToIndex, BitSet32 idBits,
Jeff Brownace13b12011-03-09 17:39:48 -08004536 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) {
4537 PointerCoords pointerCoords[MAX_POINTERS];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004538 PointerProperties pointerProperties[MAX_POINTERS];
Jeff Brownace13b12011-03-09 17:39:48 -08004539 uint32_t pointerCount = 0;
4540 while (!idBits.isEmpty()) {
4541 uint32_t id = idBits.firstMarkedBit();
4542 idBits.clearBit(id);
4543 uint32_t index = idToIndex[id];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004544 pointerProperties[pointerCount].copyFrom(properties[index]);
Jeff Brownace13b12011-03-09 17:39:48 -08004545 pointerCoords[pointerCount].copyFrom(coords[index]);
4546
4547 if (changedId >= 0 && id == uint32_t(changedId)) {
4548 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
4549 }
4550
4551 pointerCount += 1;
4552 }
4553
Jeff Brownb6110c22011-04-01 16:15:13 -07004554 LOG_ASSERT(pointerCount != 0);
Jeff Brownace13b12011-03-09 17:39:48 -08004555
4556 if (changedId >= 0 && pointerCount == 1) {
4557 // Replace initial down and final up action.
4558 // We can compare the action without masking off the changed pointer index
4559 // because we know the index is 0.
4560 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
4561 action = AMOTION_EVENT_ACTION_DOWN;
4562 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
4563 action = AMOTION_EVENT_ACTION_UP;
4564 } else {
4565 // Can't happen.
Jeff Brownb6110c22011-04-01 16:15:13 -07004566 LOG_ASSERT(false);
Jeff Brownace13b12011-03-09 17:39:48 -08004567 }
4568 }
4569
4570 getDispatcher()->notifyMotion(when, getDeviceId(), source, policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004571 action, flags, metaState, buttonState, edgeFlags,
4572 pointerCount, pointerProperties, pointerCoords, xPrecision, yPrecision, downTime);
Jeff Brownace13b12011-03-09 17:39:48 -08004573}
4574
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004575bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
Jeff Brownace13b12011-03-09 17:39:48 -08004576 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004577 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
4578 BitSet32 idBits) const {
Jeff Brownace13b12011-03-09 17:39:48 -08004579 bool changed = false;
4580 while (!idBits.isEmpty()) {
4581 uint32_t id = idBits.firstMarkedBit();
4582 idBits.clearBit(id);
4583
4584 uint32_t inIndex = inIdToIndex[id];
4585 uint32_t outIndex = outIdToIndex[id];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004586
4587 const PointerProperties& curInProperties = inProperties[inIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08004588 const PointerCoords& curInCoords = inCoords[inIndex];
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004589 PointerProperties& curOutProperties = outProperties[outIndex];
Jeff Brownace13b12011-03-09 17:39:48 -08004590 PointerCoords& curOutCoords = outCoords[outIndex];
4591
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004592 if (curInProperties != curOutProperties) {
4593 curOutProperties.copyFrom(curInProperties);
4594 changed = true;
4595 }
4596
Jeff Brownace13b12011-03-09 17:39:48 -08004597 if (curInCoords != curOutCoords) {
4598 curOutCoords.copyFrom(curInCoords);
4599 changed = true;
4600 }
4601 }
4602 return changed;
4603}
4604
4605void TouchInputMapper::fadePointer() {
4606 { // acquire lock
4607 AutoMutex _l(mLock);
4608 if (mPointerController != NULL) {
Jeff Brown538881e2011-05-25 18:23:38 -07004609 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
Jeff Brownace13b12011-03-09 17:39:48 -08004610 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07004611 } // release lock
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07004612}
4613
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07004614int32_t TouchInputMapper::getTouchToolType(bool isStylus) const {
4615 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
4616 return isStylus ? AMOTION_EVENT_TOOL_TYPE_STYLUS : AMOTION_EVENT_TOOL_TYPE_FINGER;
4617 } else {
4618 return isStylus ? AMOTION_EVENT_TOOL_TYPE_INDIRECT_STYLUS
4619 : AMOTION_EVENT_TOOL_TYPE_INDIRECT_FINGER;
4620 }
4621}
4622
Jeff Brown6328cdc2010-07-29 18:18:33 -07004623bool TouchInputMapper::isPointInsideSurfaceLocked(int32_t x, int32_t y) {
Jeff Brown9626b142011-03-03 02:09:54 -08004624 return x >= mRawAxes.x.minValue && x <= mRawAxes.x.maxValue
4625 && y >= mRawAxes.y.minValue && y <= mRawAxes.y.maxValue;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004626}
4627
Jeff Brown6328cdc2010-07-29 18:18:33 -07004628const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHitLocked(
4629 int32_t x, int32_t y) {
4630 size_t numVirtualKeys = mLocked.virtualKeys.size();
4631 for (size_t i = 0; i < numVirtualKeys; i++) {
4632 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07004633
4634#if DEBUG_VIRTUAL_KEYS
4635 LOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
4636 "left=%d, top=%d, right=%d, bottom=%d",
4637 x, y,
4638 virtualKey.keyCode, virtualKey.scanCode,
4639 virtualKey.hitLeft, virtualKey.hitTop,
4640 virtualKey.hitRight, virtualKey.hitBottom);
4641#endif
4642
4643 if (virtualKey.isHit(x, y)) {
4644 return & virtualKey;
4645 }
4646 }
4647
4648 return NULL;
4649}
4650
4651void TouchInputMapper::calculatePointerIds() {
4652 uint32_t currentPointerCount = mCurrentTouch.pointerCount;
4653 uint32_t lastPointerCount = mLastTouch.pointerCount;
4654
4655 if (currentPointerCount == 0) {
4656 // No pointers to assign.
4657 mCurrentTouch.idBits.clear();
4658 } else if (lastPointerCount == 0) {
4659 // All pointers are new.
4660 mCurrentTouch.idBits.clear();
4661 for (uint32_t i = 0; i < currentPointerCount; i++) {
4662 mCurrentTouch.pointers[i].id = i;
4663 mCurrentTouch.idToIndex[i] = i;
4664 mCurrentTouch.idBits.markBit(i);
4665 }
4666 } else if (currentPointerCount == 1 && lastPointerCount == 1) {
4667 // Only one pointer and no change in count so it must have the same id as before.
4668 uint32_t id = mLastTouch.pointers[0].id;
4669 mCurrentTouch.pointers[0].id = id;
4670 mCurrentTouch.idToIndex[id] = 0;
4671 mCurrentTouch.idBits.value = BitSet32::valueForBit(id);
4672 } else {
4673 // General case.
4674 // We build a heap of squared euclidean distances between current and last pointers
4675 // associated with the current and last pointer indices. Then, we find the best
4676 // match (by distance) for each current pointer.
4677 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
4678
4679 uint32_t heapSize = 0;
4680 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
4681 currentPointerIndex++) {
4682 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
4683 lastPointerIndex++) {
4684 int64_t deltaX = mCurrentTouch.pointers[currentPointerIndex].x
4685 - mLastTouch.pointers[lastPointerIndex].x;
4686 int64_t deltaY = mCurrentTouch.pointers[currentPointerIndex].y
4687 - mLastTouch.pointers[lastPointerIndex].y;
4688
4689 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
4690
4691 // Insert new element into the heap (sift up).
4692 heap[heapSize].currentPointerIndex = currentPointerIndex;
4693 heap[heapSize].lastPointerIndex = lastPointerIndex;
4694 heap[heapSize].distance = distance;
4695 heapSize += 1;
4696 }
4697 }
4698
4699 // Heapify
4700 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
4701 startIndex -= 1;
4702 for (uint32_t parentIndex = startIndex; ;) {
4703 uint32_t childIndex = parentIndex * 2 + 1;
4704 if (childIndex >= heapSize) {
4705 break;
4706 }
4707
4708 if (childIndex + 1 < heapSize
4709 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4710 childIndex += 1;
4711 }
4712
4713 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4714 break;
4715 }
4716
4717 swap(heap[parentIndex], heap[childIndex]);
4718 parentIndex = childIndex;
4719 }
4720 }
4721
4722#if DEBUG_POINTER_ASSIGNMENT
4723 LOGD("calculatePointerIds - initial distance min-heap: size=%d", heapSize);
4724 for (size_t i = 0; i < heapSize; i++) {
4725 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4726 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4727 heap[i].distance);
4728 }
4729#endif
4730
4731 // Pull matches out by increasing order of distance.
4732 // To avoid reassigning pointers that have already been matched, the loop keeps track
4733 // of which last and current pointers have been matched using the matchedXXXBits variables.
4734 // It also tracks the used pointer id bits.
4735 BitSet32 matchedLastBits(0);
4736 BitSet32 matchedCurrentBits(0);
4737 BitSet32 usedIdBits(0);
4738 bool first = true;
4739 for (uint32_t i = min(currentPointerCount, lastPointerCount); i > 0; i--) {
4740 for (;;) {
4741 if (first) {
4742 // The first time through the loop, we just consume the root element of
4743 // the heap (the one with smallest distance).
4744 first = false;
4745 } else {
4746 // Previous iterations consumed the root element of the heap.
4747 // Pop root element off of the heap (sift down).
4748 heapSize -= 1;
Jeff Brownb6110c22011-04-01 16:15:13 -07004749 LOG_ASSERT(heapSize > 0);
Jeff Brown6d0fec22010-07-23 21:28:06 -07004750
4751 // Sift down.
4752 heap[0] = heap[heapSize];
4753 for (uint32_t parentIndex = 0; ;) {
4754 uint32_t childIndex = parentIndex * 2 + 1;
4755 if (childIndex >= heapSize) {
4756 break;
4757 }
4758
4759 if (childIndex + 1 < heapSize
4760 && heap[childIndex + 1].distance < heap[childIndex].distance) {
4761 childIndex += 1;
4762 }
4763
4764 if (heap[parentIndex].distance <= heap[childIndex].distance) {
4765 break;
4766 }
4767
4768 swap(heap[parentIndex], heap[childIndex]);
4769 parentIndex = childIndex;
4770 }
4771
4772#if DEBUG_POINTER_ASSIGNMENT
4773 LOGD("calculatePointerIds - reduced distance min-heap: size=%d", heapSize);
4774 for (size_t i = 0; i < heapSize; i++) {
4775 LOGD(" heap[%d]: cur=%d, last=%d, distance=%lld",
4776 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
4777 heap[i].distance);
4778 }
4779#endif
4780 }
4781
4782 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4783 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4784
4785 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4786 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4787
4788 matchedCurrentBits.markBit(currentPointerIndex);
4789 matchedLastBits.markBit(lastPointerIndex);
4790
4791 uint32_t id = mLastTouch.pointers[lastPointerIndex].id;
4792 mCurrentTouch.pointers[currentPointerIndex].id = id;
4793 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4794 usedIdBits.markBit(id);
4795
4796#if DEBUG_POINTER_ASSIGNMENT
4797 LOGD("calculatePointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld",
4798 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
4799#endif
4800 break;
4801 }
4802 }
4803
4804 // Assign fresh ids to new pointers.
4805 if (currentPointerCount > lastPointerCount) {
4806 for (uint32_t i = currentPointerCount - lastPointerCount; ;) {
4807 uint32_t currentPointerIndex = matchedCurrentBits.firstUnmarkedBit();
4808 uint32_t id = usedIdBits.firstUnmarkedBit();
4809
4810 mCurrentTouch.pointers[currentPointerIndex].id = id;
4811 mCurrentTouch.idToIndex[id] = currentPointerIndex;
4812 usedIdBits.markBit(id);
4813
4814#if DEBUG_POINTER_ASSIGNMENT
4815 LOGD("calculatePointerIds - assigned: cur=%d, id=%d",
4816 currentPointerIndex, id);
4817#endif
4818
4819 if (--i == 0) break; // done
4820 matchedCurrentBits.markBit(currentPointerIndex);
4821 }
4822 }
4823
4824 // Fix id bits.
4825 mCurrentTouch.idBits = usedIdBits;
4826 }
4827}
4828
4829/* Special hack for devices that have bad screen data: if one of the
4830 * points has moved more than a screen height from the last position,
4831 * then drop it. */
4832bool TouchInputMapper::applyBadTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004833 uint32_t pointerCount = mCurrentTouch.pointerCount;
4834
4835 // Nothing to do if there are no points.
4836 if (pointerCount == 0) {
4837 return false;
4838 }
4839
4840 // Don't do anything if a finger is going down or up. We run
4841 // here before assigning pointer IDs, so there isn't a good
4842 // way to do per-finger matching.
4843 if (pointerCount != mLastTouch.pointerCount) {
4844 return false;
4845 }
4846
4847 // We consider a single movement across more than a 7/16 of
4848 // the long size of the screen to be bad. This was a magic value
4849 // determined by looking at the maximum distance it is feasible
4850 // to actually move in one sample.
Jeff Brown9626b142011-03-03 02:09:54 -08004851 int32_t maxDeltaY = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) * 7 / 16;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004852
4853 // XXX The original code in InputDevice.java included commented out
4854 // code for testing the X axis. Note that when we drop a point
4855 // we don't actually restore the old X either. Strange.
4856 // The old code also tries to track when bad points were previously
4857 // detected but it turns out that due to the placement of a "break"
4858 // at the end of the loop, we never set mDroppedBadPoint to true
4859 // so it is effectively dead code.
4860 // Need to figure out if the old code is busted or just overcomplicated
4861 // but working as intended.
4862
4863 // Look through all new points and see if any are farther than
4864 // acceptable from all previous points.
4865 for (uint32_t i = pointerCount; i-- > 0; ) {
4866 int32_t y = mCurrentTouch.pointers[i].y;
4867 int32_t closestY = INT_MAX;
4868 int32_t closestDeltaY = 0;
4869
4870#if DEBUG_HACKS
4871 LOGD("BadTouchFilter: Looking at next point #%d: y=%d", i, y);
4872#endif
4873
4874 for (uint32_t j = pointerCount; j-- > 0; ) {
4875 int32_t lastY = mLastTouch.pointers[j].y;
4876 int32_t deltaY = abs(y - lastY);
4877
4878#if DEBUG_HACKS
4879 LOGD("BadTouchFilter: Comparing with last point #%d: y=%d deltaY=%d",
4880 j, lastY, deltaY);
4881#endif
4882
4883 if (deltaY < maxDeltaY) {
4884 goto SkipSufficientlyClosePoint;
4885 }
4886 if (deltaY < closestDeltaY) {
4887 closestDeltaY = deltaY;
4888 closestY = lastY;
4889 }
4890 }
4891
4892 // Must not have found a close enough match.
4893#if DEBUG_HACKS
4894 LOGD("BadTouchFilter: Dropping bad point #%d: newY=%d oldY=%d deltaY=%d maxDeltaY=%d",
4895 i, y, closestY, closestDeltaY, maxDeltaY);
4896#endif
4897
4898 mCurrentTouch.pointers[i].y = closestY;
4899 return true; // XXX original code only corrects one point
4900
4901 SkipSufficientlyClosePoint: ;
4902 }
4903
4904 // No change.
4905 return false;
4906}
4907
4908/* Special hack for devices that have bad screen data: drop points where
4909 * the coordinate value for one axis has jumped to the other pointer's location.
4910 */
4911bool TouchInputMapper::applyJumpyTouchFilter() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07004912 uint32_t pointerCount = mCurrentTouch.pointerCount;
4913 if (mLastTouch.pointerCount != pointerCount) {
4914#if DEBUG_HACKS
4915 LOGD("JumpyTouchFilter: Different pointer count %d -> %d",
4916 mLastTouch.pointerCount, pointerCount);
4917 for (uint32_t i = 0; i < pointerCount; i++) {
4918 LOGD(" Pointer %d (%d, %d)", i,
4919 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4920 }
4921#endif
4922
4923 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_TRANSITION_DROPS) {
4924 if (mLastTouch.pointerCount == 1 && pointerCount == 2) {
4925 // Just drop the first few events going from 1 to 2 pointers.
4926 // They're bad often enough that they're not worth considering.
4927 mCurrentTouch.pointerCount = 1;
4928 mJumpyTouchFilter.jumpyPointsDropped += 1;
4929
4930#if DEBUG_HACKS
4931 LOGD("JumpyTouchFilter: Pointer 2 dropped");
4932#endif
4933 return true;
4934 } else if (mLastTouch.pointerCount == 2 && pointerCount == 1) {
4935 // The event when we go from 2 -> 1 tends to be messed up too
4936 mCurrentTouch.pointerCount = 2;
4937 mCurrentTouch.pointers[0] = mLastTouch.pointers[0];
4938 mCurrentTouch.pointers[1] = mLastTouch.pointers[1];
4939 mJumpyTouchFilter.jumpyPointsDropped += 1;
4940
4941#if DEBUG_HACKS
4942 for (int32_t i = 0; i < 2; i++) {
4943 LOGD("JumpyTouchFilter: Pointer %d replaced (%d, %d)", i,
4944 mCurrentTouch.pointers[i].x, mCurrentTouch.pointers[i].y);
4945 }
4946#endif
4947 return true;
4948 }
4949 }
4950 // Reset jumpy points dropped on other transitions or if limit exceeded.
4951 mJumpyTouchFilter.jumpyPointsDropped = 0;
4952
4953#if DEBUG_HACKS
4954 LOGD("JumpyTouchFilter: Transition - drop limit reset");
4955#endif
4956 return false;
4957 }
4958
4959 // We have the same number of pointers as last time.
4960 // A 'jumpy' point is one where the coordinate value for one axis
4961 // has jumped to the other pointer's location. No need to do anything
4962 // else if we only have one pointer.
4963 if (pointerCount < 2) {
4964 return false;
4965 }
4966
4967 if (mJumpyTouchFilter.jumpyPointsDropped < JUMPY_DROP_LIMIT) {
Jeff Brown9626b142011-03-03 02:09:54 -08004968 int jumpyEpsilon = (mRawAxes.y.maxValue - mRawAxes.y.minValue + 1) / JUMPY_EPSILON_DIVISOR;
Jeff Brown6d0fec22010-07-23 21:28:06 -07004969
4970 // We only replace the single worst jumpy point as characterized by pointer distance
4971 // in a single axis.
4972 int32_t badPointerIndex = -1;
4973 int32_t badPointerReplacementIndex = -1;
4974 int32_t badPointerDistance = INT_MIN; // distance to be corrected
4975
4976 for (uint32_t i = pointerCount; i-- > 0; ) {
4977 int32_t x = mCurrentTouch.pointers[i].x;
4978 int32_t y = mCurrentTouch.pointers[i].y;
4979
4980#if DEBUG_HACKS
4981 LOGD("JumpyTouchFilter: Point %d (%d, %d)", i, x, y);
4982#endif
4983
4984 // Check if a touch point is too close to another's coordinates
4985 bool dropX = false, dropY = false;
4986 for (uint32_t j = 0; j < pointerCount; j++) {
4987 if (i == j) {
4988 continue;
4989 }
4990
4991 if (abs(x - mCurrentTouch.pointers[j].x) <= jumpyEpsilon) {
4992 dropX = true;
4993 break;
4994 }
4995
4996 if (abs(y - mCurrentTouch.pointers[j].y) <= jumpyEpsilon) {
4997 dropY = true;
4998 break;
4999 }
5000 }
5001 if (! dropX && ! dropY) {
5002 continue; // not jumpy
5003 }
5004
5005 // Find a replacement candidate by comparing with older points on the
5006 // complementary (non-jumpy) axis.
5007 int32_t distance = INT_MIN; // distance to be corrected
5008 int32_t replacementIndex = -1;
5009
5010 if (dropX) {
5011 // X looks too close. Find an older replacement point with a close Y.
5012 int32_t smallestDeltaY = INT_MAX;
5013 for (uint32_t j = 0; j < pointerCount; j++) {
5014 int32_t deltaY = abs(y - mLastTouch.pointers[j].y);
5015 if (deltaY < smallestDeltaY) {
5016 smallestDeltaY = deltaY;
5017 replacementIndex = j;
5018 }
5019 }
5020 distance = abs(x - mLastTouch.pointers[replacementIndex].x);
5021 } else {
5022 // Y looks too close. Find an older replacement point with a close X.
5023 int32_t smallestDeltaX = INT_MAX;
5024 for (uint32_t j = 0; j < pointerCount; j++) {
5025 int32_t deltaX = abs(x - mLastTouch.pointers[j].x);
5026 if (deltaX < smallestDeltaX) {
5027 smallestDeltaX = deltaX;
5028 replacementIndex = j;
5029 }
5030 }
5031 distance = abs(y - mLastTouch.pointers[replacementIndex].y);
5032 }
5033
5034 // If replacing this pointer would correct a worse error than the previous ones
5035 // considered, then use this replacement instead.
5036 if (distance > badPointerDistance) {
5037 badPointerIndex = i;
5038 badPointerReplacementIndex = replacementIndex;
5039 badPointerDistance = distance;
5040 }
5041 }
5042
5043 // Correct the jumpy pointer if one was found.
5044 if (badPointerIndex >= 0) {
5045#if DEBUG_HACKS
5046 LOGD("JumpyTouchFilter: Replacing bad pointer %d with (%d, %d)",
5047 badPointerIndex,
5048 mLastTouch.pointers[badPointerReplacementIndex].x,
5049 mLastTouch.pointers[badPointerReplacementIndex].y);
5050#endif
5051
5052 mCurrentTouch.pointers[badPointerIndex].x =
5053 mLastTouch.pointers[badPointerReplacementIndex].x;
5054 mCurrentTouch.pointers[badPointerIndex].y =
5055 mLastTouch.pointers[badPointerReplacementIndex].y;
5056 mJumpyTouchFilter.jumpyPointsDropped += 1;
5057 return true;
5058 }
5059 }
5060
5061 mJumpyTouchFilter.jumpyPointsDropped = 0;
5062 return false;
5063}
5064
5065/* Special hack for devices that have bad screen data: aggregate and
5066 * compute averages of the coordinate data, to reduce the amount of
5067 * jitter seen by applications. */
5068void TouchInputMapper::applyAveragingTouchFilter() {
5069 for (uint32_t currentIndex = 0; currentIndex < mCurrentTouch.pointerCount; currentIndex++) {
5070 uint32_t id = mCurrentTouch.pointers[currentIndex].id;
5071 int32_t x = mCurrentTouch.pointers[currentIndex].x;
5072 int32_t y = mCurrentTouch.pointers[currentIndex].y;
Jeff Brown8d608662010-08-30 03:02:23 -07005073 int32_t pressure;
5074 switch (mCalibration.pressureSource) {
5075 case Calibration::PRESSURE_SOURCE_PRESSURE:
5076 pressure = mCurrentTouch.pointers[currentIndex].pressure;
5077 break;
5078 case Calibration::PRESSURE_SOURCE_TOUCH:
5079 pressure = mCurrentTouch.pointers[currentIndex].touchMajor;
5080 break;
5081 default:
5082 pressure = 1;
5083 break;
5084 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07005085
5086 if (mLastTouch.idBits.hasBit(id)) {
5087 // Pointer was down before and is still down now.
5088 // Compute average over history trace.
5089 uint32_t start = mAveragingTouchFilter.historyStart[id];
5090 uint32_t end = mAveragingTouchFilter.historyEnd[id];
5091
5092 int64_t deltaX = x - mAveragingTouchFilter.historyData[end].pointers[id].x;
5093 int64_t deltaY = y - mAveragingTouchFilter.historyData[end].pointers[id].y;
5094 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
5095
5096#if DEBUG_HACKS
5097 LOGD("AveragingTouchFilter: Pointer id %d - Distance from last sample: %lld",
5098 id, distance);
5099#endif
5100
5101 if (distance < AVERAGING_DISTANCE_LIMIT) {
5102 // Increment end index in preparation for recording new historical data.
5103 end += 1;
5104 if (end > AVERAGING_HISTORY_SIZE) {
5105 end = 0;
5106 }
5107
5108 // If the end index has looped back to the start index then we have filled
5109 // the historical trace up to the desired size so we drop the historical
5110 // data at the start of the trace.
5111 if (end == start) {
5112 start += 1;
5113 if (start > AVERAGING_HISTORY_SIZE) {
5114 start = 0;
5115 }
5116 }
5117
5118 // Add the raw data to the historical trace.
5119 mAveragingTouchFilter.historyStart[id] = start;
5120 mAveragingTouchFilter.historyEnd[id] = end;
5121 mAveragingTouchFilter.historyData[end].pointers[id].x = x;
5122 mAveragingTouchFilter.historyData[end].pointers[id].y = y;
5123 mAveragingTouchFilter.historyData[end].pointers[id].pressure = pressure;
5124
5125 // Average over all historical positions in the trace by total pressure.
5126 int32_t averagedX = 0;
5127 int32_t averagedY = 0;
5128 int32_t totalPressure = 0;
5129 for (;;) {
5130 int32_t historicalX = mAveragingTouchFilter.historyData[start].pointers[id].x;
5131 int32_t historicalY = mAveragingTouchFilter.historyData[start].pointers[id].y;
5132 int32_t historicalPressure = mAveragingTouchFilter.historyData[start]
5133 .pointers[id].pressure;
5134
5135 averagedX += historicalX * historicalPressure;
5136 averagedY += historicalY * historicalPressure;
5137 totalPressure += historicalPressure;
5138
5139 if (start == end) {
5140 break;
5141 }
5142
5143 start += 1;
5144 if (start > AVERAGING_HISTORY_SIZE) {
5145 start = 0;
5146 }
5147 }
5148
Jeff Brown8d608662010-08-30 03:02:23 -07005149 if (totalPressure != 0) {
5150 averagedX /= totalPressure;
5151 averagedY /= totalPressure;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005152
5153#if DEBUG_HACKS
Jeff Brown8d608662010-08-30 03:02:23 -07005154 LOGD("AveragingTouchFilter: Pointer id %d - "
5155 "totalPressure=%d, averagedX=%d, averagedY=%d", id, totalPressure,
5156 averagedX, averagedY);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005157#endif
5158
Jeff Brown8d608662010-08-30 03:02:23 -07005159 mCurrentTouch.pointers[currentIndex].x = averagedX;
5160 mCurrentTouch.pointers[currentIndex].y = averagedY;
5161 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07005162 } else {
5163#if DEBUG_HACKS
5164 LOGD("AveragingTouchFilter: Pointer id %d - Exceeded max distance", id);
5165#endif
5166 }
5167 } else {
5168#if DEBUG_HACKS
5169 LOGD("AveragingTouchFilter: Pointer id %d - Pointer went up", id);
5170#endif
5171 }
5172
5173 // Reset pointer history.
5174 mAveragingTouchFilter.historyStart[id] = 0;
5175 mAveragingTouchFilter.historyEnd[id] = 0;
5176 mAveragingTouchFilter.historyData[0].pointers[id].x = x;
5177 mAveragingTouchFilter.historyData[0].pointers[id].y = y;
5178 mAveragingTouchFilter.historyData[0].pointers[id].pressure = pressure;
5179 }
5180}
5181
5182int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07005183 { // acquire lock
5184 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005185
Jeff Brown6328cdc2010-07-29 18:18:33 -07005186 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.keyCode == keyCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07005187 return AKEY_STATE_VIRTUAL;
5188 }
5189
Jeff Brown6328cdc2010-07-29 18:18:33 -07005190 size_t numVirtualKeys = mLocked.virtualKeys.size();
5191 for (size_t i = 0; i < numVirtualKeys; i++) {
5192 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07005193 if (virtualKey.keyCode == keyCode) {
5194 return AKEY_STATE_UP;
5195 }
5196 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07005197 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07005198
5199 return AKEY_STATE_UNKNOWN;
5200}
5201
5202int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07005203 { // acquire lock
5204 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005205
Jeff Brown6328cdc2010-07-29 18:18:33 -07005206 if (mLocked.currentVirtualKey.down && mLocked.currentVirtualKey.scanCode == scanCode) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07005207 return AKEY_STATE_VIRTUAL;
5208 }
5209
Jeff Brown6328cdc2010-07-29 18:18:33 -07005210 size_t numVirtualKeys = mLocked.virtualKeys.size();
5211 for (size_t i = 0; i < numVirtualKeys; i++) {
5212 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07005213 if (virtualKey.scanCode == scanCode) {
5214 return AKEY_STATE_UP;
5215 }
5216 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07005217 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07005218
5219 return AKEY_STATE_UNKNOWN;
5220}
5221
5222bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
5223 const int32_t* keyCodes, uint8_t* outFlags) {
Jeff Brown6328cdc2010-07-29 18:18:33 -07005224 { // acquire lock
5225 AutoMutex _l(mLock);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005226
Jeff Brown6328cdc2010-07-29 18:18:33 -07005227 size_t numVirtualKeys = mLocked.virtualKeys.size();
5228 for (size_t i = 0; i < numVirtualKeys; i++) {
5229 const VirtualKey& virtualKey = mLocked.virtualKeys[i];
Jeff Brown6d0fec22010-07-23 21:28:06 -07005230
5231 for (size_t i = 0; i < numCodes; i++) {
5232 if (virtualKey.keyCode == keyCodes[i]) {
5233 outFlags[i] = 1;
5234 }
5235 }
5236 }
Jeff Brown6328cdc2010-07-29 18:18:33 -07005237 } // release lock
Jeff Brown6d0fec22010-07-23 21:28:06 -07005238
5239 return true;
5240}
5241
5242
5243// --- SingleTouchInputMapper ---
5244
Jeff Brown47e6b1b2010-11-29 17:37:49 -08005245SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
5246 TouchInputMapper(device) {
Jeff Brown80fd47c2011-05-24 01:07:44 -07005247 clearState();
Jeff Brown6d0fec22010-07-23 21:28:06 -07005248}
5249
5250SingleTouchInputMapper::~SingleTouchInputMapper() {
5251}
5252
Jeff Brown80fd47c2011-05-24 01:07:44 -07005253void SingleTouchInputMapper::clearState() {
Jeff Brown6d0fec22010-07-23 21:28:06 -07005254 mAccumulator.clear();
5255
5256 mDown = false;
5257 mX = 0;
5258 mY = 0;
Jeff Brown8d608662010-08-30 03:02:23 -07005259 mPressure = 0; // default to 0 for devices that don't report pressure
5260 mToolWidth = 0; // default to 0 for devices that don't report tool width
Jeff Brownace13b12011-03-09 17:39:48 -08005261 mButtonState = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005262}
5263
5264void SingleTouchInputMapper::reset() {
5265 TouchInputMapper::reset();
5266
Jeff Brown80fd47c2011-05-24 01:07:44 -07005267 clearState();
Jeff Brown6d0fec22010-07-23 21:28:06 -07005268 }
5269
5270void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
5271 switch (rawEvent->type) {
5272 case EV_KEY:
5273 switch (rawEvent->scanCode) {
5274 case BTN_TOUCH:
5275 mAccumulator.fields |= Accumulator::FIELD_BTN_TOUCH;
5276 mAccumulator.btnTouch = rawEvent->value != 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005277 // Don't sync immediately. Wait until the next SYN_REPORT since we might
5278 // not have received valid position information yet. This logic assumes that
5279 // BTN_TOUCH is always followed by SYN_REPORT as part of a complete packet.
Jeff Brown6d0fec22010-07-23 21:28:06 -07005280 break;
Jeff Brownace13b12011-03-09 17:39:48 -08005281 default:
5282 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07005283 int32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
Jeff Brownace13b12011-03-09 17:39:48 -08005284 if (buttonState) {
5285 if (rawEvent->value) {
5286 mAccumulator.buttonDown |= buttonState;
5287 } else {
5288 mAccumulator.buttonUp |= buttonState;
5289 }
5290 mAccumulator.fields |= Accumulator::FIELD_BUTTONS;
5291 }
5292 }
5293 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005294 }
5295 break;
5296
5297 case EV_ABS:
5298 switch (rawEvent->scanCode) {
5299 case ABS_X:
5300 mAccumulator.fields |= Accumulator::FIELD_ABS_X;
5301 mAccumulator.absX = rawEvent->value;
5302 break;
5303 case ABS_Y:
5304 mAccumulator.fields |= Accumulator::FIELD_ABS_Y;
5305 mAccumulator.absY = rawEvent->value;
5306 break;
5307 case ABS_PRESSURE:
5308 mAccumulator.fields |= Accumulator::FIELD_ABS_PRESSURE;
5309 mAccumulator.absPressure = rawEvent->value;
5310 break;
5311 case ABS_TOOL_WIDTH:
5312 mAccumulator.fields |= Accumulator::FIELD_ABS_TOOL_WIDTH;
5313 mAccumulator.absToolWidth = rawEvent->value;
5314 break;
5315 }
5316 break;
5317
5318 case EV_SYN:
5319 switch (rawEvent->scanCode) {
5320 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005321 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005322 break;
5323 }
5324 break;
5325 }
5326}
5327
5328void SingleTouchInputMapper::sync(nsecs_t when) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07005329 uint32_t fields = mAccumulator.fields;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005330 if (fields == 0) {
5331 return; // no new state changes, so nothing to do
5332 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07005333
5334 if (fields & Accumulator::FIELD_BTN_TOUCH) {
5335 mDown = mAccumulator.btnTouch;
5336 }
5337
5338 if (fields & Accumulator::FIELD_ABS_X) {
5339 mX = mAccumulator.absX;
5340 }
5341
5342 if (fields & Accumulator::FIELD_ABS_Y) {
5343 mY = mAccumulator.absY;
5344 }
5345
5346 if (fields & Accumulator::FIELD_ABS_PRESSURE) {
5347 mPressure = mAccumulator.absPressure;
5348 }
5349
5350 if (fields & Accumulator::FIELD_ABS_TOOL_WIDTH) {
Jeff Brown8d608662010-08-30 03:02:23 -07005351 mToolWidth = mAccumulator.absToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005352 }
5353
Jeff Brownace13b12011-03-09 17:39:48 -08005354 if (fields & Accumulator::FIELD_BUTTONS) {
5355 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
5356 }
5357
Jeff Brown6d0fec22010-07-23 21:28:06 -07005358 mCurrentTouch.clear();
5359
5360 if (mDown) {
5361 mCurrentTouch.pointerCount = 1;
5362 mCurrentTouch.pointers[0].id = 0;
5363 mCurrentTouch.pointers[0].x = mX;
5364 mCurrentTouch.pointers[0].y = mY;
5365 mCurrentTouch.pointers[0].pressure = mPressure;
Jeff Brown8d608662010-08-30 03:02:23 -07005366 mCurrentTouch.pointers[0].touchMajor = 0;
5367 mCurrentTouch.pointers[0].touchMinor = 0;
5368 mCurrentTouch.pointers[0].toolMajor = mToolWidth;
5369 mCurrentTouch.pointers[0].toolMinor = mToolWidth;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005370 mCurrentTouch.pointers[0].orientation = 0;
Jeff Brown80fd47c2011-05-24 01:07:44 -07005371 mCurrentTouch.pointers[0].distance = 0;
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07005372 mCurrentTouch.pointers[0].isStylus = false; // TODO: Set stylus
Jeff Brown6d0fec22010-07-23 21:28:06 -07005373 mCurrentTouch.idToIndex[0] = 0;
5374 mCurrentTouch.idBits.markBit(0);
Jeff Brownace13b12011-03-09 17:39:48 -08005375 mCurrentTouch.buttonState = mButtonState;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005376 }
5377
5378 syncTouch(when, true);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005379
5380 mAccumulator.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -07005381}
5382
Jeff Brown8d608662010-08-30 03:02:23 -07005383void SingleTouchInputMapper::configureRawAxes() {
5384 TouchInputMapper::configureRawAxes();
Jeff Brown6d0fec22010-07-23 21:28:06 -07005385
Jeff Brown8d608662010-08-30 03:02:23 -07005386 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_X, & mRawAxes.x);
5387 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_Y, & mRawAxes.y);
5388 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_PRESSURE, & mRawAxes.pressure);
5389 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_TOOL_WIDTH, & mRawAxes.toolMajor);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005390}
5391
5392
5393// --- MultiTouchInputMapper ---
5394
Jeff Brown47e6b1b2010-11-29 17:37:49 -08005395MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
Jeff Brown80fd47c2011-05-24 01:07:44 -07005396 TouchInputMapper(device), mSlotCount(0), mUsingSlotsProtocol(false) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07005397}
5398
5399MultiTouchInputMapper::~MultiTouchInputMapper() {
5400}
5401
Jeff Brown80fd47c2011-05-24 01:07:44 -07005402void MultiTouchInputMapper::clearState() {
Jeff Brown441a9c22011-06-02 18:22:25 -07005403 mAccumulator.clearSlots(mSlotCount);
5404 mAccumulator.clearButtons();
Jeff Brownace13b12011-03-09 17:39:48 -08005405 mButtonState = 0;
Jeff Brown2717eff2011-06-30 23:53:07 -07005406
5407 if (mUsingSlotsProtocol) {
5408 // Query the driver for the current slot index and use it as the initial slot
5409 // before we start reading events from the device. It is possible that the
5410 // current slot index will not be the same as it was when the first event was
5411 // written into the evdev buffer, which means the input mapper could start
5412 // out of sync with the initial state of the events in the evdev buffer.
5413 // In the extremely unlikely case that this happens, the data from
5414 // two slots will be confused until the next ABS_MT_SLOT event is received.
5415 // This can cause the touch point to "jump", but at least there will be
5416 // no stuck touches.
5417 status_t status = getEventHub()->getAbsoluteAxisValue(getDeviceId(), ABS_MT_SLOT,
5418 &mAccumulator.currentSlot);
5419 if (status) {
5420 LOGW("Could not retrieve current multitouch slot index. status=%d", status);
5421 mAccumulator.currentSlot = -1;
5422 }
5423 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07005424}
5425
5426void MultiTouchInputMapper::reset() {
5427 TouchInputMapper::reset();
5428
Jeff Brown80fd47c2011-05-24 01:07:44 -07005429 clearState();
Jeff Brown6d0fec22010-07-23 21:28:06 -07005430}
5431
5432void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
5433 switch (rawEvent->type) {
Jeff Brownace13b12011-03-09 17:39:48 -08005434 case EV_KEY: {
5435 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07005436 int32_t buttonState = getButtonStateForScanCode(rawEvent->scanCode);
Jeff Brownace13b12011-03-09 17:39:48 -08005437 if (buttonState) {
5438 if (rawEvent->value) {
5439 mAccumulator.buttonDown |= buttonState;
5440 } else {
5441 mAccumulator.buttonUp |= buttonState;
5442 }
5443 }
5444 }
5445 break;
5446 }
5447
Jeff Brown6d0fec22010-07-23 21:28:06 -07005448 case EV_ABS: {
Jeff Brown80fd47c2011-05-24 01:07:44 -07005449 bool newSlot = false;
5450 if (mUsingSlotsProtocol && rawEvent->scanCode == ABS_MT_SLOT) {
5451 mAccumulator.currentSlot = rawEvent->value;
5452 newSlot = true;
5453 }
5454
5455 if (mAccumulator.currentSlot < 0 || size_t(mAccumulator.currentSlot) >= mSlotCount) {
Jeff Brown80fd47c2011-05-24 01:07:44 -07005456#if DEBUG_POINTERS
Jeff Brown441a9c22011-06-02 18:22:25 -07005457 if (newSlot) {
Jeff Brown80fd47c2011-05-24 01:07:44 -07005458 LOGW("MultiTouch device %s emitted invalid slot index %d but it "
5459 "should be between 0 and %d; ignoring this slot.",
5460 getDeviceName().string(), mAccumulator.currentSlot, mSlotCount);
Jeff Brown80fd47c2011-05-24 01:07:44 -07005461 }
Jeff Brown441a9c22011-06-02 18:22:25 -07005462#endif
Jeff Brown80fd47c2011-05-24 01:07:44 -07005463 break;
5464 }
5465
5466 Accumulator::Slot* slot = &mAccumulator.slots[mAccumulator.currentSlot];
Jeff Brown6d0fec22010-07-23 21:28:06 -07005467
5468 switch (rawEvent->scanCode) {
5469 case ABS_MT_POSITION_X:
Jeff Brown80fd47c2011-05-24 01:07:44 -07005470 slot->fields |= Accumulator::FIELD_ABS_MT_POSITION_X;
5471 slot->absMTPositionX = rawEvent->value;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005472 break;
5473 case ABS_MT_POSITION_Y:
Jeff Brown80fd47c2011-05-24 01:07:44 -07005474 slot->fields |= Accumulator::FIELD_ABS_MT_POSITION_Y;
5475 slot->absMTPositionY = rawEvent->value;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005476 break;
5477 case ABS_MT_TOUCH_MAJOR:
Jeff Brown80fd47c2011-05-24 01:07:44 -07005478 slot->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MAJOR;
5479 slot->absMTTouchMajor = rawEvent->value;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005480 break;
5481 case ABS_MT_TOUCH_MINOR:
Jeff Brown80fd47c2011-05-24 01:07:44 -07005482 slot->fields |= Accumulator::FIELD_ABS_MT_TOUCH_MINOR;
5483 slot->absMTTouchMinor = rawEvent->value;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005484 break;
5485 case ABS_MT_WIDTH_MAJOR:
Jeff Brown80fd47c2011-05-24 01:07:44 -07005486 slot->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MAJOR;
5487 slot->absMTWidthMajor = rawEvent->value;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005488 break;
5489 case ABS_MT_WIDTH_MINOR:
Jeff Brown80fd47c2011-05-24 01:07:44 -07005490 slot->fields |= Accumulator::FIELD_ABS_MT_WIDTH_MINOR;
5491 slot->absMTWidthMinor = rawEvent->value;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005492 break;
5493 case ABS_MT_ORIENTATION:
Jeff Brown80fd47c2011-05-24 01:07:44 -07005494 slot->fields |= Accumulator::FIELD_ABS_MT_ORIENTATION;
5495 slot->absMTOrientation = rawEvent->value;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005496 break;
5497 case ABS_MT_TRACKING_ID:
Jeff Brown80fd47c2011-05-24 01:07:44 -07005498 if (mUsingSlotsProtocol && rawEvent->value < 0) {
5499 slot->clear();
5500 } else {
5501 slot->fields |= Accumulator::FIELD_ABS_MT_TRACKING_ID;
5502 slot->absMTTrackingId = rawEvent->value;
5503 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07005504 break;
Jeff Brown8d608662010-08-30 03:02:23 -07005505 case ABS_MT_PRESSURE:
Jeff Brown80fd47c2011-05-24 01:07:44 -07005506 slot->fields |= Accumulator::FIELD_ABS_MT_PRESSURE;
5507 slot->absMTPressure = rawEvent->value;
5508 break;
5509 case ABS_MT_TOOL_TYPE:
5510 slot->fields |= Accumulator::FIELD_ABS_MT_TOOL_TYPE;
5511 slot->absMTToolType = rawEvent->value;
Jeff Brown8d608662010-08-30 03:02:23 -07005512 break;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005513 }
5514 break;
5515 }
5516
5517 case EV_SYN:
5518 switch (rawEvent->scanCode) {
5519 case SYN_MT_REPORT: {
5520 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
Jeff Brown80fd47c2011-05-24 01:07:44 -07005521 mAccumulator.currentSlot += 1;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005522 break;
5523 }
5524
5525 case SYN_REPORT:
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005526 sync(rawEvent->when);
Jeff Brown6d0fec22010-07-23 21:28:06 -07005527 break;
5528 }
5529 break;
5530 }
5531}
5532
5533void MultiTouchInputMapper::sync(nsecs_t when) {
5534 static const uint32_t REQUIRED_FIELDS =
Jeff Brown8d608662010-08-30 03:02:23 -07005535 Accumulator::FIELD_ABS_MT_POSITION_X | Accumulator::FIELD_ABS_MT_POSITION_Y;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005536
Jeff Brown80fd47c2011-05-24 01:07:44 -07005537 size_t inCount = mSlotCount;
5538 size_t outCount = 0;
Jeff Brown6d0fec22010-07-23 21:28:06 -07005539 bool havePointerIds = true;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005540
Jeff Brown6d0fec22010-07-23 21:28:06 -07005541 mCurrentTouch.clear();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005542
Jeff Brown80fd47c2011-05-24 01:07:44 -07005543 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
5544 const Accumulator::Slot& inSlot = mAccumulator.slots[inIndex];
5545 uint32_t fields = inSlot.fields;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005546
Jeff Brown6d0fec22010-07-23 21:28:06 -07005547 if ((fields & REQUIRED_FIELDS) != REQUIRED_FIELDS) {
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005548 // Some drivers send empty MT sync packets without X / Y to indicate a pointer up.
Jeff Brown80fd47c2011-05-24 01:07:44 -07005549 // This may also indicate an unused slot.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005550 // Drop this finger.
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005551 continue;
5552 }
5553
Jeff Brown80fd47c2011-05-24 01:07:44 -07005554 if (outCount >= MAX_POINTERS) {
5555#if DEBUG_POINTERS
5556 LOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
5557 "ignoring the rest.",
5558 getDeviceName().string(), MAX_POINTERS);
5559#endif
5560 break; // too many fingers!
5561 }
5562
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005563 PointerData& outPointer = mCurrentTouch.pointers[outCount];
Jeff Brown80fd47c2011-05-24 01:07:44 -07005564 outPointer.x = inSlot.absMTPositionX;
5565 outPointer.y = inSlot.absMTPositionY;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005566
Jeff Brown8d608662010-08-30 03:02:23 -07005567 if (fields & Accumulator::FIELD_ABS_MT_PRESSURE) {
Jeff Brown80fd47c2011-05-24 01:07:44 -07005568 outPointer.pressure = inSlot.absMTPressure;
Jeff Brown8d608662010-08-30 03:02:23 -07005569 } else {
5570 // Default pressure to 0 if absent.
5571 outPointer.pressure = 0;
5572 }
5573
5574 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MAJOR) {
Jeff Brown80fd47c2011-05-24 01:07:44 -07005575 if (inSlot.absMTTouchMajor <= 0) {
Jeff Brown8d608662010-08-30 03:02:23 -07005576 // Some devices send sync packets with X / Y but with a 0 touch major to indicate
5577 // a pointer going up. Drop this finger.
5578 continue;
5579 }
Jeff Brown80fd47c2011-05-24 01:07:44 -07005580 outPointer.touchMajor = inSlot.absMTTouchMajor;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005581 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005582 // Default touch area to 0 if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005583 outPointer.touchMajor = 0;
5584 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005585
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005586 if (fields & Accumulator::FIELD_ABS_MT_TOUCH_MINOR) {
Jeff Brown80fd47c2011-05-24 01:07:44 -07005587 outPointer.touchMinor = inSlot.absMTTouchMinor;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005588 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005589 // Assume touch area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005590 outPointer.touchMinor = outPointer.touchMajor;
5591 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005592
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005593 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MAJOR) {
Jeff Brown80fd47c2011-05-24 01:07:44 -07005594 outPointer.toolMajor = inSlot.absMTWidthMajor;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005595 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005596 // Default tool area to 0 if absent.
5597 outPointer.toolMajor = 0;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005598 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005599
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005600 if (fields & Accumulator::FIELD_ABS_MT_WIDTH_MINOR) {
Jeff Brown80fd47c2011-05-24 01:07:44 -07005601 outPointer.toolMinor = inSlot.absMTWidthMinor;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005602 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005603 // Assume tool area is circular.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005604 outPointer.toolMinor = outPointer.toolMajor;
5605 }
5606
5607 if (fields & Accumulator::FIELD_ABS_MT_ORIENTATION) {
Jeff Brown80fd47c2011-05-24 01:07:44 -07005608 outPointer.orientation = inSlot.absMTOrientation;
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005609 } else {
Jeff Brown8d608662010-08-30 03:02:23 -07005610 // Default orientation to vertical if absent.
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005611 outPointer.orientation = 0;
5612 }
5613
Jeff Brown80fd47c2011-05-24 01:07:44 -07005614 if (fields & Accumulator::FIELD_ABS_MT_DISTANCE) {
5615 outPointer.distance = inSlot.absMTDistance;
5616 } else {
5617 // Default distance is 0 (direct contact).
5618 outPointer.distance = 0;
5619 }
5620
5621 if (fields & Accumulator::FIELD_ABS_MT_TOOL_TYPE) {
5622 outPointer.isStylus = (inSlot.absMTToolType == MT_TOOL_PEN);
5623 } else {
5624 // Assume this is not a stylus.
5625 outPointer.isStylus = false;
5626 }
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07005627
Jeff Brown8d608662010-08-30 03:02:23 -07005628 // Assign pointer id using tracking id if available.
Jeff Brown6d0fec22010-07-23 21:28:06 -07005629 if (havePointerIds) {
Jeff Brown80fd47c2011-05-24 01:07:44 -07005630 int32_t id;
5631 if (mUsingSlotsProtocol) {
5632 id = inIndex;
5633 } else if (fields & Accumulator::FIELD_ABS_MT_TRACKING_ID) {
5634 id = inSlot.absMTTrackingId;
5635 } else {
5636 id = -1;
5637 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005638
Jeff Brown80fd47c2011-05-24 01:07:44 -07005639 if (id >= 0 && id <= MAX_POINTER_ID) {
5640 outPointer.id = id;
5641 mCurrentTouch.idToIndex[id] = outCount;
5642 mCurrentTouch.idBits.markBit(id);
5643 } else {
5644 if (id >= 0) {
Jeff Brown6d0fec22010-07-23 21:28:06 -07005645#if DEBUG_POINTERS
Jeff Brown80fd47c2011-05-24 01:07:44 -07005646 LOGD("Pointers: Ignoring driver provided slot index or tracking id %d because "
5647 "it is larger than the maximum supported pointer id %d",
Jeff Brown6d0fec22010-07-23 21:28:06 -07005648 id, MAX_POINTER_ID);
5649#endif
Jeff Brown6d0fec22010-07-23 21:28:06 -07005650 }
Jeff Brown6d0fec22010-07-23 21:28:06 -07005651 havePointerIds = false;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005652 }
5653 }
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005654
Jeff Brown6d0fec22010-07-23 21:28:06 -07005655 outCount += 1;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005656 }
5657
Jeff Brown6d0fec22010-07-23 21:28:06 -07005658 mCurrentTouch.pointerCount = outCount;
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005659
Jeff Brownace13b12011-03-09 17:39:48 -08005660 mButtonState = (mButtonState | mAccumulator.buttonDown) & ~mAccumulator.buttonUp;
5661 mCurrentTouch.buttonState = mButtonState;
5662
Jeff Brown6d0fec22010-07-23 21:28:06 -07005663 syncTouch(when, havePointerIds);
Jeff Brown2dfd7a72010-08-17 20:38:35 -07005664
Jeff Brown441a9c22011-06-02 18:22:25 -07005665 if (!mUsingSlotsProtocol) {
5666 mAccumulator.clearSlots(mSlotCount);
5667 }
5668 mAccumulator.clearButtons();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005669}
5670
Jeff Brown8d608662010-08-30 03:02:23 -07005671void MultiTouchInputMapper::configureRawAxes() {
5672 TouchInputMapper::configureRawAxes();
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005673
Jeff Brown80fd47c2011-05-24 01:07:44 -07005674 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_X, &mRawAxes.x);
5675 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_POSITION_Y, &mRawAxes.y);
5676 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MAJOR, &mRawAxes.touchMajor);
5677 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TOUCH_MINOR, &mRawAxes.touchMinor);
5678 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MAJOR, &mRawAxes.toolMajor);
5679 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_WIDTH_MINOR, &mRawAxes.toolMinor);
5680 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_ORIENTATION, &mRawAxes.orientation);
5681 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_PRESSURE, &mRawAxes.pressure);
5682 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_DISTANCE, &mRawAxes.distance);
5683 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_TRACKING_ID, &mRawAxes.trackingId);
5684 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), ABS_MT_SLOT, &mRawAxes.slot);
5685
5686 if (mRawAxes.trackingId.valid
5687 && mRawAxes.slot.valid && mRawAxes.slot.minValue == 0 && mRawAxes.slot.maxValue > 0) {
5688 mSlotCount = mRawAxes.slot.maxValue + 1;
5689 if (mSlotCount > MAX_SLOTS) {
5690 LOGW("MultiTouch Device %s reported %d slots but the framework "
5691 "only supports a maximum of %d slots at this time.",
5692 getDeviceName().string(), mSlotCount, MAX_SLOTS);
5693 mSlotCount = MAX_SLOTS;
5694 }
5695 mUsingSlotsProtocol = true;
5696 } else {
5697 mSlotCount = MAX_POINTERS;
5698 mUsingSlotsProtocol = false;
5699 }
5700
5701 mAccumulator.allocateSlots(mSlotCount);
Jeff Brown2717eff2011-06-30 23:53:07 -07005702
5703 clearState();
Jeff Brown9c3cda02010-06-15 01:31:58 -07005704}
5705
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07005706
Jeff Browncb1404e2011-01-15 18:14:15 -08005707// --- JoystickInputMapper ---
5708
5709JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
5710 InputMapper(device) {
Jeff Browncb1404e2011-01-15 18:14:15 -08005711}
5712
5713JoystickInputMapper::~JoystickInputMapper() {
5714}
5715
5716uint32_t JoystickInputMapper::getSources() {
5717 return AINPUT_SOURCE_JOYSTICK;
5718}
5719
5720void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
5721 InputMapper::populateDeviceInfo(info);
5722
Jeff Brown6f2fba42011-02-19 01:08:02 -08005723 for (size_t i = 0; i < mAxes.size(); i++) {
5724 const Axis& axis = mAxes.valueAt(i);
Jeff Brownefd32662011-03-08 15:13:06 -08005725 info->addMotionRange(axis.axisInfo.axis, AINPUT_SOURCE_JOYSTICK,
5726 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08005727 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
Jeff Brownefd32662011-03-08 15:13:06 -08005728 info->addMotionRange(axis.axisInfo.highAxis, AINPUT_SOURCE_JOYSTICK,
5729 axis.min, axis.max, axis.flat, axis.fuzz);
Jeff Brown85297452011-03-04 13:07:49 -08005730 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005731 }
5732}
5733
5734void JoystickInputMapper::dump(String8& dump) {
5735 dump.append(INDENT2 "Joystick Input Mapper:\n");
5736
Jeff Brown6f2fba42011-02-19 01:08:02 -08005737 dump.append(INDENT3 "Axes:\n");
5738 size_t numAxes = mAxes.size();
5739 for (size_t i = 0; i < numAxes; i++) {
5740 const Axis& axis = mAxes.valueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005741 const char* label = getAxisLabel(axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005742 if (label) {
Jeff Brown85297452011-03-04 13:07:49 -08005743 dump.appendFormat(INDENT4 "%s", label);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005744 } else {
Jeff Brown85297452011-03-04 13:07:49 -08005745 dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005746 }
Jeff Brown85297452011-03-04 13:07:49 -08005747 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5748 label = getAxisLabel(axis.axisInfo.highAxis);
5749 if (label) {
5750 dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue);
5751 } else {
5752 dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis,
5753 axis.axisInfo.splitValue);
5754 }
5755 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
5756 dump.append(" (invert)");
5757 }
5758
5759 dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f\n",
5760 axis.min, axis.max, axis.flat, axis.fuzz);
5761 dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, "
5762 "highScale=%0.5f, highOffset=%0.5f\n",
5763 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Jeff Brownb3a2d132011-06-12 18:14:50 -07005764 dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
5765 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
Jeff Brown6f2fba42011-02-19 01:08:02 -08005766 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
Jeff Brownb3a2d132011-06-12 18:14:50 -07005767 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
Jeff Browncb1404e2011-01-15 18:14:15 -08005768 }
5769}
5770
Jeff Brown474dcb52011-06-14 20:22:50 -07005771void JoystickInputMapper::configure(const InputReaderConfiguration* config, uint32_t changes) {
5772 InputMapper::configure(config, changes);
Jeff Browncb1404e2011-01-15 18:14:15 -08005773
Jeff Brown474dcb52011-06-14 20:22:50 -07005774 if (!changes) { // first time only
5775 // Collect all axes.
5776 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
5777 RawAbsoluteAxisInfo rawAxisInfo;
5778 getEventHub()->getAbsoluteAxisInfo(getDeviceId(), abs, &rawAxisInfo);
5779 if (rawAxisInfo.valid) {
5780 // Map axis.
5781 AxisInfo axisInfo;
5782 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
5783 if (!explicitlyMapped) {
5784 // Axis is not explicitly mapped, will choose a generic axis later.
5785 axisInfo.mode = AxisInfo::MODE_NORMAL;
5786 axisInfo.axis = -1;
5787 }
5788
5789 // Apply flat override.
5790 int32_t rawFlat = axisInfo.flatOverride < 0
5791 ? rawAxisInfo.flat : axisInfo.flatOverride;
5792
5793 // Calculate scaling factors and limits.
5794 Axis axis;
5795 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
5796 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
5797 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
5798 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5799 scale, 0.0f, highScale, 0.0f,
5800 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
5801 } else if (isCenteredAxis(axisInfo.axis)) {
5802 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
5803 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
5804 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5805 scale, offset, scale, offset,
5806 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
5807 } else {
5808 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
5809 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
5810 scale, 0.0f, scale, 0.0f,
5811 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale);
5812 }
5813
5814 // To eliminate noise while the joystick is at rest, filter out small variations
5815 // in axis values up front.
5816 axis.filter = axis.flat * 0.25f;
5817
5818 mAxes.add(abs, axis);
Jeff Brown6f2fba42011-02-19 01:08:02 -08005819 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08005820 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08005821
Jeff Brown474dcb52011-06-14 20:22:50 -07005822 // If there are too many axes, start dropping them.
5823 // Prefer to keep explicitly mapped axes.
5824 if (mAxes.size() > PointerCoords::MAX_AXES) {
5825 LOGI("Joystick '%s' has %d axes but the framework only supports a maximum of %d.",
5826 getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES);
5827 pruneAxes(true);
5828 pruneAxes(false);
5829 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08005830
Jeff Brown474dcb52011-06-14 20:22:50 -07005831 // Assign generic axis ids to remaining axes.
5832 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
5833 size_t numAxes = mAxes.size();
5834 for (size_t i = 0; i < numAxes; i++) {
5835 Axis& axis = mAxes.editValueAt(i);
5836 if (axis.axisInfo.axis < 0) {
5837 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
5838 && haveAxis(nextGenericAxisId)) {
5839 nextGenericAxisId += 1;
5840 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08005841
Jeff Brown474dcb52011-06-14 20:22:50 -07005842 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
5843 axis.axisInfo.axis = nextGenericAxisId;
5844 nextGenericAxisId += 1;
5845 } else {
5846 LOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
5847 "have already been assigned to other axes.",
5848 getDeviceName().string(), mAxes.keyAt(i));
5849 mAxes.removeItemsAt(i--);
5850 numAxes -= 1;
5851 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08005852 }
5853 }
5854 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005855}
5856
Jeff Brown85297452011-03-04 13:07:49 -08005857bool JoystickInputMapper::haveAxis(int32_t axisId) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005858 size_t numAxes = mAxes.size();
5859 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005860 const Axis& axis = mAxes.valueAt(i);
5861 if (axis.axisInfo.axis == axisId
5862 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
5863 && axis.axisInfo.highAxis == axisId)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005864 return true;
5865 }
5866 }
5867 return false;
5868}
Jeff Browncb1404e2011-01-15 18:14:15 -08005869
Jeff Brown6f2fba42011-02-19 01:08:02 -08005870void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
5871 size_t i = mAxes.size();
5872 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
5873 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
5874 continue;
5875 }
5876 LOGI("Discarding joystick '%s' axis %d because there are too many axes.",
5877 getDeviceName().string(), mAxes.keyAt(i));
5878 mAxes.removeItemsAt(i);
5879 }
5880}
5881
5882bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
5883 switch (axis) {
5884 case AMOTION_EVENT_AXIS_X:
5885 case AMOTION_EVENT_AXIS_Y:
5886 case AMOTION_EVENT_AXIS_Z:
5887 case AMOTION_EVENT_AXIS_RX:
5888 case AMOTION_EVENT_AXIS_RY:
5889 case AMOTION_EVENT_AXIS_RZ:
5890 case AMOTION_EVENT_AXIS_HAT_X:
5891 case AMOTION_EVENT_AXIS_HAT_Y:
5892 case AMOTION_EVENT_AXIS_ORIENTATION:
Jeff Brown85297452011-03-04 13:07:49 -08005893 case AMOTION_EVENT_AXIS_RUDDER:
5894 case AMOTION_EVENT_AXIS_WHEEL:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005895 return true;
5896 default:
5897 return false;
5898 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005899}
5900
5901void JoystickInputMapper::reset() {
5902 // Recenter all axes.
5903 nsecs_t when = systemTime(SYSTEM_TIME_MONOTONIC);
Jeff Browncb1404e2011-01-15 18:14:15 -08005904
Jeff Brown6f2fba42011-02-19 01:08:02 -08005905 size_t numAxes = mAxes.size();
5906 for (size_t i = 0; i < numAxes; i++) {
5907 Axis& axis = mAxes.editValueAt(i);
Jeff Brown85297452011-03-04 13:07:49 -08005908 axis.resetValue();
Jeff Brown6f2fba42011-02-19 01:08:02 -08005909 }
5910
5911 sync(when, true /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005912
5913 InputMapper::reset();
5914}
5915
5916void JoystickInputMapper::process(const RawEvent* rawEvent) {
5917 switch (rawEvent->type) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005918 case EV_ABS: {
5919 ssize_t index = mAxes.indexOfKey(rawEvent->scanCode);
5920 if (index >= 0) {
5921 Axis& axis = mAxes.editValueAt(index);
Jeff Brown85297452011-03-04 13:07:49 -08005922 float newValue, highNewValue;
5923 switch (axis.axisInfo.mode) {
5924 case AxisInfo::MODE_INVERT:
5925 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
5926 * axis.scale + axis.offset;
5927 highNewValue = 0.0f;
5928 break;
5929 case AxisInfo::MODE_SPLIT:
5930 if (rawEvent->value < axis.axisInfo.splitValue) {
5931 newValue = (axis.axisInfo.splitValue - rawEvent->value)
5932 * axis.scale + axis.offset;
5933 highNewValue = 0.0f;
5934 } else if (rawEvent->value > axis.axisInfo.splitValue) {
5935 newValue = 0.0f;
5936 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
5937 * axis.highScale + axis.highOffset;
5938 } else {
5939 newValue = 0.0f;
5940 highNewValue = 0.0f;
5941 }
5942 break;
5943 default:
5944 newValue = rawEvent->value * axis.scale + axis.offset;
5945 highNewValue = 0.0f;
5946 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005947 }
Jeff Brown85297452011-03-04 13:07:49 -08005948 axis.newValue = newValue;
5949 axis.highNewValue = highNewValue;
Jeff Browncb1404e2011-01-15 18:14:15 -08005950 }
5951 break;
Jeff Brown6f2fba42011-02-19 01:08:02 -08005952 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005953
5954 case EV_SYN:
5955 switch (rawEvent->scanCode) {
5956 case SYN_REPORT:
Jeff Brown6f2fba42011-02-19 01:08:02 -08005957 sync(rawEvent->when, false /*force*/);
Jeff Browncb1404e2011-01-15 18:14:15 -08005958 break;
5959 }
5960 break;
5961 }
5962}
5963
Jeff Brown6f2fba42011-02-19 01:08:02 -08005964void JoystickInputMapper::sync(nsecs_t when, bool force) {
Jeff Brown85297452011-03-04 13:07:49 -08005965 if (!filterAxes(force)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08005966 return;
Jeff Browncb1404e2011-01-15 18:14:15 -08005967 }
5968
5969 int32_t metaState = mContext->getGlobalMetaState();
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07005970 int32_t buttonState = 0;
5971
5972 PointerProperties pointerProperties;
5973 pointerProperties.clear();
5974 pointerProperties.id = 0;
5975 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
Jeff Browncb1404e2011-01-15 18:14:15 -08005976
Jeff Brown6f2fba42011-02-19 01:08:02 -08005977 PointerCoords pointerCoords;
5978 pointerCoords.clear();
5979
5980 size_t numAxes = mAxes.size();
5981 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08005982 const Axis& axis = mAxes.valueAt(i);
5983 pointerCoords.setAxisValue(axis.axisInfo.axis, axis.currentValue);
5984 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
5985 pointerCoords.setAxisValue(axis.axisInfo.highAxis, axis.highCurrentValue);
5986 }
Jeff Browncb1404e2011-01-15 18:14:15 -08005987 }
5988
Jeff Brown56194eb2011-03-02 19:23:13 -08005989 // Moving a joystick axis should not wake the devide because joysticks can
5990 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
5991 // button will likely wake the device.
5992 // TODO: Use the input device configuration to control this behavior more finely.
5993 uint32_t policyFlags = 0;
5994
Jeff Brown56194eb2011-03-02 19:23:13 -08005995 getDispatcher()->notifyMotion(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags,
Jeff Brownfe9f8ab2011-05-06 18:20:01 -07005996 AMOTION_EVENT_ACTION_MOVE, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5997 1, &pointerProperties, &pointerCoords, 0, 0, 0);
Jeff Browncb1404e2011-01-15 18:14:15 -08005998}
5999
Jeff Brown85297452011-03-04 13:07:49 -08006000bool JoystickInputMapper::filterAxes(bool force) {
6001 bool atLeastOneSignificantChange = force;
Jeff Brown6f2fba42011-02-19 01:08:02 -08006002 size_t numAxes = mAxes.size();
6003 for (size_t i = 0; i < numAxes; i++) {
Jeff Brown85297452011-03-04 13:07:49 -08006004 Axis& axis = mAxes.editValueAt(i);
6005 if (force || hasValueChangedSignificantly(axis.filter,
6006 axis.newValue, axis.currentValue, axis.min, axis.max)) {
6007 axis.currentValue = axis.newValue;
6008 atLeastOneSignificantChange = true;
6009 }
6010 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
6011 if (force || hasValueChangedSignificantly(axis.filter,
6012 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
6013 axis.highCurrentValue = axis.highNewValue;
6014 atLeastOneSignificantChange = true;
6015 }
6016 }
6017 }
6018 return atLeastOneSignificantChange;
6019}
6020
6021bool JoystickInputMapper::hasValueChangedSignificantly(
6022 float filter, float newValue, float currentValue, float min, float max) {
6023 if (newValue != currentValue) {
6024 // Filter out small changes in value unless the value is converging on the axis
6025 // bounds or center point. This is intended to reduce the amount of information
6026 // sent to applications by particularly noisy joysticks (such as PS3).
6027 if (fabs(newValue - currentValue) > filter
6028 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
6029 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
6030 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
6031 return true;
6032 }
6033 }
6034 return false;
6035}
6036
6037bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
6038 float filter, float newValue, float currentValue, float thresholdValue) {
6039 float newDistance = fabs(newValue - thresholdValue);
6040 if (newDistance < filter) {
6041 float oldDistance = fabs(currentValue - thresholdValue);
6042 if (newDistance < oldDistance) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08006043 return true;
6044 }
Jeff Browncb1404e2011-01-15 18:14:15 -08006045 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08006046 return false;
Jeff Browncb1404e2011-01-15 18:14:15 -08006047}
6048
Jeff Brown46b9ac0a2010-04-22 18:58:52 -07006049} // namespace android