blob: 50b75d504e6a989efcce7c0cf7c82ad13b01746d [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 Brownadab6202011-06-01 12:33:19 -070016// Log debug messages about acceleration.
17#define DEBUG_ACCELERATION 0
18
19
Jeff Brown66888372010-11-29 17:37:49 -080020#include <stdlib.h>
21#include <unistd.h>
Jeff Browndb360642010-12-02 13:50:46 -080022#include <ctype.h>
Jeff Brown66888372010-11-29 17:37:49 -080023
Jeff Browne839a582010-04-22 18:58:52 -070024#include <ui/Input.h>
25
Jeff Brown3e341462011-02-14 17:03:18 -080026#include <math.h>
Jeff Brownadab6202011-06-01 12:33:19 -070027#include <limits.h>
Jeff Brown3e341462011-02-14 17:03:18 -080028
29#ifdef HAVE_ANDROID_OS
30#include <binder/Parcel.h>
31
32#include "SkPoint.h"
33#include "SkMatrix.h"
34#include "SkScalar.h"
35#endif
36
Jeff Browne839a582010-04-22 18:58:52 -070037namespace android {
38
Jeff Brown66888372010-11-29 17:37:49 -080039static const char* CONFIGURATION_FILE_DIR[] = {
40 "idc/",
41 "keylayout/",
42 "keychars/",
43};
44
45static const char* CONFIGURATION_FILE_EXTENSION[] = {
46 ".idc",
47 ".kl",
48 ".kcm",
49};
50
Jeff Browndb360642010-12-02 13:50:46 -080051static bool isValidNameChar(char ch) {
52 return isascii(ch) && (isdigit(ch) || isalpha(ch) || ch == '-' || ch == '_');
53}
54
Jeff Brown66888372010-11-29 17:37:49 -080055static void appendInputDeviceConfigurationFileRelativePath(String8& path,
56 const String8& name, InputDeviceConfigurationFileType type) {
57 path.append(CONFIGURATION_FILE_DIR[type]);
58 for (size_t i = 0; i < name.length(); i++) {
59 char ch = name[i];
Jeff Browndb360642010-12-02 13:50:46 -080060 if (!isValidNameChar(ch)) {
Jeff Brown66888372010-11-29 17:37:49 -080061 ch = '_';
62 }
63 path.append(&ch, 1);
64 }
65 path.append(CONFIGURATION_FILE_EXTENSION[type]);
66}
67
Jeff Browndb360642010-12-02 13:50:46 -080068String8 getInputDeviceConfigurationFilePathByDeviceIdentifier(
69 const InputDeviceIdentifier& deviceIdentifier,
70 InputDeviceConfigurationFileType type) {
71 if (deviceIdentifier.vendor !=0 && deviceIdentifier.product != 0) {
72 if (deviceIdentifier.version != 0) {
73 // Try vendor product version.
74 String8 versionPath(getInputDeviceConfigurationFilePathByName(
75 String8::format("Vendor_%04x_Product_%04x_Version_%04x",
76 deviceIdentifier.vendor, deviceIdentifier.product,
77 deviceIdentifier.version),
78 type));
79 if (!versionPath.isEmpty()) {
80 return versionPath;
81 }
82 }
83
84 // Try vendor product.
85 String8 productPath(getInputDeviceConfigurationFilePathByName(
86 String8::format("Vendor_%04x_Product_%04x",
87 deviceIdentifier.vendor, deviceIdentifier.product),
88 type));
89 if (!productPath.isEmpty()) {
90 return productPath;
91 }
92 }
93
94 // Try device name.
95 return getInputDeviceConfigurationFilePathByName(deviceIdentifier.name, type);
96}
97
98String8 getInputDeviceConfigurationFilePathByName(
Jeff Brown66888372010-11-29 17:37:49 -080099 const String8& name, InputDeviceConfigurationFileType type) {
100 // Search system repository.
101 String8 path;
102 path.setTo(getenv("ANDROID_ROOT"));
103 path.append("/usr/");
104 appendInputDeviceConfigurationFileRelativePath(path, name, type);
105#if DEBUG_PROBE
106 LOGD("Probing for system provided input device configuration file: path='%s'", path.string());
107#endif
108 if (!access(path.string(), R_OK)) {
109#if DEBUG_PROBE
110 LOGD("Found");
111#endif
112 return path;
113 }
114
115 // Search user repository.
116 // TODO Should only look here if not in safe mode.
117 path.setTo(getenv("ANDROID_DATA"));
118 path.append("/system/devices/");
119 appendInputDeviceConfigurationFileRelativePath(path, name, type);
120#if DEBUG_PROBE
121 LOGD("Probing for system user input device configuration file: path='%s'", path.string());
122#endif
123 if (!access(path.string(), R_OK)) {
124#if DEBUG_PROBE
125 LOGD("Found");
126#endif
127 return path;
128 }
129
130 // Not found.
131#if DEBUG_PROBE
132 LOGD("Probe failed to find input device configuration file: name='%s', type=%d",
133 name.string(), type);
134#endif
135 return String8();
136}
137
138
139// --- InputEvent ---
Jeff Browne839a582010-04-22 18:58:52 -0700140
Jeff Brown5c1ed842010-07-14 18:48:53 -0700141void InputEvent::initialize(int32_t deviceId, int32_t source) {
Jeff Browne839a582010-04-22 18:58:52 -0700142 mDeviceId = deviceId;
Jeff Brown5c1ed842010-07-14 18:48:53 -0700143 mSource = source;
Jeff Browne839a582010-04-22 18:58:52 -0700144}
145
Dianne Hackborn0e885272010-07-15 17:44:53 -0700146void InputEvent::initialize(const InputEvent& from) {
147 mDeviceId = from.mDeviceId;
148 mSource = from.mSource;
149}
150
Jeff Brown66888372010-11-29 17:37:49 -0800151// --- KeyEvent ---
Jeff Browne839a582010-04-22 18:58:52 -0700152
Dianne Hackborn189ed232010-06-29 19:20:40 -0700153bool KeyEvent::hasDefaultAction(int32_t keyCode) {
154 switch (keyCode) {
Jeff Brown8575a872010-06-30 16:10:35 -0700155 case AKEYCODE_HOME:
156 case AKEYCODE_BACK:
157 case AKEYCODE_CALL:
158 case AKEYCODE_ENDCALL:
159 case AKEYCODE_VOLUME_UP:
160 case AKEYCODE_VOLUME_DOWN:
Jeff Brown7e5660f2010-11-01 15:24:01 -0700161 case AKEYCODE_VOLUME_MUTE:
Jeff Brown8575a872010-06-30 16:10:35 -0700162 case AKEYCODE_POWER:
163 case AKEYCODE_CAMERA:
164 case AKEYCODE_HEADSETHOOK:
165 case AKEYCODE_MENU:
166 case AKEYCODE_NOTIFICATION:
167 case AKEYCODE_FOCUS:
168 case AKEYCODE_SEARCH:
Jeff Brown7e5660f2010-11-01 15:24:01 -0700169 case AKEYCODE_MEDIA_PLAY:
170 case AKEYCODE_MEDIA_PAUSE:
Jeff Brown8575a872010-06-30 16:10:35 -0700171 case AKEYCODE_MEDIA_PLAY_PAUSE:
172 case AKEYCODE_MEDIA_STOP:
173 case AKEYCODE_MEDIA_NEXT:
174 case AKEYCODE_MEDIA_PREVIOUS:
175 case AKEYCODE_MEDIA_REWIND:
Jeff Brown7e5660f2010-11-01 15:24:01 -0700176 case AKEYCODE_MEDIA_RECORD:
Jeff Brown8575a872010-06-30 16:10:35 -0700177 case AKEYCODE_MEDIA_FAST_FORWARD:
178 case AKEYCODE_MUTE:
Dianne Hackborn189ed232010-06-29 19:20:40 -0700179 return true;
180 }
181
182 return false;
183}
184
185bool KeyEvent::hasDefaultAction() const {
186 return hasDefaultAction(getKeyCode());
187}
188
189bool KeyEvent::isSystemKey(int32_t keyCode) {
190 switch (keyCode) {
Jeff Brown8575a872010-06-30 16:10:35 -0700191 case AKEYCODE_MENU:
192 case AKEYCODE_SOFT_RIGHT:
193 case AKEYCODE_HOME:
194 case AKEYCODE_BACK:
195 case AKEYCODE_CALL:
196 case AKEYCODE_ENDCALL:
197 case AKEYCODE_VOLUME_UP:
198 case AKEYCODE_VOLUME_DOWN:
Jeff Brown7e5660f2010-11-01 15:24:01 -0700199 case AKEYCODE_VOLUME_MUTE:
Jeff Brown8575a872010-06-30 16:10:35 -0700200 case AKEYCODE_MUTE:
201 case AKEYCODE_POWER:
202 case AKEYCODE_HEADSETHOOK:
Jeff Brown7e5660f2010-11-01 15:24:01 -0700203 case AKEYCODE_MEDIA_PLAY:
204 case AKEYCODE_MEDIA_PAUSE:
Jeff Brown8575a872010-06-30 16:10:35 -0700205 case AKEYCODE_MEDIA_PLAY_PAUSE:
206 case AKEYCODE_MEDIA_STOP:
207 case AKEYCODE_MEDIA_NEXT:
208 case AKEYCODE_MEDIA_PREVIOUS:
209 case AKEYCODE_MEDIA_REWIND:
Jeff Brown7e5660f2010-11-01 15:24:01 -0700210 case AKEYCODE_MEDIA_RECORD:
Jeff Brown8575a872010-06-30 16:10:35 -0700211 case AKEYCODE_MEDIA_FAST_FORWARD:
212 case AKEYCODE_CAMERA:
213 case AKEYCODE_FOCUS:
214 case AKEYCODE_SEARCH:
Dianne Hackborn189ed232010-06-29 19:20:40 -0700215 return true;
216 }
217
218 return false;
219}
220
221bool KeyEvent::isSystemKey() const {
222 return isSystemKey(getKeyCode());
223}
224
Jeff Browne839a582010-04-22 18:58:52 -0700225void KeyEvent::initialize(
226 int32_t deviceId,
Jeff Brown5c1ed842010-07-14 18:48:53 -0700227 int32_t source,
Jeff Browne839a582010-04-22 18:58:52 -0700228 int32_t action,
229 int32_t flags,
230 int32_t keyCode,
231 int32_t scanCode,
232 int32_t metaState,
233 int32_t repeatCount,
234 nsecs_t downTime,
235 nsecs_t eventTime) {
Jeff Brown5c1ed842010-07-14 18:48:53 -0700236 InputEvent::initialize(deviceId, source);
Jeff Browne839a582010-04-22 18:58:52 -0700237 mAction = action;
238 mFlags = flags;
239 mKeyCode = keyCode;
240 mScanCode = scanCode;
241 mMetaState = metaState;
242 mRepeatCount = repeatCount;
243 mDownTime = downTime;
244 mEventTime = eventTime;
245}
246
Dianne Hackborn0e885272010-07-15 17:44:53 -0700247void KeyEvent::initialize(const KeyEvent& from) {
248 InputEvent::initialize(from);
249 mAction = from.mAction;
250 mFlags = from.mFlags;
251 mKeyCode = from.mKeyCode;
252 mScanCode = from.mScanCode;
253 mMetaState = from.mMetaState;
254 mRepeatCount = from.mRepeatCount;
255 mDownTime = from.mDownTime;
256 mEventTime = from.mEventTime;
257}
258
Jeff Brown3e341462011-02-14 17:03:18 -0800259
260// --- PointerCoords ---
261
Jeff Brown3ea4de82011-02-19 01:08:02 -0800262float PointerCoords::getAxisValue(int32_t axis) const {
263 if (axis < 0 || axis > 63) {
264 return 0;
265 }
266
267 uint64_t axisBit = 1LL << axis;
268 if (!(bits & axisBit)) {
269 return 0;
270 }
271 uint32_t index = __builtin_popcountll(bits & (axisBit - 1LL));
272 return values[index];
273}
274
275status_t PointerCoords::setAxisValue(int32_t axis, float value) {
276 if (axis < 0 || axis > 63) {
277 return NAME_NOT_FOUND;
278 }
279
280 uint64_t axisBit = 1LL << axis;
281 uint32_t index = __builtin_popcountll(bits & (axisBit - 1LL));
282 if (!(bits & axisBit)) {
283 uint32_t count = __builtin_popcountll(bits);
284 if (count >= MAX_AXES) {
285 tooManyAxes(axis);
286 return NO_MEMORY;
287 }
288 bits |= axisBit;
289 for (uint32_t i = count; i > index; i--) {
290 values[i] = values[i - 1];
291 }
292 }
293 values[index] = value;
294 return OK;
295}
296
297float* PointerCoords::editAxisValue(int32_t axis) {
298 if (axis < 0 || axis > 63) {
299 return NULL;
300 }
301
302 uint64_t axisBit = 1LL << axis;
303 if (!(bits & axisBit)) {
304 return NULL;
305 }
306 uint32_t index = __builtin_popcountll(bits & (axisBit - 1LL));
307 return &values[index];
308}
309
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400310static inline void scaleAxisValue(PointerCoords& c, int axis, float scaleFactor) {
311 float* value = c.editAxisValue(axis);
312 if (value) {
313 *value *= scaleFactor;
314 }
315}
316
317void PointerCoords::scale(float scaleFactor) {
318 // No need to scale pressure or size since they are normalized.
319 // No need to scale orientation since it is meaningless to do so.
320 scaleAxisValue(*this, AMOTION_EVENT_AXIS_X, scaleFactor);
321 scaleAxisValue(*this, AMOTION_EVENT_AXIS_Y, scaleFactor);
322 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOUCH_MAJOR, scaleFactor);
323 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOUCH_MINOR, scaleFactor);
324 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOOL_MAJOR, scaleFactor);
325 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOOL_MINOR, scaleFactor);
326}
327
Jeff Brown3e341462011-02-14 17:03:18 -0800328#ifdef HAVE_ANDROID_OS
329status_t PointerCoords::readFromParcel(Parcel* parcel) {
Jeff Brown3ea4de82011-02-19 01:08:02 -0800330 bits = parcel->readInt64();
Jeff Brown3e341462011-02-14 17:03:18 -0800331
Jeff Brown3ea4de82011-02-19 01:08:02 -0800332 uint32_t count = __builtin_popcountll(bits);
Jeff Brown3e341462011-02-14 17:03:18 -0800333 if (count > MAX_AXES) {
334 return BAD_VALUE;
335 }
336
337 for (uint32_t i = 0; i < count; i++) {
338 values[i] = parcel->readInt32();
339 }
340 return OK;
341}
342
343status_t PointerCoords::writeToParcel(Parcel* parcel) const {
Jeff Brown3ea4de82011-02-19 01:08:02 -0800344 parcel->writeInt64(bits);
Jeff Brown3e341462011-02-14 17:03:18 -0800345
Jeff Brown3ea4de82011-02-19 01:08:02 -0800346 uint32_t count = __builtin_popcountll(bits);
Jeff Brown3e341462011-02-14 17:03:18 -0800347 for (uint32_t i = 0; i < count; i++) {
348 parcel->writeInt32(values[i]);
349 }
350 return OK;
351}
352#endif
353
354void PointerCoords::tooManyAxes(int axis) {
355 LOGW("Could not set value for axis %d because the PointerCoords structure is full and "
356 "cannot contain more than %d axis values.", axis, int(MAX_AXES));
357}
358
Jeff Brown247da722011-03-09 17:39:48 -0800359bool PointerCoords::operator==(const PointerCoords& other) const {
360 if (bits != other.bits) {
361 return false;
362 }
363 uint32_t count = __builtin_popcountll(bits);
364 for (uint32_t i = 0; i < count; i++) {
365 if (values[i] != other.values[i]) {
366 return false;
367 }
368 }
369 return true;
370}
371
372void PointerCoords::copyFrom(const PointerCoords& other) {
373 bits = other.bits;
374 uint32_t count = __builtin_popcountll(bits);
375 for (uint32_t i = 0; i < count; i++) {
376 values[i] = other.values[i];
377 }
378}
379
Jeff Brown3e341462011-02-14 17:03:18 -0800380
Jeff Brown66888372010-11-29 17:37:49 -0800381// --- MotionEvent ---
Jeff Browne839a582010-04-22 18:58:52 -0700382
383void MotionEvent::initialize(
384 int32_t deviceId,
Jeff Brown5c1ed842010-07-14 18:48:53 -0700385 int32_t source,
Jeff Browne839a582010-04-22 18:58:52 -0700386 int32_t action,
Jeff Brownaf30ff62010-09-01 17:01:00 -0700387 int32_t flags,
Jeff Browne839a582010-04-22 18:58:52 -0700388 int32_t edgeFlags,
389 int32_t metaState,
Jeff Brownf4a4ec22010-06-16 01:53:36 -0700390 float xOffset,
391 float yOffset,
Jeff Browne839a582010-04-22 18:58:52 -0700392 float xPrecision,
393 float yPrecision,
394 nsecs_t downTime,
395 nsecs_t eventTime,
396 size_t pointerCount,
397 const int32_t* pointerIds,
398 const PointerCoords* pointerCoords) {
Jeff Brown5c1ed842010-07-14 18:48:53 -0700399 InputEvent::initialize(deviceId, source);
Jeff Browne839a582010-04-22 18:58:52 -0700400 mAction = action;
Jeff Brownaf30ff62010-09-01 17:01:00 -0700401 mFlags = flags;
Jeff Browne839a582010-04-22 18:58:52 -0700402 mEdgeFlags = edgeFlags;
403 mMetaState = metaState;
Jeff Brownf4a4ec22010-06-16 01:53:36 -0700404 mXOffset = xOffset;
405 mYOffset = yOffset;
Jeff Browne839a582010-04-22 18:58:52 -0700406 mXPrecision = xPrecision;
407 mYPrecision = yPrecision;
408 mDownTime = downTime;
409 mPointerIds.clear();
410 mPointerIds.appendArray(pointerIds, pointerCount);
411 mSampleEventTimes.clear();
412 mSamplePointerCoords.clear();
413 addSample(eventTime, pointerCoords);
414}
415
Jeff Brown3e341462011-02-14 17:03:18 -0800416void MotionEvent::copyFrom(const MotionEvent* other, bool keepHistory) {
417 InputEvent::initialize(other->mDeviceId, other->mSource);
418 mAction = other->mAction;
419 mFlags = other->mFlags;
420 mEdgeFlags = other->mEdgeFlags;
421 mMetaState = other->mMetaState;
422 mXOffset = other->mXOffset;
423 mYOffset = other->mYOffset;
424 mXPrecision = other->mXPrecision;
425 mYPrecision = other->mYPrecision;
426 mDownTime = other->mDownTime;
427 mPointerIds = other->mPointerIds;
428
429 if (keepHistory) {
430 mSampleEventTimes = other->mSampleEventTimes;
431 mSamplePointerCoords = other->mSamplePointerCoords;
432 } else {
433 mSampleEventTimes.clear();
434 mSampleEventTimes.push(other->getEventTime());
435 mSamplePointerCoords.clear();
436 size_t pointerCount = other->getPointerCount();
437 size_t historySize = other->getHistorySize();
438 mSamplePointerCoords.appendArray(other->mSamplePointerCoords.array()
439 + (historySize * pointerCount), pointerCount);
440 }
441}
442
Jeff Browne839a582010-04-22 18:58:52 -0700443void MotionEvent::addSample(
444 int64_t eventTime,
445 const PointerCoords* pointerCoords) {
446 mSampleEventTimes.push(eventTime);
447 mSamplePointerCoords.appendArray(pointerCoords, getPointerCount());
448}
449
Jeff Brown3e341462011-02-14 17:03:18 -0800450const PointerCoords* MotionEvent::getRawPointerCoords(size_t pointerIndex) const {
451 return &mSamplePointerCoords[getHistorySize() * getPointerCount() + pointerIndex];
452}
453
454float MotionEvent::getRawAxisValue(int32_t axis, size_t pointerIndex) const {
455 return getRawPointerCoords(pointerIndex)->getAxisValue(axis);
456}
457
458float MotionEvent::getAxisValue(int32_t axis, size_t pointerIndex) const {
459 float value = getRawPointerCoords(pointerIndex)->getAxisValue(axis);
460 switch (axis) {
Jeff Brownb2d44352011-02-17 13:01:34 -0800461 case AMOTION_EVENT_AXIS_X:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400462 return value + mXOffset;
Jeff Brownb2d44352011-02-17 13:01:34 -0800463 case AMOTION_EVENT_AXIS_Y:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400464 return value + mYOffset;
Jeff Brown3e341462011-02-14 17:03:18 -0800465 }
466 return value;
467}
468
469const PointerCoords* MotionEvent::getHistoricalRawPointerCoords(
470 size_t pointerIndex, size_t historicalIndex) const {
471 return &mSamplePointerCoords[historicalIndex * getPointerCount() + pointerIndex];
472}
473
474float MotionEvent::getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex,
475 size_t historicalIndex) const {
476 return getHistoricalRawPointerCoords(pointerIndex, historicalIndex)->getAxisValue(axis);
477}
478
479float MotionEvent::getHistoricalAxisValue(int32_t axis, size_t pointerIndex,
480 size_t historicalIndex) const {
481 float value = getHistoricalRawPointerCoords(pointerIndex, historicalIndex)->getAxisValue(axis);
482 switch (axis) {
Jeff Brownb2d44352011-02-17 13:01:34 -0800483 case AMOTION_EVENT_AXIS_X:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400484 return value + mXOffset;
Jeff Brownb2d44352011-02-17 13:01:34 -0800485 case AMOTION_EVENT_AXIS_Y:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400486 return value + mYOffset;
Jeff Brown3e341462011-02-14 17:03:18 -0800487 }
488 return value;
489}
490
Jeff Brownc5982b72011-03-14 19:39:54 -0700491ssize_t MotionEvent::findPointerIndex(int32_t pointerId) const {
492 size_t pointerCount = mPointerIds.size();
493 for (size_t i = 0; i < pointerCount; i++) {
494 if (mPointerIds.itemAt(i) == pointerId) {
495 return i;
496 }
497 }
498 return -1;
499}
500
Jeff Browne839a582010-04-22 18:58:52 -0700501void MotionEvent::offsetLocation(float xOffset, float yOffset) {
Jeff Brownf4a4ec22010-06-16 01:53:36 -0700502 mXOffset += xOffset;
503 mYOffset += yOffset;
Jeff Browne839a582010-04-22 18:58:52 -0700504}
505
Jeff Brown3e341462011-02-14 17:03:18 -0800506void MotionEvent::scale(float scaleFactor) {
507 mXOffset *= scaleFactor;
508 mYOffset *= scaleFactor;
509 mXPrecision *= scaleFactor;
510 mYPrecision *= scaleFactor;
511
512 size_t numSamples = mSamplePointerCoords.size();
513 for (size_t i = 0; i < numSamples; i++) {
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400514 mSamplePointerCoords.editItemAt(i).scale(scaleFactor);
Jeff Brown3e341462011-02-14 17:03:18 -0800515 }
516}
517
518#ifdef HAVE_ANDROID_OS
519static inline float transformAngle(const SkMatrix* matrix, float angleRadians) {
520 // Construct and transform a vector oriented at the specified clockwise angle from vertical.
521 // Coordinate system: down is increasing Y, right is increasing X.
522 SkPoint vector;
523 vector.fX = SkFloatToScalar(sinf(angleRadians));
524 vector.fY = SkFloatToScalar(-cosf(angleRadians));
525 matrix->mapVectors(& vector, 1);
526
527 // Derive the transformed vector's clockwise angle from vertical.
528 float result = atan2f(SkScalarToFloat(vector.fX), SkScalarToFloat(-vector.fY));
529 if (result < - M_PI_2) {
530 result += M_PI;
531 } else if (result > M_PI_2) {
532 result -= M_PI;
533 }
534 return result;
535}
536
537void MotionEvent::transform(const SkMatrix* matrix) {
538 float oldXOffset = mXOffset;
539 float oldYOffset = mYOffset;
540
541 // The tricky part of this implementation is to preserve the value of
542 // rawX and rawY. So we apply the transformation to the first point
543 // then derive an appropriate new X/Y offset that will preserve rawX and rawY.
544 SkPoint point;
545 float rawX = getRawX(0);
546 float rawY = getRawY(0);
547 matrix->mapXY(SkFloatToScalar(rawX + oldXOffset), SkFloatToScalar(rawY + oldYOffset),
548 & point);
549 float newX = SkScalarToFloat(point.fX);
550 float newY = SkScalarToFloat(point.fY);
551 float newXOffset = newX - rawX;
552 float newYOffset = newY - rawY;
553
554 mXOffset = newXOffset;
555 mYOffset = newYOffset;
556
557 // Apply the transformation to all samples.
558 size_t numSamples = mSamplePointerCoords.size();
559 for (size_t i = 0; i < numSamples; i++) {
560 PointerCoords& c = mSamplePointerCoords.editItemAt(i);
Jeff Brownb2d44352011-02-17 13:01:34 -0800561 float* xPtr = c.editAxisValue(AMOTION_EVENT_AXIS_X);
562 float* yPtr = c.editAxisValue(AMOTION_EVENT_AXIS_Y);
Jeff Brown3e341462011-02-14 17:03:18 -0800563 if (xPtr && yPtr) {
564 float x = *xPtr + oldXOffset;
565 float y = *yPtr + oldYOffset;
566 matrix->mapXY(SkFloatToScalar(x), SkFloatToScalar(y), & point);
567 *xPtr = SkScalarToFloat(point.fX) - newXOffset;
568 *yPtr = SkScalarToFloat(point.fY) - newYOffset;
569 }
570
Jeff Brownb2d44352011-02-17 13:01:34 -0800571 float* orientationPtr = c.editAxisValue(AMOTION_EVENT_AXIS_ORIENTATION);
Jeff Brown3e341462011-02-14 17:03:18 -0800572 if (orientationPtr) {
573 *orientationPtr = transformAngle(matrix, *orientationPtr);
574 }
575 }
576}
577
578status_t MotionEvent::readFromParcel(Parcel* parcel) {
579 size_t pointerCount = parcel->readInt32();
580 size_t sampleCount = parcel->readInt32();
581 if (pointerCount == 0 || pointerCount > MAX_POINTERS || sampleCount == 0) {
582 return BAD_VALUE;
583 }
584
585 mDeviceId = parcel->readInt32();
586 mSource = parcel->readInt32();
587 mAction = parcel->readInt32();
588 mFlags = parcel->readInt32();
589 mEdgeFlags = parcel->readInt32();
590 mMetaState = parcel->readInt32();
591 mXOffset = parcel->readFloat();
592 mYOffset = parcel->readFloat();
593 mXPrecision = parcel->readFloat();
594 mYPrecision = parcel->readFloat();
595 mDownTime = parcel->readInt64();
596
597 mPointerIds.clear();
598 mPointerIds.setCapacity(pointerCount);
599 mSampleEventTimes.clear();
600 mSampleEventTimes.setCapacity(sampleCount);
601 mSamplePointerCoords.clear();
602 mSamplePointerCoords.setCapacity(sampleCount * pointerCount);
603
604 for (size_t i = 0; i < pointerCount; i++) {
605 mPointerIds.push(parcel->readInt32());
606 }
607
608 while (sampleCount-- > 0) {
609 mSampleEventTimes.push(parcel->readInt64());
610 for (size_t i = 0; i < pointerCount; i++) {
611 mSamplePointerCoords.push();
612 status_t status = mSamplePointerCoords.editTop().readFromParcel(parcel);
Jeff Brownb2d44352011-02-17 13:01:34 -0800613 if (status) {
Jeff Brown3e341462011-02-14 17:03:18 -0800614 return status;
615 }
616 }
617 }
618 return OK;
619}
620
621status_t MotionEvent::writeToParcel(Parcel* parcel) const {
622 size_t pointerCount = mPointerIds.size();
623 size_t sampleCount = mSampleEventTimes.size();
624
625 parcel->writeInt32(pointerCount);
626 parcel->writeInt32(sampleCount);
627
628 parcel->writeInt32(mDeviceId);
629 parcel->writeInt32(mSource);
630 parcel->writeInt32(mAction);
631 parcel->writeInt32(mFlags);
632 parcel->writeInt32(mEdgeFlags);
633 parcel->writeInt32(mMetaState);
634 parcel->writeFloat(mXOffset);
635 parcel->writeFloat(mYOffset);
636 parcel->writeFloat(mXPrecision);
637 parcel->writeFloat(mYPrecision);
638 parcel->writeInt64(mDownTime);
639
640 for (size_t i = 0; i < pointerCount; i++) {
641 parcel->writeInt32(mPointerIds.itemAt(i));
642 }
643
644 const PointerCoords* pc = mSamplePointerCoords.array();
645 for (size_t h = 0; h < sampleCount; h++) {
646 parcel->writeInt64(mSampleEventTimes.itemAt(h));
647 for (size_t i = 0; i < pointerCount; i++) {
648 status_t status = (pc++)->writeToParcel(parcel);
Jeff Brownb2d44352011-02-17 13:01:34 -0800649 if (status) {
Jeff Brown3e341462011-02-14 17:03:18 -0800650 return status;
651 }
652 }
653 }
654 return OK;
655}
656#endif
657
Jeff Brownd5ed2852011-03-02 19:23:13 -0800658bool MotionEvent::isTouchEvent(int32_t source, int32_t action) {
659 if (source & AINPUT_SOURCE_CLASS_POINTER) {
660 // Specifically excludes HOVER_MOVE and SCROLL.
661 switch (action & AMOTION_EVENT_ACTION_MASK) {
662 case AMOTION_EVENT_ACTION_DOWN:
663 case AMOTION_EVENT_ACTION_MOVE:
664 case AMOTION_EVENT_ACTION_UP:
665 case AMOTION_EVENT_ACTION_POINTER_DOWN:
666 case AMOTION_EVENT_ACTION_POINTER_UP:
667 case AMOTION_EVENT_ACTION_CANCEL:
668 case AMOTION_EVENT_ACTION_OUTSIDE:
669 return true;
670 }
671 }
672 return false;
673}
674
Jeff Brown3e341462011-02-14 17:03:18 -0800675
Jeff Brown247da722011-03-09 17:39:48 -0800676// --- VelocityTracker ---
677
Jeff Brownadab6202011-06-01 12:33:19 -0700678const uint32_t VelocityTracker::HISTORY_SIZE;
679const nsecs_t VelocityTracker::MAX_AGE;
680const nsecs_t VelocityTracker::MIN_WINDOW;
681const nsecs_t VelocityTracker::MIN_DURATION;
682
Jeff Brown247da722011-03-09 17:39:48 -0800683VelocityTracker::VelocityTracker() {
684 clear();
685}
686
687void VelocityTracker::clear() {
688 mIndex = 0;
689 mMovements[0].idBits.clear();
Jeff Brownc5982b72011-03-14 19:39:54 -0700690 mActivePointerId = -1;
691}
692
693void VelocityTracker::clearPointers(BitSet32 idBits) {
694 BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value);
695 mMovements[mIndex].idBits = remainingIdBits;
696
697 if (mActivePointerId >= 0 && idBits.hasBit(mActivePointerId)) {
698 mActivePointerId = !remainingIdBits.isEmpty() ? remainingIdBits.firstMarkedBit() : -1;
699 }
Jeff Brown247da722011-03-09 17:39:48 -0800700}
701
702void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions) {
703 if (++mIndex == HISTORY_SIZE) {
704 mIndex = 0;
705 }
Jeff Brownc5982b72011-03-14 19:39:54 -0700706
707 while (idBits.count() > MAX_POINTERS) {
708 idBits.clearBit(idBits.lastMarkedBit());
709 }
710
Jeff Brown247da722011-03-09 17:39:48 -0800711 Movement& movement = mMovements[mIndex];
712 movement.eventTime = eventTime;
713 movement.idBits = idBits;
714 uint32_t count = idBits.count();
715 for (uint32_t i = 0; i < count; i++) {
716 movement.positions[i] = positions[i];
717 }
718
Jeff Brownc5982b72011-03-14 19:39:54 -0700719 if (mActivePointerId < 0 || !idBits.hasBit(mActivePointerId)) {
720 mActivePointerId = count != 0 ? idBits.firstMarkedBit() : -1;
721 }
722
Jeff Brown247da722011-03-09 17:39:48 -0800723#if DEBUG_VELOCITY
Jeff Brownc5982b72011-03-14 19:39:54 -0700724 LOGD("VelocityTracker: addMovement eventTime=%lld, idBits=0x%08x, activePointerId=%d",
725 eventTime, idBits.value, mActivePointerId);
Jeff Brown247da722011-03-09 17:39:48 -0800726 for (BitSet32 iterBits(idBits); !iterBits.isEmpty(); ) {
727 uint32_t id = iterBits.firstMarkedBit();
728 uint32_t index = idBits.getIndexOfBit(id);
729 iterBits.clearBit(id);
730 float vx, vy;
731 bool available = getVelocity(id, &vx, &vy);
732 if (available) {
Jeff Brownc5982b72011-03-14 19:39:54 -0700733 LOGD(" %d: position (%0.3f, %0.3f), vx=%0.3f, vy=%0.3f, speed=%0.3f",
Jeff Brown247da722011-03-09 17:39:48 -0800734 id, positions[index].x, positions[index].y, vx, vy, sqrtf(vx * vx + vy * vy));
735 } else {
736 assert(vx == 0 && vy == 0);
737 LOGD(" %d: position (%0.3f, %0.3f), velocity not available",
738 id, positions[index].x, positions[index].y);
739 }
740 }
741#endif
742}
743
Jeff Brownc5982b72011-03-14 19:39:54 -0700744void VelocityTracker::addMovement(const MotionEvent* event) {
745 int32_t actionMasked = event->getActionMasked();
746
747 switch (actionMasked) {
748 case AMOTION_EVENT_ACTION_DOWN:
749 // Clear all pointers on down before adding the new movement.
750 clear();
751 break;
752 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
753 // Start a new movement trace for a pointer that just went down.
754 // We do this on down instead of on up because the client may want to query the
755 // final velocity for a pointer that just went up.
756 BitSet32 downIdBits;
757 downIdBits.markBit(event->getActionIndex());
758 clearPointers(downIdBits);
759 break;
760 }
761 case AMOTION_EVENT_ACTION_OUTSIDE:
762 case AMOTION_EVENT_ACTION_CANCEL:
763 case AMOTION_EVENT_ACTION_SCROLL:
764 case AMOTION_EVENT_ACTION_UP:
765 case AMOTION_EVENT_ACTION_POINTER_UP:
766 // Ignore these actions because they do not convey any new information about
767 // pointer movement. We also want to preserve the last known velocity of the pointers.
768 // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position
769 // of the pointers that went up. ACTION_POINTER_UP does include the new position of
770 // pointers that remained down but we will also receive an ACTION_MOVE with this
771 // information if any of them actually moved. Since we don't know how many pointers
772 // will be going up at once it makes sense to just wait for the following ACTION_MOVE
773 // before adding the movement.
774 return;
775 }
776
777 size_t pointerCount = event->getPointerCount();
778 if (pointerCount > MAX_POINTERS) {
779 pointerCount = MAX_POINTERS;
780 }
781
782 BitSet32 idBits;
783 for (size_t i = 0; i < pointerCount; i++) {
784 idBits.markBit(event->getPointerId(i));
785 }
786
787 nsecs_t eventTime;
788 Position positions[pointerCount];
789
790 size_t historySize = event->getHistorySize();
791 for (size_t h = 0; h < historySize; h++) {
792 eventTime = event->getHistoricalEventTime(h);
793 for (size_t i = 0; i < pointerCount; i++) {
794 positions[i].x = event->getHistoricalX(i, h);
795 positions[i].y = event->getHistoricalY(i, h);
796 }
797 addMovement(eventTime, idBits, positions);
798 }
799
800 eventTime = event->getEventTime();
801 for (size_t i = 0; i < pointerCount; i++) {
802 positions[i].x = event->getX(i);
803 positions[i].y = event->getY(i);
804 }
805 addMovement(eventTime, idBits, positions);
806}
807
Jeff Brown247da722011-03-09 17:39:48 -0800808bool VelocityTracker::getVelocity(uint32_t id, float* outVx, float* outVy) const {
809 const Movement& newestMovement = mMovements[mIndex];
810 if (newestMovement.idBits.hasBit(id)) {
811 // Find the oldest sample that contains the pointer and that is not older than MAX_AGE.
812 nsecs_t minTime = newestMovement.eventTime - MAX_AGE;
813 uint32_t oldestIndex = mIndex;
814 uint32_t numTouches = 1;
815 do {
816 uint32_t nextOldestIndex = (oldestIndex == 0 ? HISTORY_SIZE : oldestIndex) - 1;
817 const Movement& nextOldestMovement = mMovements[nextOldestIndex];
818 if (!nextOldestMovement.idBits.hasBit(id)
819 || nextOldestMovement.eventTime < minTime) {
820 break;
821 }
822 oldestIndex = nextOldestIndex;
823 } while (++numTouches < HISTORY_SIZE);
824
Jeff Brownc5982b72011-03-14 19:39:54 -0700825 // Calculate an exponentially weighted moving average of the velocity estimate
826 // at different points in time measured relative to the oldest sample.
827 // This is essentially an IIR filter. Newer samples are weighted more heavily
828 // than older samples. Samples at equal time points are weighted more or less
829 // equally.
Jeff Brown247da722011-03-09 17:39:48 -0800830 //
Jeff Brownc5982b72011-03-14 19:39:54 -0700831 // One tricky problem is that the sample data may be poorly conditioned.
Jeff Brown247da722011-03-09 17:39:48 -0800832 // Sometimes samples arrive very close together in time which can cause us to
833 // overestimate the velocity at that time point. Most samples might be measured
Jeff Brownc5982b72011-03-14 19:39:54 -0700834 // 16ms apart but some consecutive samples could be only 0.5sm apart because
835 // the hardware or driver reports them irregularly or in bursts.
Jeff Brown247da722011-03-09 17:39:48 -0800836 float accumVx = 0;
837 float accumVy = 0;
838 uint32_t index = oldestIndex;
839 uint32_t samplesUsed = 0;
840 const Movement& oldestMovement = mMovements[oldestIndex];
841 const Position& oldestPosition =
842 oldestMovement.positions[oldestMovement.idBits.getIndexOfBit(id)];
Jeff Brownc5982b72011-03-14 19:39:54 -0700843 nsecs_t lastDuration = 0;
Jeff Brownd3e6d3e2011-04-12 22:39:53 -0700844
Jeff Brown247da722011-03-09 17:39:48 -0800845 while (numTouches-- > 1) {
846 if (++index == HISTORY_SIZE) {
847 index = 0;
848 }
849 const Movement& movement = mMovements[index];
850 nsecs_t duration = movement.eventTime - oldestMovement.eventTime;
Jeff Brownc5982b72011-03-14 19:39:54 -0700851
852 // If the duration between samples is small, we may significantly overestimate
853 // the velocity. Consequently, we impose a minimum duration constraint on the
854 // samples that we include in the calculation.
855 if (duration >= MIN_DURATION) {
Jeff Brown247da722011-03-09 17:39:48 -0800856 const Position& position = movement.positions[movement.idBits.getIndexOfBit(id)];
857 float scale = 1000000000.0f / duration; // one over time delta in seconds
858 float vx = (position.x - oldestPosition.x) * scale;
859 float vy = (position.y - oldestPosition.y) * scale;
Jeff Brownc5982b72011-03-14 19:39:54 -0700860
861 accumVx = (accumVx * lastDuration + vx * duration) / (duration + lastDuration);
862 accumVy = (accumVy * lastDuration + vy * duration) / (duration + lastDuration);
863
864 lastDuration = duration;
Jeff Brown247da722011-03-09 17:39:48 -0800865 samplesUsed += 1;
866 }
867 }
868
869 // Make sure we used at least one sample.
870 if (samplesUsed != 0) {
Jeff Brownd3e6d3e2011-04-12 22:39:53 -0700871 // Scale the velocity linearly if the window of samples is small.
872 nsecs_t totalDuration = newestMovement.eventTime - oldestMovement.eventTime;
873 if (totalDuration < MIN_WINDOW) {
874 float scale = float(totalDuration) / float(MIN_WINDOW);
875 accumVx *= scale;
876 accumVy *= scale;
877 }
878
Jeff Brown247da722011-03-09 17:39:48 -0800879 *outVx = accumVx;
880 *outVy = accumVy;
881 return true;
882 }
883 }
884
885 // No data available for this pointer.
886 *outVx = 0;
887 *outVy = 0;
888 return false;
889}
890
891
Jeff Brownadab6202011-06-01 12:33:19 -0700892// --- VelocityControl ---
893
894const nsecs_t VelocityControl::STOP_TIME;
895
896VelocityControl::VelocityControl() {
897 reset();
898}
899
900void VelocityControl::setParameters(const VelocityControlParameters& parameters) {
901 mParameters = parameters;
902 reset();
903}
904
905void VelocityControl::reset() {
906 mLastMovementTime = LLONG_MIN;
907 mRawPosition.x = 0;
908 mRawPosition.y = 0;
909 mVelocityTracker.clear();
910}
911
912void VelocityControl::move(nsecs_t eventTime, float* deltaX, float* deltaY) {
913 if ((deltaX && *deltaX) || (deltaY && *deltaY)) {
914 if (eventTime >= mLastMovementTime + STOP_TIME) {
915#if DEBUG_ACCELERATION
916 LOGD("VelocityControl: stopped, last movement was %0.3fms ago",
917 (eventTime - mLastMovementTime) * 0.000001f);
918#endif
919 reset();
920 }
921
922 mLastMovementTime = eventTime;
923 if (deltaX) {
924 mRawPosition.x += *deltaX;
925 }
926 if (deltaY) {
927 mRawPosition.y += *deltaY;
928 }
929 mVelocityTracker.addMovement(eventTime, BitSet32(BitSet32::valueForBit(0)), &mRawPosition);
930
931 float vx, vy;
932 float scale = mParameters.scale;
933 if (mVelocityTracker.getVelocity(0, &vx, &vy)) {
934 float speed = hypotf(vx, vy) * scale;
935 if (speed >= mParameters.highThreshold) {
936 // Apply full acceleration above the high speed threshold.
937 scale *= mParameters.acceleration;
938 } else if (speed > mParameters.lowThreshold) {
939 // Linearly interpolate the acceleration to apply between the low and high
940 // speed thresholds.
941 scale *= 1 + (speed - mParameters.lowThreshold)
942 / (mParameters.highThreshold - mParameters.lowThreshold)
943 * (mParameters.acceleration - 1);
944 }
945
946#if DEBUG_ACCELERATION
947 LOGD("VelocityControl(%0.3f, %0.3f, %0.3f, %0.3f): "
948 "vx=%0.3f, vy=%0.3f, speed=%0.3f, accel=%0.3f",
949 mParameters.scale, mParameters.lowThreshold, mParameters.highThreshold,
950 mParameters.acceleration,
951 vx, vy, speed, scale / mParameters.scale);
952#endif
953 } else {
954#if DEBUG_ACCELERATION
955 LOGD("VelocityControl(%0.3f, %0.3f, %0.3f, %0.3f): unknown velocity",
956 mParameters.scale, mParameters.lowThreshold, mParameters.highThreshold,
957 mParameters.acceleration);
958#endif
959 }
960
961 if (deltaX) {
962 *deltaX *= scale;
963 }
964 if (deltaY) {
965 *deltaY *= scale;
966 }
967 }
968}
969
970
Jeff Brown66888372010-11-29 17:37:49 -0800971// --- InputDeviceInfo ---
Jeff Browne57e8952010-07-23 21:28:06 -0700972
973InputDeviceInfo::InputDeviceInfo() {
974 initialize(-1, String8("uninitialized device info"));
975}
976
977InputDeviceInfo::InputDeviceInfo(const InputDeviceInfo& other) :
978 mId(other.mId), mName(other.mName), mSources(other.mSources),
979 mKeyboardType(other.mKeyboardType),
980 mMotionRanges(other.mMotionRanges) {
981}
982
983InputDeviceInfo::~InputDeviceInfo() {
984}
985
986void InputDeviceInfo::initialize(int32_t id, const String8& name) {
987 mId = id;
988 mName = name;
989 mSources = 0;
990 mKeyboardType = AINPUT_KEYBOARD_TYPE_NONE;
991 mMotionRanges.clear();
992}
993
Jeff Brown46689da2011-03-08 15:13:06 -0800994const InputDeviceInfo::MotionRange* InputDeviceInfo::getMotionRange(
995 int32_t axis, uint32_t source) const {
996 size_t numRanges = mMotionRanges.size();
997 for (size_t i = 0; i < numRanges; i++) {
998 const MotionRange& range = mMotionRanges.itemAt(i);
999 if (range.axis == axis && range.source == source) {
1000 return &range;
1001 }
1002 }
1003 return NULL;
Jeff Browne57e8952010-07-23 21:28:06 -07001004}
1005
1006void InputDeviceInfo::addSource(uint32_t source) {
1007 mSources |= source;
1008}
1009
Jeff Brown46689da2011-03-08 15:13:06 -08001010void InputDeviceInfo::addMotionRange(int32_t axis, uint32_t source, float min, float max,
Jeff Browne57e8952010-07-23 21:28:06 -07001011 float flat, float fuzz) {
Jeff Brown46689da2011-03-08 15:13:06 -08001012 MotionRange range = { axis, source, min, max, flat, fuzz };
1013 mMotionRanges.add(range);
Jeff Browne57e8952010-07-23 21:28:06 -07001014}
1015
Jeff Brown46689da2011-03-08 15:13:06 -08001016void InputDeviceInfo::addMotionRange(const MotionRange& range) {
1017 mMotionRanges.add(range);
Jeff Browne57e8952010-07-23 21:28:06 -07001018}
1019
Jeff Browne839a582010-04-22 18:58:52 -07001020} // namespace android