blob: 0f13879ec0043883299feb65aa0eda70cb47d4f0 [file] [log] [blame]
Jeff Browne839a582010-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 Brown247da722011-03-09 17:39:48 -080010// Log debug messages about keymap probing.
Jeff Brown66888372010-11-29 17:37:49 -080011#define DEBUG_PROBE 0
12
Jeff Brown247da722011-03-09 17:39:48 -080013// Log debug messages about velocity tracking.
14#define DEBUG_VELOCITY 0
15
Jeff Brown66888372010-11-29 17:37:49 -080016#include <stdlib.h>
17#include <unistd.h>
Jeff Browndb360642010-12-02 13:50:46 -080018#include <ctype.h>
Jeff Brown66888372010-11-29 17:37:49 -080019
Jeff Browne839a582010-04-22 18:58:52 -070020#include <ui/Input.h>
21
Jeff Brown3e341462011-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 Browne839a582010-04-22 18:58:52 -070032namespace android {
33
Jeff Brown66888372010-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 Browndb360642010-12-02 13:50:46 -080046static bool isValidNameChar(char ch) {
47 return isascii(ch) && (isdigit(ch) || isalpha(ch) || ch == '-' || ch == '_');
48}
49
Jeff Brown66888372010-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 Browndb360642010-12-02 13:50:46 -080055 if (!isValidNameChar(ch)) {
Jeff Brown66888372010-11-29 17:37:49 -080056 ch = '_';
57 }
58 path.append(&ch, 1);
59 }
60 path.append(CONFIGURATION_FILE_EXTENSION[type]);
61}
62
Jeff Browndb360642010-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 Brown66888372010-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 Browne839a582010-04-22 18:58:52 -0700135
Jeff Brown5c1ed842010-07-14 18:48:53 -0700136void InputEvent::initialize(int32_t deviceId, int32_t source) {
Jeff Browne839a582010-04-22 18:58:52 -0700137 mDeviceId = deviceId;
Jeff Brown5c1ed842010-07-14 18:48:53 -0700138 mSource = source;
Jeff Browne839a582010-04-22 18:58:52 -0700139}
140
Dianne Hackborn0e885272010-07-15 17:44:53 -0700141void InputEvent::initialize(const InputEvent& from) {
142 mDeviceId = from.mDeviceId;
143 mSource = from.mSource;
144}
145
Jeff Brown66888372010-11-29 17:37:49 -0800146// --- KeyEvent ---
Jeff Browne839a582010-04-22 18:58:52 -0700147
Dianne Hackborn189ed232010-06-29 19:20:40 -0700148bool KeyEvent::hasDefaultAction(int32_t keyCode) {
149 switch (keyCode) {
Jeff Brown8575a872010-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 Brown7e5660f2010-11-01 15:24:01 -0700156 case AKEYCODE_VOLUME_MUTE:
Jeff Brown8575a872010-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 Brown7e5660f2010-11-01 15:24:01 -0700164 case AKEYCODE_MEDIA_PLAY:
165 case AKEYCODE_MEDIA_PAUSE:
Jeff Brown8575a872010-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 Brown7e5660f2010-11-01 15:24:01 -0700171 case AKEYCODE_MEDIA_RECORD:
Jeff Brown8575a872010-06-30 16:10:35 -0700172 case AKEYCODE_MEDIA_FAST_FORWARD:
173 case AKEYCODE_MUTE:
Dianne Hackborn189ed232010-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 Brown8575a872010-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 Brown7e5660f2010-11-01 15:24:01 -0700194 case AKEYCODE_VOLUME_MUTE:
Jeff Brown8575a872010-06-30 16:10:35 -0700195 case AKEYCODE_MUTE:
196 case AKEYCODE_POWER:
197 case AKEYCODE_HEADSETHOOK:
Jeff Brown7e5660f2010-11-01 15:24:01 -0700198 case AKEYCODE_MEDIA_PLAY:
199 case AKEYCODE_MEDIA_PAUSE:
Jeff Brown8575a872010-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 Brown7e5660f2010-11-01 15:24:01 -0700205 case AKEYCODE_MEDIA_RECORD:
Jeff Brown8575a872010-06-30 16:10:35 -0700206 case AKEYCODE_MEDIA_FAST_FORWARD:
207 case AKEYCODE_CAMERA:
208 case AKEYCODE_FOCUS:
209 case AKEYCODE_SEARCH:
Dianne Hackborn189ed232010-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 Browne839a582010-04-22 18:58:52 -0700220void KeyEvent::initialize(
221 int32_t deviceId,
Jeff Brown5c1ed842010-07-14 18:48:53 -0700222 int32_t source,
Jeff Browne839a582010-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 Brown5c1ed842010-07-14 18:48:53 -0700231 InputEvent::initialize(deviceId, source);
Jeff Browne839a582010-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 Hackborn0e885272010-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 Brown3e341462011-02-14 17:03:18 -0800254
255// --- PointerCoords ---
256
Jeff Brown3ea4de82011-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 Hackborn16fe3c22011-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 Brown3e341462011-02-14 17:03:18 -0800323#ifdef HAVE_ANDROID_OS
324status_t PointerCoords::readFromParcel(Parcel* parcel) {
Jeff Brown3ea4de82011-02-19 01:08:02 -0800325 bits = parcel->readInt64();
Jeff Brown3e341462011-02-14 17:03:18 -0800326
Jeff Brown3ea4de82011-02-19 01:08:02 -0800327 uint32_t count = __builtin_popcountll(bits);
Jeff Brown3e341462011-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 Brown3ea4de82011-02-19 01:08:02 -0800339 parcel->writeInt64(bits);
Jeff Brown3e341462011-02-14 17:03:18 -0800340
Jeff Brown3ea4de82011-02-19 01:08:02 -0800341 uint32_t count = __builtin_popcountll(bits);
Jeff Brown3e341462011-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 Brown247da722011-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 Brown3e341462011-02-14 17:03:18 -0800375
Jeff Brown66888372010-11-29 17:37:49 -0800376// --- MotionEvent ---
Jeff Browne839a582010-04-22 18:58:52 -0700377
378void MotionEvent::initialize(
379 int32_t deviceId,
Jeff Brown5c1ed842010-07-14 18:48:53 -0700380 int32_t source,
Jeff Browne839a582010-04-22 18:58:52 -0700381 int32_t action,
Jeff Brownaf30ff62010-09-01 17:01:00 -0700382 int32_t flags,
Jeff Browne839a582010-04-22 18:58:52 -0700383 int32_t edgeFlags,
384 int32_t metaState,
Jeff Brownf4a4ec22010-06-16 01:53:36 -0700385 float xOffset,
386 float yOffset,
Jeff Browne839a582010-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 Brown5c1ed842010-07-14 18:48:53 -0700394 InputEvent::initialize(deviceId, source);
Jeff Browne839a582010-04-22 18:58:52 -0700395 mAction = action;
Jeff Brownaf30ff62010-09-01 17:01:00 -0700396 mFlags = flags;
Jeff Browne839a582010-04-22 18:58:52 -0700397 mEdgeFlags = edgeFlags;
398 mMetaState = metaState;
Jeff Brownf4a4ec22010-06-16 01:53:36 -0700399 mXOffset = xOffset;
400 mYOffset = yOffset;
Jeff Browne839a582010-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 Brown3e341462011-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 Browne839a582010-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 Brown3e341462011-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 Brownb2d44352011-02-17 13:01:34 -0800456 case AMOTION_EVENT_AXIS_X:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400457 return value + mXOffset;
Jeff Brownb2d44352011-02-17 13:01:34 -0800458 case AMOTION_EVENT_AXIS_Y:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400459 return value + mYOffset;
Jeff Brown3e341462011-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 Brownb2d44352011-02-17 13:01:34 -0800478 case AMOTION_EVENT_AXIS_X:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400479 return value + mXOffset;
Jeff Brownb2d44352011-02-17 13:01:34 -0800480 case AMOTION_EVENT_AXIS_Y:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400481 return value + mYOffset;
Jeff Brown3e341462011-02-14 17:03:18 -0800482 }
483 return value;
484}
485
Jeff Browne839a582010-04-22 18:58:52 -0700486void MotionEvent::offsetLocation(float xOffset, float yOffset) {
Jeff Brownf4a4ec22010-06-16 01:53:36 -0700487 mXOffset += xOffset;
488 mYOffset += yOffset;
Jeff Browne839a582010-04-22 18:58:52 -0700489}
490
Jeff Brown3e341462011-02-14 17:03:18 -0800491void MotionEvent::scale(float scaleFactor) {
492 mXOffset *= scaleFactor;
493 mYOffset *= scaleFactor;
494 mXPrecision *= scaleFactor;
495 mYPrecision *= scaleFactor;
496
497 size_t numSamples = mSamplePointerCoords.size();
498 for (size_t i = 0; i < numSamples; i++) {
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400499 mSamplePointerCoords.editItemAt(i).scale(scaleFactor);
Jeff Brown3e341462011-02-14 17:03:18 -0800500 }
501}
502
503#ifdef HAVE_ANDROID_OS
504static inline float transformAngle(const SkMatrix* matrix, float angleRadians) {
505 // Construct and transform a vector oriented at the specified clockwise angle from vertical.
506 // Coordinate system: down is increasing Y, right is increasing X.
507 SkPoint vector;
508 vector.fX = SkFloatToScalar(sinf(angleRadians));
509 vector.fY = SkFloatToScalar(-cosf(angleRadians));
510 matrix->mapVectors(& vector, 1);
511
512 // Derive the transformed vector's clockwise angle from vertical.
513 float result = atan2f(SkScalarToFloat(vector.fX), SkScalarToFloat(-vector.fY));
514 if (result < - M_PI_2) {
515 result += M_PI;
516 } else if (result > M_PI_2) {
517 result -= M_PI;
518 }
519 return result;
520}
521
522void MotionEvent::transform(const SkMatrix* matrix) {
523 float oldXOffset = mXOffset;
524 float oldYOffset = mYOffset;
525
526 // The tricky part of this implementation is to preserve the value of
527 // rawX and rawY. So we apply the transformation to the first point
528 // then derive an appropriate new X/Y offset that will preserve rawX and rawY.
529 SkPoint point;
530 float rawX = getRawX(0);
531 float rawY = getRawY(0);
532 matrix->mapXY(SkFloatToScalar(rawX + oldXOffset), SkFloatToScalar(rawY + oldYOffset),
533 & point);
534 float newX = SkScalarToFloat(point.fX);
535 float newY = SkScalarToFloat(point.fY);
536 float newXOffset = newX - rawX;
537 float newYOffset = newY - rawY;
538
539 mXOffset = newXOffset;
540 mYOffset = newYOffset;
541
542 // Apply the transformation to all samples.
543 size_t numSamples = mSamplePointerCoords.size();
544 for (size_t i = 0; i < numSamples; i++) {
545 PointerCoords& c = mSamplePointerCoords.editItemAt(i);
Jeff Brownb2d44352011-02-17 13:01:34 -0800546 float* xPtr = c.editAxisValue(AMOTION_EVENT_AXIS_X);
547 float* yPtr = c.editAxisValue(AMOTION_EVENT_AXIS_Y);
Jeff Brown3e341462011-02-14 17:03:18 -0800548 if (xPtr && yPtr) {
549 float x = *xPtr + oldXOffset;
550 float y = *yPtr + oldYOffset;
551 matrix->mapXY(SkFloatToScalar(x), SkFloatToScalar(y), & point);
552 *xPtr = SkScalarToFloat(point.fX) - newXOffset;
553 *yPtr = SkScalarToFloat(point.fY) - newYOffset;
554 }
555
Jeff Brownb2d44352011-02-17 13:01:34 -0800556 float* orientationPtr = c.editAxisValue(AMOTION_EVENT_AXIS_ORIENTATION);
Jeff Brown3e341462011-02-14 17:03:18 -0800557 if (orientationPtr) {
558 *orientationPtr = transformAngle(matrix, *orientationPtr);
559 }
560 }
561}
562
563status_t MotionEvent::readFromParcel(Parcel* parcel) {
564 size_t pointerCount = parcel->readInt32();
565 size_t sampleCount = parcel->readInt32();
566 if (pointerCount == 0 || pointerCount > MAX_POINTERS || sampleCount == 0) {
567 return BAD_VALUE;
568 }
569
570 mDeviceId = parcel->readInt32();
571 mSource = parcel->readInt32();
572 mAction = parcel->readInt32();
573 mFlags = parcel->readInt32();
574 mEdgeFlags = parcel->readInt32();
575 mMetaState = parcel->readInt32();
576 mXOffset = parcel->readFloat();
577 mYOffset = parcel->readFloat();
578 mXPrecision = parcel->readFloat();
579 mYPrecision = parcel->readFloat();
580 mDownTime = parcel->readInt64();
581
582 mPointerIds.clear();
583 mPointerIds.setCapacity(pointerCount);
584 mSampleEventTimes.clear();
585 mSampleEventTimes.setCapacity(sampleCount);
586 mSamplePointerCoords.clear();
587 mSamplePointerCoords.setCapacity(sampleCount * pointerCount);
588
589 for (size_t i = 0; i < pointerCount; i++) {
590 mPointerIds.push(parcel->readInt32());
591 }
592
593 while (sampleCount-- > 0) {
594 mSampleEventTimes.push(parcel->readInt64());
595 for (size_t i = 0; i < pointerCount; i++) {
596 mSamplePointerCoords.push();
597 status_t status = mSamplePointerCoords.editTop().readFromParcel(parcel);
Jeff Brownb2d44352011-02-17 13:01:34 -0800598 if (status) {
Jeff Brown3e341462011-02-14 17:03:18 -0800599 return status;
600 }
601 }
602 }
603 return OK;
604}
605
606status_t MotionEvent::writeToParcel(Parcel* parcel) const {
607 size_t pointerCount = mPointerIds.size();
608 size_t sampleCount = mSampleEventTimes.size();
609
610 parcel->writeInt32(pointerCount);
611 parcel->writeInt32(sampleCount);
612
613 parcel->writeInt32(mDeviceId);
614 parcel->writeInt32(mSource);
615 parcel->writeInt32(mAction);
616 parcel->writeInt32(mFlags);
617 parcel->writeInt32(mEdgeFlags);
618 parcel->writeInt32(mMetaState);
619 parcel->writeFloat(mXOffset);
620 parcel->writeFloat(mYOffset);
621 parcel->writeFloat(mXPrecision);
622 parcel->writeFloat(mYPrecision);
623 parcel->writeInt64(mDownTime);
624
625 for (size_t i = 0; i < pointerCount; i++) {
626 parcel->writeInt32(mPointerIds.itemAt(i));
627 }
628
629 const PointerCoords* pc = mSamplePointerCoords.array();
630 for (size_t h = 0; h < sampleCount; h++) {
631 parcel->writeInt64(mSampleEventTimes.itemAt(h));
632 for (size_t i = 0; i < pointerCount; i++) {
633 status_t status = (pc++)->writeToParcel(parcel);
Jeff Brownb2d44352011-02-17 13:01:34 -0800634 if (status) {
Jeff Brown3e341462011-02-14 17:03:18 -0800635 return status;
636 }
637 }
638 }
639 return OK;
640}
641#endif
642
Jeff Brownd5ed2852011-03-02 19:23:13 -0800643bool MotionEvent::isTouchEvent(int32_t source, int32_t action) {
644 if (source & AINPUT_SOURCE_CLASS_POINTER) {
645 // Specifically excludes HOVER_MOVE and SCROLL.
646 switch (action & AMOTION_EVENT_ACTION_MASK) {
647 case AMOTION_EVENT_ACTION_DOWN:
648 case AMOTION_EVENT_ACTION_MOVE:
649 case AMOTION_EVENT_ACTION_UP:
650 case AMOTION_EVENT_ACTION_POINTER_DOWN:
651 case AMOTION_EVENT_ACTION_POINTER_UP:
652 case AMOTION_EVENT_ACTION_CANCEL:
653 case AMOTION_EVENT_ACTION_OUTSIDE:
654 return true;
655 }
656 }
657 return false;
658}
659
Jeff Brown3e341462011-02-14 17:03:18 -0800660
Jeff Brown247da722011-03-09 17:39:48 -0800661// --- VelocityTracker ---
662
663VelocityTracker::VelocityTracker() {
664 clear();
665}
666
667void VelocityTracker::clear() {
668 mIndex = 0;
669 mMovements[0].idBits.clear();
670}
671
672void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions) {
673 if (++mIndex == HISTORY_SIZE) {
674 mIndex = 0;
675 }
676 Movement& movement = mMovements[mIndex];
677 movement.eventTime = eventTime;
678 movement.idBits = idBits;
679 uint32_t count = idBits.count();
680 for (uint32_t i = 0; i < count; i++) {
681 movement.positions[i] = positions[i];
682 }
683
684#if DEBUG_VELOCITY
685 LOGD("VelocityTracker: addMovement eventTime=%lld, idBits=0x%08x", eventTime, idBits.value);
686 for (BitSet32 iterBits(idBits); !iterBits.isEmpty(); ) {
687 uint32_t id = iterBits.firstMarkedBit();
688 uint32_t index = idBits.getIndexOfBit(id);
689 iterBits.clearBit(id);
690 float vx, vy;
691 bool available = getVelocity(id, &vx, &vy);
692 if (available) {
693 LOGD(" %d: position (%0.3f, %0.3f), velocity (%0.3f, %0.3f), speed %0.3f",
694 id, positions[index].x, positions[index].y, vx, vy, sqrtf(vx * vx + vy * vy));
695 } else {
696 assert(vx == 0 && vy == 0);
697 LOGD(" %d: position (%0.3f, %0.3f), velocity not available",
698 id, positions[index].x, positions[index].y);
699 }
700 }
701#endif
702}
703
704bool VelocityTracker::getVelocity(uint32_t id, float* outVx, float* outVy) const {
705 const Movement& newestMovement = mMovements[mIndex];
706 if (newestMovement.idBits.hasBit(id)) {
707 // Find the oldest sample that contains the pointer and that is not older than MAX_AGE.
708 nsecs_t minTime = newestMovement.eventTime - MAX_AGE;
709 uint32_t oldestIndex = mIndex;
710 uint32_t numTouches = 1;
711 do {
712 uint32_t nextOldestIndex = (oldestIndex == 0 ? HISTORY_SIZE : oldestIndex) - 1;
713 const Movement& nextOldestMovement = mMovements[nextOldestIndex];
714 if (!nextOldestMovement.idBits.hasBit(id)
715 || nextOldestMovement.eventTime < minTime) {
716 break;
717 }
718 oldestIndex = nextOldestIndex;
719 } while (++numTouches < HISTORY_SIZE);
720
721 // If we have a lot of samples, skip the last received sample since it is
722 // probably pretty noisy compared to the sum of all of the traces already acquired.
723 //
724 // NOTE: This condition exists in the android.view.VelocityTracker and imposes a
725 // bias against the most recent data.
726 if (numTouches > 3) {
727 numTouches -= 1;
728 }
729
730 // Calculate an exponentially weighted moving average of the velocity at different
731 // points in time measured relative to the oldest samples. This is essentially
732 // an IIR filter.
733 //
734 // One problem with this algorithm is that the sample data may be poorly conditioned.
735 // Sometimes samples arrive very close together in time which can cause us to
736 // overestimate the velocity at that time point. Most samples might be measured
737 // 16ms apart but some consecutive samples could be only 0.5sm apart due to
738 // the way they are reported by the hardware or driver (sometimes in bursts or with
739 // significant jitter). The instantaneous velocity for those samples 0.5ms apart will
740 // be calculated to be 32 times what it should have been.
741 // To work around this effect, we impose a minimum duration on the samples.
742 //
743 // FIXME: Samples close together in time can have an disproportionately large
744 // impact on the result because all samples are equally weighted. The average should
745 // instead take the time factor into account.
746 //
747 // FIXME: The minimum duration condition does not exist in
748 // android.view.VelocityTracker yet. It is less important there because sample times
749 // are truncated to the millisecond so back to back samples will often appear to be
750 // zero milliseconds apart and will be ignored if they are the oldest ones.
751 float accumVx = 0;
752 float accumVy = 0;
753 uint32_t index = oldestIndex;
754 uint32_t samplesUsed = 0;
755 const Movement& oldestMovement = mMovements[oldestIndex];
756 const Position& oldestPosition =
757 oldestMovement.positions[oldestMovement.idBits.getIndexOfBit(id)];
758 while (numTouches-- > 1) {
759 if (++index == HISTORY_SIZE) {
760 index = 0;
761 }
762 const Movement& movement = mMovements[index];
763 nsecs_t duration = movement.eventTime - oldestMovement.eventTime;
764 if (duration > MIN_DURATION) {
765 const Position& position = movement.positions[movement.idBits.getIndexOfBit(id)];
766 float scale = 1000000000.0f / duration; // one over time delta in seconds
767 float vx = (position.x - oldestPosition.x) * scale;
768 float vy = (position.y - oldestPosition.y) * scale;
769 accumVx = accumVx == 0 ? vx : (accumVx + vx) * 0.5f;
770 accumVy = accumVy == 0 ? vy : (accumVy + vy) * 0.5f;
771 samplesUsed += 1;
772 }
773 }
774
775 // Make sure we used at least one sample.
776 if (samplesUsed != 0) {
777 *outVx = accumVx;
778 *outVy = accumVy;
779 return true;
780 }
781 }
782
783 // No data available for this pointer.
784 *outVx = 0;
785 *outVy = 0;
786 return false;
787}
788
789
Jeff Brown66888372010-11-29 17:37:49 -0800790// --- InputDeviceInfo ---
Jeff Browne57e8952010-07-23 21:28:06 -0700791
792InputDeviceInfo::InputDeviceInfo() {
793 initialize(-1, String8("uninitialized device info"));
794}
795
796InputDeviceInfo::InputDeviceInfo(const InputDeviceInfo& other) :
797 mId(other.mId), mName(other.mName), mSources(other.mSources),
798 mKeyboardType(other.mKeyboardType),
799 mMotionRanges(other.mMotionRanges) {
800}
801
802InputDeviceInfo::~InputDeviceInfo() {
803}
804
805void InputDeviceInfo::initialize(int32_t id, const String8& name) {
806 mId = id;
807 mName = name;
808 mSources = 0;
809 mKeyboardType = AINPUT_KEYBOARD_TYPE_NONE;
810 mMotionRanges.clear();
811}
812
Jeff Brown46689da2011-03-08 15:13:06 -0800813const InputDeviceInfo::MotionRange* InputDeviceInfo::getMotionRange(
814 int32_t axis, uint32_t source) const {
815 size_t numRanges = mMotionRanges.size();
816 for (size_t i = 0; i < numRanges; i++) {
817 const MotionRange& range = mMotionRanges.itemAt(i);
818 if (range.axis == axis && range.source == source) {
819 return &range;
820 }
821 }
822 return NULL;
Jeff Browne57e8952010-07-23 21:28:06 -0700823}
824
825void InputDeviceInfo::addSource(uint32_t source) {
826 mSources |= source;
827}
828
Jeff Brown46689da2011-03-08 15:13:06 -0800829void InputDeviceInfo::addMotionRange(int32_t axis, uint32_t source, float min, float max,
Jeff Browne57e8952010-07-23 21:28:06 -0700830 float flat, float fuzz) {
Jeff Brown46689da2011-03-08 15:13:06 -0800831 MotionRange range = { axis, source, min, max, flat, fuzz };
832 mMotionRanges.add(range);
Jeff Browne57e8952010-07-23 21:28:06 -0700833}
834
Jeff Brown46689da2011-03-08 15:13:06 -0800835void InputDeviceInfo::addMotionRange(const MotionRange& range) {
836 mMotionRanges.add(range);
Jeff Browne57e8952010-07-23 21:28:06 -0700837}
838
Jeff Browne839a582010-04-22 18:58:52 -0700839} // namespace android