blob: d811dd7ba3c02f3d50f9cd7c78b55402a5e6c72c [file] [log] [blame]
Jeff Brown46b9ac02010-04-22 18:58:52 -07001//
2// Copyright 2010 The Android Open Source Project
3//
4// Provides a pipe-based transport for native events in the NDK.
5//
6#define LOG_TAG "Input"
7
8//#define LOG_NDEBUG 0
9
Jeff Brownace13b12011-03-09 17:39:48 -080010// Log debug messages about keymap probing.
Jeff Brown47e6b1b2010-11-29 17:37:49 -080011#define DEBUG_PROBE 0
12
Jeff Brownace13b12011-03-09 17:39:48 -080013// Log debug messages about velocity tracking.
14#define DEBUG_VELOCITY 0
15
Jeff Brown47e6b1b2010-11-29 17:37:49 -080016#include <stdlib.h>
17#include <unistd.h>
Jeff Brown90655042010-12-02 13:50:46 -080018#include <ctype.h>
Jeff Brown47e6b1b2010-11-29 17:37:49 -080019
Jeff Brown46b9ac02010-04-22 18:58:52 -070020#include <ui/Input.h>
21
Jeff Brown91c69ab2011-02-14 17:03:18 -080022#include <math.h>
23
24#ifdef HAVE_ANDROID_OS
25#include <binder/Parcel.h>
26
27#include "SkPoint.h"
28#include "SkMatrix.h"
29#include "SkScalar.h"
30#endif
31
Jeff Brown46b9ac02010-04-22 18:58:52 -070032namespace android {
33
Jeff Brown47e6b1b2010-11-29 17:37:49 -080034static const char* CONFIGURATION_FILE_DIR[] = {
35 "idc/",
36 "keylayout/",
37 "keychars/",
38};
39
40static const char* CONFIGURATION_FILE_EXTENSION[] = {
41 ".idc",
42 ".kl",
43 ".kcm",
44};
45
Jeff Brown90655042010-12-02 13:50:46 -080046static bool isValidNameChar(char ch) {
47 return isascii(ch) && (isdigit(ch) || isalpha(ch) || ch == '-' || ch == '_');
48}
49
Jeff Brown47e6b1b2010-11-29 17:37:49 -080050static void appendInputDeviceConfigurationFileRelativePath(String8& path,
51 const String8& name, InputDeviceConfigurationFileType type) {
52 path.append(CONFIGURATION_FILE_DIR[type]);
53 for (size_t i = 0; i < name.length(); i++) {
54 char ch = name[i];
Jeff Brown90655042010-12-02 13:50:46 -080055 if (!isValidNameChar(ch)) {
Jeff Brown47e6b1b2010-11-29 17:37:49 -080056 ch = '_';
57 }
58 path.append(&ch, 1);
59 }
60 path.append(CONFIGURATION_FILE_EXTENSION[type]);
61}
62
Jeff Brown90655042010-12-02 13:50:46 -080063String8 getInputDeviceConfigurationFilePathByDeviceIdentifier(
64 const InputDeviceIdentifier& deviceIdentifier,
65 InputDeviceConfigurationFileType type) {
66 if (deviceIdentifier.vendor !=0 && deviceIdentifier.product != 0) {
67 if (deviceIdentifier.version != 0) {
68 // Try vendor product version.
69 String8 versionPath(getInputDeviceConfigurationFilePathByName(
70 String8::format("Vendor_%04x_Product_%04x_Version_%04x",
71 deviceIdentifier.vendor, deviceIdentifier.product,
72 deviceIdentifier.version),
73 type));
74 if (!versionPath.isEmpty()) {
75 return versionPath;
76 }
77 }
78
79 // Try vendor product.
80 String8 productPath(getInputDeviceConfigurationFilePathByName(
81 String8::format("Vendor_%04x_Product_%04x",
82 deviceIdentifier.vendor, deviceIdentifier.product),
83 type));
84 if (!productPath.isEmpty()) {
85 return productPath;
86 }
87 }
88
89 // Try device name.
90 return getInputDeviceConfigurationFilePathByName(deviceIdentifier.name, type);
91}
92
93String8 getInputDeviceConfigurationFilePathByName(
Jeff Brown47e6b1b2010-11-29 17:37:49 -080094 const String8& name, InputDeviceConfigurationFileType type) {
95 // Search system repository.
96 String8 path;
97 path.setTo(getenv("ANDROID_ROOT"));
98 path.append("/usr/");
99 appendInputDeviceConfigurationFileRelativePath(path, name, type);
100#if DEBUG_PROBE
101 LOGD("Probing for system provided input device configuration file: path='%s'", path.string());
102#endif
103 if (!access(path.string(), R_OK)) {
104#if DEBUG_PROBE
105 LOGD("Found");
106#endif
107 return path;
108 }
109
110 // Search user repository.
111 // TODO Should only look here if not in safe mode.
112 path.setTo(getenv("ANDROID_DATA"));
113 path.append("/system/devices/");
114 appendInputDeviceConfigurationFileRelativePath(path, name, type);
115#if DEBUG_PROBE
116 LOGD("Probing for system user input device configuration file: path='%s'", path.string());
117#endif
118 if (!access(path.string(), R_OK)) {
119#if DEBUG_PROBE
120 LOGD("Found");
121#endif
122 return path;
123 }
124
125 // Not found.
126#if DEBUG_PROBE
127 LOGD("Probe failed to find input device configuration file: name='%s', type=%d",
128 name.string(), type);
129#endif
130 return String8();
131}
132
133
134// --- InputEvent ---
Jeff Brown46b9ac02010-04-22 18:58:52 -0700135
Jeff Brownc5ed5912010-07-14 18:48:53 -0700136void InputEvent::initialize(int32_t deviceId, int32_t source) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700137 mDeviceId = deviceId;
Jeff Brownc5ed5912010-07-14 18:48:53 -0700138 mSource = source;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700139}
140
Dianne Hackborn2c6081c2010-07-15 17:44:53 -0700141void InputEvent::initialize(const InputEvent& from) {
142 mDeviceId = from.mDeviceId;
143 mSource = from.mSource;
144}
145
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800146// --- KeyEvent ---
Jeff Brown46b9ac02010-04-22 18:58:52 -0700147
Dianne Hackborn3c80a4a2010-06-29 19:20:40 -0700148bool KeyEvent::hasDefaultAction(int32_t keyCode) {
149 switch (keyCode) {
Jeff Brownfd035822010-06-30 16:10:35 -0700150 case AKEYCODE_HOME:
151 case AKEYCODE_BACK:
152 case AKEYCODE_CALL:
153 case AKEYCODE_ENDCALL:
154 case AKEYCODE_VOLUME_UP:
155 case AKEYCODE_VOLUME_DOWN:
Jeff Brownb0418da2010-11-01 15:24:01 -0700156 case AKEYCODE_VOLUME_MUTE:
Jeff Brownfd035822010-06-30 16:10:35 -0700157 case AKEYCODE_POWER:
158 case AKEYCODE_CAMERA:
159 case AKEYCODE_HEADSETHOOK:
160 case AKEYCODE_MENU:
161 case AKEYCODE_NOTIFICATION:
162 case AKEYCODE_FOCUS:
163 case AKEYCODE_SEARCH:
Jeff Brownb0418da2010-11-01 15:24:01 -0700164 case AKEYCODE_MEDIA_PLAY:
165 case AKEYCODE_MEDIA_PAUSE:
Jeff Brownfd035822010-06-30 16:10:35 -0700166 case AKEYCODE_MEDIA_PLAY_PAUSE:
167 case AKEYCODE_MEDIA_STOP:
168 case AKEYCODE_MEDIA_NEXT:
169 case AKEYCODE_MEDIA_PREVIOUS:
170 case AKEYCODE_MEDIA_REWIND:
Jeff Brownb0418da2010-11-01 15:24:01 -0700171 case AKEYCODE_MEDIA_RECORD:
Jeff Brownfd035822010-06-30 16:10:35 -0700172 case AKEYCODE_MEDIA_FAST_FORWARD:
173 case AKEYCODE_MUTE:
Dianne Hackborn3c80a4a2010-06-29 19:20:40 -0700174 return true;
175 }
176
177 return false;
178}
179
180bool KeyEvent::hasDefaultAction() const {
181 return hasDefaultAction(getKeyCode());
182}
183
184bool KeyEvent::isSystemKey(int32_t keyCode) {
185 switch (keyCode) {
Jeff Brownfd035822010-06-30 16:10:35 -0700186 case AKEYCODE_MENU:
187 case AKEYCODE_SOFT_RIGHT:
188 case AKEYCODE_HOME:
189 case AKEYCODE_BACK:
190 case AKEYCODE_CALL:
191 case AKEYCODE_ENDCALL:
192 case AKEYCODE_VOLUME_UP:
193 case AKEYCODE_VOLUME_DOWN:
Jeff Brownb0418da2010-11-01 15:24:01 -0700194 case AKEYCODE_VOLUME_MUTE:
Jeff Brownfd035822010-06-30 16:10:35 -0700195 case AKEYCODE_MUTE:
196 case AKEYCODE_POWER:
197 case AKEYCODE_HEADSETHOOK:
Jeff Brownb0418da2010-11-01 15:24:01 -0700198 case AKEYCODE_MEDIA_PLAY:
199 case AKEYCODE_MEDIA_PAUSE:
Jeff Brownfd035822010-06-30 16:10:35 -0700200 case AKEYCODE_MEDIA_PLAY_PAUSE:
201 case AKEYCODE_MEDIA_STOP:
202 case AKEYCODE_MEDIA_NEXT:
203 case AKEYCODE_MEDIA_PREVIOUS:
204 case AKEYCODE_MEDIA_REWIND:
Jeff Brownb0418da2010-11-01 15:24:01 -0700205 case AKEYCODE_MEDIA_RECORD:
Jeff Brownfd035822010-06-30 16:10:35 -0700206 case AKEYCODE_MEDIA_FAST_FORWARD:
207 case AKEYCODE_CAMERA:
208 case AKEYCODE_FOCUS:
209 case AKEYCODE_SEARCH:
Dianne Hackborn3c80a4a2010-06-29 19:20:40 -0700210 return true;
211 }
212
213 return false;
214}
215
216bool KeyEvent::isSystemKey() const {
217 return isSystemKey(getKeyCode());
218}
219
Jeff Brown46b9ac02010-04-22 18:58:52 -0700220void KeyEvent::initialize(
221 int32_t deviceId,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700222 int32_t source,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700223 int32_t action,
224 int32_t flags,
225 int32_t keyCode,
226 int32_t scanCode,
227 int32_t metaState,
228 int32_t repeatCount,
229 nsecs_t downTime,
230 nsecs_t eventTime) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700231 InputEvent::initialize(deviceId, source);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700232 mAction = action;
233 mFlags = flags;
234 mKeyCode = keyCode;
235 mScanCode = scanCode;
236 mMetaState = metaState;
237 mRepeatCount = repeatCount;
238 mDownTime = downTime;
239 mEventTime = eventTime;
240}
241
Dianne Hackborn2c6081c2010-07-15 17:44:53 -0700242void KeyEvent::initialize(const KeyEvent& from) {
243 InputEvent::initialize(from);
244 mAction = from.mAction;
245 mFlags = from.mFlags;
246 mKeyCode = from.mKeyCode;
247 mScanCode = from.mScanCode;
248 mMetaState = from.mMetaState;
249 mRepeatCount = from.mRepeatCount;
250 mDownTime = from.mDownTime;
251 mEventTime = from.mEventTime;
252}
253
Jeff Brown91c69ab2011-02-14 17:03:18 -0800254
255// --- PointerCoords ---
256
Jeff Brown6f2fba42011-02-19 01:08:02 -0800257float PointerCoords::getAxisValue(int32_t axis) const {
258 if (axis < 0 || axis > 63) {
259 return 0;
260 }
261
262 uint64_t axisBit = 1LL << axis;
263 if (!(bits & axisBit)) {
264 return 0;
265 }
266 uint32_t index = __builtin_popcountll(bits & (axisBit - 1LL));
267 return values[index];
268}
269
270status_t PointerCoords::setAxisValue(int32_t axis, float value) {
271 if (axis < 0 || axis > 63) {
272 return NAME_NOT_FOUND;
273 }
274
275 uint64_t axisBit = 1LL << axis;
276 uint32_t index = __builtin_popcountll(bits & (axisBit - 1LL));
277 if (!(bits & axisBit)) {
278 uint32_t count = __builtin_popcountll(bits);
279 if (count >= MAX_AXES) {
280 tooManyAxes(axis);
281 return NO_MEMORY;
282 }
283 bits |= axisBit;
284 for (uint32_t i = count; i > index; i--) {
285 values[i] = values[i - 1];
286 }
287 }
288 values[index] = value;
289 return OK;
290}
291
292float* PointerCoords::editAxisValue(int32_t axis) {
293 if (axis < 0 || axis > 63) {
294 return NULL;
295 }
296
297 uint64_t axisBit = 1LL << axis;
298 if (!(bits & axisBit)) {
299 return NULL;
300 }
301 uint32_t index = __builtin_popcountll(bits & (axisBit - 1LL));
302 return &values[index];
303}
304
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400305static inline void scaleAxisValue(PointerCoords& c, int axis, float scaleFactor) {
306 float* value = c.editAxisValue(axis);
307 if (value) {
308 *value *= scaleFactor;
309 }
310}
311
312void PointerCoords::scale(float scaleFactor) {
313 // No need to scale pressure or size since they are normalized.
314 // No need to scale orientation since it is meaningless to do so.
315 scaleAxisValue(*this, AMOTION_EVENT_AXIS_X, scaleFactor);
316 scaleAxisValue(*this, AMOTION_EVENT_AXIS_Y, scaleFactor);
317 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOUCH_MAJOR, scaleFactor);
318 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOUCH_MINOR, scaleFactor);
319 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOOL_MAJOR, scaleFactor);
320 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOOL_MINOR, scaleFactor);
321}
322
Jeff Brown91c69ab2011-02-14 17:03:18 -0800323#ifdef HAVE_ANDROID_OS
324status_t PointerCoords::readFromParcel(Parcel* parcel) {
Jeff Brown6f2fba42011-02-19 01:08:02 -0800325 bits = parcel->readInt64();
Jeff Brown91c69ab2011-02-14 17:03:18 -0800326
Jeff Brown6f2fba42011-02-19 01:08:02 -0800327 uint32_t count = __builtin_popcountll(bits);
Jeff Brown91c69ab2011-02-14 17:03:18 -0800328 if (count > MAX_AXES) {
329 return BAD_VALUE;
330 }
331
332 for (uint32_t i = 0; i < count; i++) {
333 values[i] = parcel->readInt32();
334 }
335 return OK;
336}
337
338status_t PointerCoords::writeToParcel(Parcel* parcel) const {
Jeff Brown6f2fba42011-02-19 01:08:02 -0800339 parcel->writeInt64(bits);
Jeff Brown91c69ab2011-02-14 17:03:18 -0800340
Jeff Brown6f2fba42011-02-19 01:08:02 -0800341 uint32_t count = __builtin_popcountll(bits);
Jeff Brown91c69ab2011-02-14 17:03:18 -0800342 for (uint32_t i = 0; i < count; i++) {
343 parcel->writeInt32(values[i]);
344 }
345 return OK;
346}
347#endif
348
349void PointerCoords::tooManyAxes(int axis) {
350 LOGW("Could not set value for axis %d because the PointerCoords structure is full and "
351 "cannot contain more than %d axis values.", axis, int(MAX_AXES));
352}
353
Jeff Brownace13b12011-03-09 17:39:48 -0800354bool PointerCoords::operator==(const PointerCoords& other) const {
355 if (bits != other.bits) {
356 return false;
357 }
358 uint32_t count = __builtin_popcountll(bits);
359 for (uint32_t i = 0; i < count; i++) {
360 if (values[i] != other.values[i]) {
361 return false;
362 }
363 }
364 return true;
365}
366
367void PointerCoords::copyFrom(const PointerCoords& other) {
368 bits = other.bits;
369 uint32_t count = __builtin_popcountll(bits);
370 for (uint32_t i = 0; i < count; i++) {
371 values[i] = other.values[i];
372 }
373}
374
Jeff Brown91c69ab2011-02-14 17:03:18 -0800375
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800376// --- MotionEvent ---
Jeff Brown46b9ac02010-04-22 18:58:52 -0700377
378void MotionEvent::initialize(
379 int32_t deviceId,
Jeff Brownc5ed5912010-07-14 18:48:53 -0700380 int32_t source,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700381 int32_t action,
Jeff Brown85a31762010-09-01 17:01:00 -0700382 int32_t flags,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700383 int32_t edgeFlags,
384 int32_t metaState,
Jeff Brown5c225b12010-06-16 01:53:36 -0700385 float xOffset,
386 float yOffset,
Jeff Brown46b9ac02010-04-22 18:58:52 -0700387 float xPrecision,
388 float yPrecision,
389 nsecs_t downTime,
390 nsecs_t eventTime,
391 size_t pointerCount,
392 const int32_t* pointerIds,
393 const PointerCoords* pointerCoords) {
Jeff Brownc5ed5912010-07-14 18:48:53 -0700394 InputEvent::initialize(deviceId, source);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700395 mAction = action;
Jeff Brown85a31762010-09-01 17:01:00 -0700396 mFlags = flags;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700397 mEdgeFlags = edgeFlags;
398 mMetaState = metaState;
Jeff Brown5c225b12010-06-16 01:53:36 -0700399 mXOffset = xOffset;
400 mYOffset = yOffset;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700401 mXPrecision = xPrecision;
402 mYPrecision = yPrecision;
403 mDownTime = downTime;
404 mPointerIds.clear();
405 mPointerIds.appendArray(pointerIds, pointerCount);
406 mSampleEventTimes.clear();
407 mSamplePointerCoords.clear();
408 addSample(eventTime, pointerCoords);
409}
410
Jeff Brown91c69ab2011-02-14 17:03:18 -0800411void MotionEvent::copyFrom(const MotionEvent* other, bool keepHistory) {
412 InputEvent::initialize(other->mDeviceId, other->mSource);
413 mAction = other->mAction;
414 mFlags = other->mFlags;
415 mEdgeFlags = other->mEdgeFlags;
416 mMetaState = other->mMetaState;
417 mXOffset = other->mXOffset;
418 mYOffset = other->mYOffset;
419 mXPrecision = other->mXPrecision;
420 mYPrecision = other->mYPrecision;
421 mDownTime = other->mDownTime;
422 mPointerIds = other->mPointerIds;
423
424 if (keepHistory) {
425 mSampleEventTimes = other->mSampleEventTimes;
426 mSamplePointerCoords = other->mSamplePointerCoords;
427 } else {
428 mSampleEventTimes.clear();
429 mSampleEventTimes.push(other->getEventTime());
430 mSamplePointerCoords.clear();
431 size_t pointerCount = other->getPointerCount();
432 size_t historySize = other->getHistorySize();
433 mSamplePointerCoords.appendArray(other->mSamplePointerCoords.array()
434 + (historySize * pointerCount), pointerCount);
435 }
436}
437
Jeff Brown46b9ac02010-04-22 18:58:52 -0700438void MotionEvent::addSample(
439 int64_t eventTime,
440 const PointerCoords* pointerCoords) {
441 mSampleEventTimes.push(eventTime);
442 mSamplePointerCoords.appendArray(pointerCoords, getPointerCount());
443}
444
Jeff Brown91c69ab2011-02-14 17:03:18 -0800445const PointerCoords* MotionEvent::getRawPointerCoords(size_t pointerIndex) const {
446 return &mSamplePointerCoords[getHistorySize() * getPointerCount() + pointerIndex];
447}
448
449float MotionEvent::getRawAxisValue(int32_t axis, size_t pointerIndex) const {
450 return getRawPointerCoords(pointerIndex)->getAxisValue(axis);
451}
452
453float MotionEvent::getAxisValue(int32_t axis, size_t pointerIndex) const {
454 float value = getRawPointerCoords(pointerIndex)->getAxisValue(axis);
455 switch (axis) {
Jeff Brownebbd5d12011-02-17 13:01:34 -0800456 case AMOTION_EVENT_AXIS_X:
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400457 return value + mXOffset;
Jeff Brownebbd5d12011-02-17 13:01:34 -0800458 case AMOTION_EVENT_AXIS_Y:
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400459 return value + mYOffset;
Jeff Brown91c69ab2011-02-14 17:03:18 -0800460 }
461 return value;
462}
463
464const PointerCoords* MotionEvent::getHistoricalRawPointerCoords(
465 size_t pointerIndex, size_t historicalIndex) const {
466 return &mSamplePointerCoords[historicalIndex * getPointerCount() + pointerIndex];
467}
468
469float MotionEvent::getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex,
470 size_t historicalIndex) const {
471 return getHistoricalRawPointerCoords(pointerIndex, historicalIndex)->getAxisValue(axis);
472}
473
474float MotionEvent::getHistoricalAxisValue(int32_t axis, size_t pointerIndex,
475 size_t historicalIndex) const {
476 float value = getHistoricalRawPointerCoords(pointerIndex, historicalIndex)->getAxisValue(axis);
477 switch (axis) {
Jeff Brownebbd5d12011-02-17 13:01:34 -0800478 case AMOTION_EVENT_AXIS_X:
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400479 return value + mXOffset;
Jeff Brownebbd5d12011-02-17 13:01:34 -0800480 case AMOTION_EVENT_AXIS_Y:
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400481 return value + mYOffset;
Jeff Brown91c69ab2011-02-14 17:03:18 -0800482 }
483 return value;
484}
485
Jeff Brown2ed24622011-03-14 19:39:54 -0700486ssize_t MotionEvent::findPointerIndex(int32_t pointerId) const {
487 size_t pointerCount = mPointerIds.size();
488 for (size_t i = 0; i < pointerCount; i++) {
489 if (mPointerIds.itemAt(i) == pointerId) {
490 return i;
491 }
492 }
493 return -1;
494}
495
Jeff Brown46b9ac02010-04-22 18:58:52 -0700496void MotionEvent::offsetLocation(float xOffset, float yOffset) {
Jeff Brown5c225b12010-06-16 01:53:36 -0700497 mXOffset += xOffset;
498 mYOffset += yOffset;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700499}
500
Jeff Brown91c69ab2011-02-14 17:03:18 -0800501void MotionEvent::scale(float scaleFactor) {
502 mXOffset *= scaleFactor;
503 mYOffset *= scaleFactor;
504 mXPrecision *= scaleFactor;
505 mYPrecision *= scaleFactor;
506
507 size_t numSamples = mSamplePointerCoords.size();
508 for (size_t i = 0; i < numSamples; i++) {
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400509 mSamplePointerCoords.editItemAt(i).scale(scaleFactor);
Jeff Brown91c69ab2011-02-14 17:03:18 -0800510 }
511}
512
513#ifdef HAVE_ANDROID_OS
514static inline float transformAngle(const SkMatrix* matrix, float angleRadians) {
515 // Construct and transform a vector oriented at the specified clockwise angle from vertical.
516 // Coordinate system: down is increasing Y, right is increasing X.
517 SkPoint vector;
518 vector.fX = SkFloatToScalar(sinf(angleRadians));
519 vector.fY = SkFloatToScalar(-cosf(angleRadians));
520 matrix->mapVectors(& vector, 1);
521
522 // Derive the transformed vector's clockwise angle from vertical.
523 float result = atan2f(SkScalarToFloat(vector.fX), SkScalarToFloat(-vector.fY));
524 if (result < - M_PI_2) {
525 result += M_PI;
526 } else if (result > M_PI_2) {
527 result -= M_PI;
528 }
529 return result;
530}
531
532void MotionEvent::transform(const SkMatrix* matrix) {
533 float oldXOffset = mXOffset;
534 float oldYOffset = mYOffset;
535
536 // The tricky part of this implementation is to preserve the value of
537 // rawX and rawY. So we apply the transformation to the first point
538 // then derive an appropriate new X/Y offset that will preserve rawX and rawY.
539 SkPoint point;
540 float rawX = getRawX(0);
541 float rawY = getRawY(0);
542 matrix->mapXY(SkFloatToScalar(rawX + oldXOffset), SkFloatToScalar(rawY + oldYOffset),
543 & point);
544 float newX = SkScalarToFloat(point.fX);
545 float newY = SkScalarToFloat(point.fY);
546 float newXOffset = newX - rawX;
547 float newYOffset = newY - rawY;
548
549 mXOffset = newXOffset;
550 mYOffset = newYOffset;
551
552 // Apply the transformation to all samples.
553 size_t numSamples = mSamplePointerCoords.size();
554 for (size_t i = 0; i < numSamples; i++) {
555 PointerCoords& c = mSamplePointerCoords.editItemAt(i);
Jeff Brownebbd5d12011-02-17 13:01:34 -0800556 float* xPtr = c.editAxisValue(AMOTION_EVENT_AXIS_X);
557 float* yPtr = c.editAxisValue(AMOTION_EVENT_AXIS_Y);
Jeff Brown91c69ab2011-02-14 17:03:18 -0800558 if (xPtr && yPtr) {
559 float x = *xPtr + oldXOffset;
560 float y = *yPtr + oldYOffset;
561 matrix->mapXY(SkFloatToScalar(x), SkFloatToScalar(y), & point);
562 *xPtr = SkScalarToFloat(point.fX) - newXOffset;
563 *yPtr = SkScalarToFloat(point.fY) - newYOffset;
564 }
565
Jeff Brownebbd5d12011-02-17 13:01:34 -0800566 float* orientationPtr = c.editAxisValue(AMOTION_EVENT_AXIS_ORIENTATION);
Jeff Brown91c69ab2011-02-14 17:03:18 -0800567 if (orientationPtr) {
568 *orientationPtr = transformAngle(matrix, *orientationPtr);
569 }
570 }
571}
572
573status_t MotionEvent::readFromParcel(Parcel* parcel) {
574 size_t pointerCount = parcel->readInt32();
575 size_t sampleCount = parcel->readInt32();
576 if (pointerCount == 0 || pointerCount > MAX_POINTERS || sampleCount == 0) {
577 return BAD_VALUE;
578 }
579
580 mDeviceId = parcel->readInt32();
581 mSource = parcel->readInt32();
582 mAction = parcel->readInt32();
583 mFlags = parcel->readInt32();
584 mEdgeFlags = parcel->readInt32();
585 mMetaState = parcel->readInt32();
586 mXOffset = parcel->readFloat();
587 mYOffset = parcel->readFloat();
588 mXPrecision = parcel->readFloat();
589 mYPrecision = parcel->readFloat();
590 mDownTime = parcel->readInt64();
591
592 mPointerIds.clear();
593 mPointerIds.setCapacity(pointerCount);
594 mSampleEventTimes.clear();
595 mSampleEventTimes.setCapacity(sampleCount);
596 mSamplePointerCoords.clear();
597 mSamplePointerCoords.setCapacity(sampleCount * pointerCount);
598
599 for (size_t i = 0; i < pointerCount; i++) {
600 mPointerIds.push(parcel->readInt32());
601 }
602
603 while (sampleCount-- > 0) {
604 mSampleEventTimes.push(parcel->readInt64());
605 for (size_t i = 0; i < pointerCount; i++) {
606 mSamplePointerCoords.push();
607 status_t status = mSamplePointerCoords.editTop().readFromParcel(parcel);
Jeff Brownebbd5d12011-02-17 13:01:34 -0800608 if (status) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800609 return status;
610 }
611 }
612 }
613 return OK;
614}
615
616status_t MotionEvent::writeToParcel(Parcel* parcel) const {
617 size_t pointerCount = mPointerIds.size();
618 size_t sampleCount = mSampleEventTimes.size();
619
620 parcel->writeInt32(pointerCount);
621 parcel->writeInt32(sampleCount);
622
623 parcel->writeInt32(mDeviceId);
624 parcel->writeInt32(mSource);
625 parcel->writeInt32(mAction);
626 parcel->writeInt32(mFlags);
627 parcel->writeInt32(mEdgeFlags);
628 parcel->writeInt32(mMetaState);
629 parcel->writeFloat(mXOffset);
630 parcel->writeFloat(mYOffset);
631 parcel->writeFloat(mXPrecision);
632 parcel->writeFloat(mYPrecision);
633 parcel->writeInt64(mDownTime);
634
635 for (size_t i = 0; i < pointerCount; i++) {
636 parcel->writeInt32(mPointerIds.itemAt(i));
637 }
638
639 const PointerCoords* pc = mSamplePointerCoords.array();
640 for (size_t h = 0; h < sampleCount; h++) {
641 parcel->writeInt64(mSampleEventTimes.itemAt(h));
642 for (size_t i = 0; i < pointerCount; i++) {
643 status_t status = (pc++)->writeToParcel(parcel);
Jeff Brownebbd5d12011-02-17 13:01:34 -0800644 if (status) {
Jeff Brown91c69ab2011-02-14 17:03:18 -0800645 return status;
646 }
647 }
648 }
649 return OK;
650}
651#endif
652
Jeff Brown56194eb2011-03-02 19:23:13 -0800653bool MotionEvent::isTouchEvent(int32_t source, int32_t action) {
654 if (source & AINPUT_SOURCE_CLASS_POINTER) {
655 // Specifically excludes HOVER_MOVE and SCROLL.
656 switch (action & AMOTION_EVENT_ACTION_MASK) {
657 case AMOTION_EVENT_ACTION_DOWN:
658 case AMOTION_EVENT_ACTION_MOVE:
659 case AMOTION_EVENT_ACTION_UP:
660 case AMOTION_EVENT_ACTION_POINTER_DOWN:
661 case AMOTION_EVENT_ACTION_POINTER_UP:
662 case AMOTION_EVENT_ACTION_CANCEL:
663 case AMOTION_EVENT_ACTION_OUTSIDE:
664 return true;
665 }
666 }
667 return false;
668}
669
Jeff Brown91c69ab2011-02-14 17:03:18 -0800670
Jeff Brownace13b12011-03-09 17:39:48 -0800671// --- VelocityTracker ---
672
673VelocityTracker::VelocityTracker() {
674 clear();
675}
676
677void VelocityTracker::clear() {
678 mIndex = 0;
679 mMovements[0].idBits.clear();
Jeff Brown2ed24622011-03-14 19:39:54 -0700680 mActivePointerId = -1;
681}
682
683void VelocityTracker::clearPointers(BitSet32 idBits) {
684 BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value);
685 mMovements[mIndex].idBits = remainingIdBits;
686
687 if (mActivePointerId >= 0 && idBits.hasBit(mActivePointerId)) {
688 mActivePointerId = !remainingIdBits.isEmpty() ? remainingIdBits.firstMarkedBit() : -1;
689 }
Jeff Brownace13b12011-03-09 17:39:48 -0800690}
691
692void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions) {
693 if (++mIndex == HISTORY_SIZE) {
694 mIndex = 0;
695 }
Jeff Brown2ed24622011-03-14 19:39:54 -0700696
697 while (idBits.count() > MAX_POINTERS) {
698 idBits.clearBit(idBits.lastMarkedBit());
699 }
700
Jeff Brownace13b12011-03-09 17:39:48 -0800701 Movement& movement = mMovements[mIndex];
702 movement.eventTime = eventTime;
703 movement.idBits = idBits;
704 uint32_t count = idBits.count();
705 for (uint32_t i = 0; i < count; i++) {
706 movement.positions[i] = positions[i];
707 }
708
Jeff Brown2ed24622011-03-14 19:39:54 -0700709 if (mActivePointerId < 0 || !idBits.hasBit(mActivePointerId)) {
710 mActivePointerId = count != 0 ? idBits.firstMarkedBit() : -1;
711 }
712
Jeff Brownace13b12011-03-09 17:39:48 -0800713#if DEBUG_VELOCITY
Jeff Brown2ed24622011-03-14 19:39:54 -0700714 LOGD("VelocityTracker: addMovement eventTime=%lld, idBits=0x%08x, activePointerId=%d",
715 eventTime, idBits.value, mActivePointerId);
Jeff Brownace13b12011-03-09 17:39:48 -0800716 for (BitSet32 iterBits(idBits); !iterBits.isEmpty(); ) {
717 uint32_t id = iterBits.firstMarkedBit();
718 uint32_t index = idBits.getIndexOfBit(id);
719 iterBits.clearBit(id);
720 float vx, vy;
721 bool available = getVelocity(id, &vx, &vy);
722 if (available) {
Jeff Brown2ed24622011-03-14 19:39:54 -0700723 LOGD(" %d: position (%0.3f, %0.3f), vx=%0.3f, vy=%0.3f, speed=%0.3f",
Jeff Brownace13b12011-03-09 17:39:48 -0800724 id, positions[index].x, positions[index].y, vx, vy, sqrtf(vx * vx + vy * vy));
725 } else {
Jeff Brownb6110c22011-04-01 16:15:13 -0700726 LOG_ASSERT(vx == 0 && vy == 0);
Jeff Brownace13b12011-03-09 17:39:48 -0800727 LOGD(" %d: position (%0.3f, %0.3f), velocity not available",
728 id, positions[index].x, positions[index].y);
729 }
730 }
731#endif
732}
733
Jeff Brown2ed24622011-03-14 19:39:54 -0700734void VelocityTracker::addMovement(const MotionEvent* event) {
735 int32_t actionMasked = event->getActionMasked();
736
737 switch (actionMasked) {
738 case AMOTION_EVENT_ACTION_DOWN:
739 // Clear all pointers on down before adding the new movement.
740 clear();
741 break;
742 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
743 // Start a new movement trace for a pointer that just went down.
744 // We do this on down instead of on up because the client may want to query the
745 // final velocity for a pointer that just went up.
746 BitSet32 downIdBits;
747 downIdBits.markBit(event->getActionIndex());
748 clearPointers(downIdBits);
749 break;
750 }
751 case AMOTION_EVENT_ACTION_OUTSIDE:
752 case AMOTION_EVENT_ACTION_CANCEL:
753 case AMOTION_EVENT_ACTION_SCROLL:
754 case AMOTION_EVENT_ACTION_UP:
755 case AMOTION_EVENT_ACTION_POINTER_UP:
756 // Ignore these actions because they do not convey any new information about
757 // pointer movement. We also want to preserve the last known velocity of the pointers.
758 // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position
759 // of the pointers that went up. ACTION_POINTER_UP does include the new position of
760 // pointers that remained down but we will also receive an ACTION_MOVE with this
761 // information if any of them actually moved. Since we don't know how many pointers
762 // will be going up at once it makes sense to just wait for the following ACTION_MOVE
763 // before adding the movement.
764 return;
765 }
766
767 size_t pointerCount = event->getPointerCount();
768 if (pointerCount > MAX_POINTERS) {
769 pointerCount = MAX_POINTERS;
770 }
771
772 BitSet32 idBits;
773 for (size_t i = 0; i < pointerCount; i++) {
774 idBits.markBit(event->getPointerId(i));
775 }
776
777 nsecs_t eventTime;
778 Position positions[pointerCount];
779
780 size_t historySize = event->getHistorySize();
781 for (size_t h = 0; h < historySize; h++) {
782 eventTime = event->getHistoricalEventTime(h);
783 for (size_t i = 0; i < pointerCount; i++) {
784 positions[i].x = event->getHistoricalX(i, h);
785 positions[i].y = event->getHistoricalY(i, h);
786 }
787 addMovement(eventTime, idBits, positions);
788 }
789
790 eventTime = event->getEventTime();
791 for (size_t i = 0; i < pointerCount; i++) {
792 positions[i].x = event->getX(i);
793 positions[i].y = event->getY(i);
794 }
795 addMovement(eventTime, idBits, positions);
796}
797
Jeff Brownace13b12011-03-09 17:39:48 -0800798bool VelocityTracker::getVelocity(uint32_t id, float* outVx, float* outVy) const {
799 const Movement& newestMovement = mMovements[mIndex];
800 if (newestMovement.idBits.hasBit(id)) {
801 // Find the oldest sample that contains the pointer and that is not older than MAX_AGE.
802 nsecs_t minTime = newestMovement.eventTime - MAX_AGE;
803 uint32_t oldestIndex = mIndex;
804 uint32_t numTouches = 1;
805 do {
806 uint32_t nextOldestIndex = (oldestIndex == 0 ? HISTORY_SIZE : oldestIndex) - 1;
807 const Movement& nextOldestMovement = mMovements[nextOldestIndex];
808 if (!nextOldestMovement.idBits.hasBit(id)
809 || nextOldestMovement.eventTime < minTime) {
810 break;
811 }
812 oldestIndex = nextOldestIndex;
813 } while (++numTouches < HISTORY_SIZE);
814
Jeff Brown2ed24622011-03-14 19:39:54 -0700815 // Calculate an exponentially weighted moving average of the velocity estimate
816 // at different points in time measured relative to the oldest sample.
817 // This is essentially an IIR filter. Newer samples are weighted more heavily
818 // than older samples. Samples at equal time points are weighted more or less
819 // equally.
Jeff Brownace13b12011-03-09 17:39:48 -0800820 //
Jeff Brown2ed24622011-03-14 19:39:54 -0700821 // One tricky problem is that the sample data may be poorly conditioned.
Jeff Brownace13b12011-03-09 17:39:48 -0800822 // Sometimes samples arrive very close together in time which can cause us to
823 // overestimate the velocity at that time point. Most samples might be measured
Jeff Brown2ed24622011-03-14 19:39:54 -0700824 // 16ms apart but some consecutive samples could be only 0.5sm apart because
825 // the hardware or driver reports them irregularly or in bursts.
Jeff Brownace13b12011-03-09 17:39:48 -0800826 float accumVx = 0;
827 float accumVy = 0;
828 uint32_t index = oldestIndex;
829 uint32_t samplesUsed = 0;
830 const Movement& oldestMovement = mMovements[oldestIndex];
831 const Position& oldestPosition =
832 oldestMovement.positions[oldestMovement.idBits.getIndexOfBit(id)];
Jeff Brown2ed24622011-03-14 19:39:54 -0700833 nsecs_t lastDuration = 0;
Jeff Brown2352b972011-04-12 22:39:53 -0700834
Jeff Brownace13b12011-03-09 17:39:48 -0800835 while (numTouches-- > 1) {
836 if (++index == HISTORY_SIZE) {
837 index = 0;
838 }
839 const Movement& movement = mMovements[index];
840 nsecs_t duration = movement.eventTime - oldestMovement.eventTime;
Jeff Brown2ed24622011-03-14 19:39:54 -0700841
842 // If the duration between samples is small, we may significantly overestimate
843 // the velocity. Consequently, we impose a minimum duration constraint on the
844 // samples that we include in the calculation.
845 if (duration >= MIN_DURATION) {
Jeff Brownace13b12011-03-09 17:39:48 -0800846 const Position& position = movement.positions[movement.idBits.getIndexOfBit(id)];
847 float scale = 1000000000.0f / duration; // one over time delta in seconds
848 float vx = (position.x - oldestPosition.x) * scale;
849 float vy = (position.y - oldestPosition.y) * scale;
Jeff Brown2ed24622011-03-14 19:39:54 -0700850
851 accumVx = (accumVx * lastDuration + vx * duration) / (duration + lastDuration);
852 accumVy = (accumVy * lastDuration + vy * duration) / (duration + lastDuration);
853
854 lastDuration = duration;
Jeff Brownace13b12011-03-09 17:39:48 -0800855 samplesUsed += 1;
856 }
857 }
858
859 // Make sure we used at least one sample.
860 if (samplesUsed != 0) {
Jeff Brown2352b972011-04-12 22:39:53 -0700861 // Scale the velocity linearly if the window of samples is small.
862 nsecs_t totalDuration = newestMovement.eventTime - oldestMovement.eventTime;
863 if (totalDuration < MIN_WINDOW) {
864 float scale = float(totalDuration) / float(MIN_WINDOW);
865 accumVx *= scale;
866 accumVy *= scale;
867 }
868
Jeff Brownace13b12011-03-09 17:39:48 -0800869 *outVx = accumVx;
870 *outVy = accumVy;
871 return true;
872 }
873 }
874
875 // No data available for this pointer.
876 *outVx = 0;
877 *outVy = 0;
878 return false;
879}
880
881
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800882// --- InputDeviceInfo ---
Jeff Brown6d0fec22010-07-23 21:28:06 -0700883
884InputDeviceInfo::InputDeviceInfo() {
885 initialize(-1, String8("uninitialized device info"));
886}
887
888InputDeviceInfo::InputDeviceInfo(const InputDeviceInfo& other) :
889 mId(other.mId), mName(other.mName), mSources(other.mSources),
890 mKeyboardType(other.mKeyboardType),
891 mMotionRanges(other.mMotionRanges) {
892}
893
894InputDeviceInfo::~InputDeviceInfo() {
895}
896
897void InputDeviceInfo::initialize(int32_t id, const String8& name) {
898 mId = id;
899 mName = name;
900 mSources = 0;
901 mKeyboardType = AINPUT_KEYBOARD_TYPE_NONE;
902 mMotionRanges.clear();
903}
904
Jeff Brownefd32662011-03-08 15:13:06 -0800905const InputDeviceInfo::MotionRange* InputDeviceInfo::getMotionRange(
906 int32_t axis, uint32_t source) const {
907 size_t numRanges = mMotionRanges.size();
908 for (size_t i = 0; i < numRanges; i++) {
909 const MotionRange& range = mMotionRanges.itemAt(i);
910 if (range.axis == axis && range.source == source) {
911 return &range;
912 }
913 }
914 return NULL;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700915}
916
917void InputDeviceInfo::addSource(uint32_t source) {
918 mSources |= source;
919}
920
Jeff Brownefd32662011-03-08 15:13:06 -0800921void InputDeviceInfo::addMotionRange(int32_t axis, uint32_t source, float min, float max,
Jeff Brown6d0fec22010-07-23 21:28:06 -0700922 float flat, float fuzz) {
Jeff Brownefd32662011-03-08 15:13:06 -0800923 MotionRange range = { axis, source, min, max, flat, fuzz };
924 mMotionRanges.add(range);
Jeff Brown6d0fec22010-07-23 21:28:06 -0700925}
926
Jeff Brownefd32662011-03-08 15:13:06 -0800927void InputDeviceInfo::addMotionRange(const MotionRange& range) {
928 mMotionRanges.add(range);
Jeff Brown6d0fec22010-07-23 21:28:06 -0700929}
930
Jeff Brown46b9ac02010-04-22 18:58:52 -0700931} // namespace android