blob: 1ba38a7ee9297c8307952b06d5fef5a649e5bf5e [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 Brownfa773aa2011-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 Brownfa773aa2011-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 Brownfa773aa2011-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 Browne959ed22011-05-06 18:20:01 -0700376// --- PointerProperties ---
377
378bool PointerProperties::operator==(const PointerProperties& other) const {
379 return id == other.id
380 && toolType == other.toolType;
381}
382
383void PointerProperties::copyFrom(const PointerProperties& other) {
384 id = other.id;
385 toolType = other.toolType;
386}
387
388
Jeff Brown66888372010-11-29 17:37:49 -0800389// --- MotionEvent ---
Jeff Browne839a582010-04-22 18:58:52 -0700390
391void MotionEvent::initialize(
392 int32_t deviceId,
Jeff Brown5c1ed842010-07-14 18:48:53 -0700393 int32_t source,
Jeff Browne839a582010-04-22 18:58:52 -0700394 int32_t action,
Jeff Brownaf30ff62010-09-01 17:01:00 -0700395 int32_t flags,
Jeff Browne839a582010-04-22 18:58:52 -0700396 int32_t edgeFlags,
397 int32_t metaState,
Jeff Browne959ed22011-05-06 18:20:01 -0700398 int32_t buttonState,
Jeff Brownf4a4ec22010-06-16 01:53:36 -0700399 float xOffset,
400 float yOffset,
Jeff Browne839a582010-04-22 18:58:52 -0700401 float xPrecision,
402 float yPrecision,
403 nsecs_t downTime,
404 nsecs_t eventTime,
405 size_t pointerCount,
Jeff Browne959ed22011-05-06 18:20:01 -0700406 const PointerProperties* pointerProperties,
Jeff Browne839a582010-04-22 18:58:52 -0700407 const PointerCoords* pointerCoords) {
Jeff Brown5c1ed842010-07-14 18:48:53 -0700408 InputEvent::initialize(deviceId, source);
Jeff Browne839a582010-04-22 18:58:52 -0700409 mAction = action;
Jeff Brownaf30ff62010-09-01 17:01:00 -0700410 mFlags = flags;
Jeff Browne839a582010-04-22 18:58:52 -0700411 mEdgeFlags = edgeFlags;
412 mMetaState = metaState;
Jeff Browne959ed22011-05-06 18:20:01 -0700413 mButtonState = buttonState;
Jeff Brownf4a4ec22010-06-16 01:53:36 -0700414 mXOffset = xOffset;
415 mYOffset = yOffset;
Jeff Browne839a582010-04-22 18:58:52 -0700416 mXPrecision = xPrecision;
417 mYPrecision = yPrecision;
418 mDownTime = downTime;
Jeff Browne959ed22011-05-06 18:20:01 -0700419 mPointerProperties.clear();
420 mPointerProperties.appendArray(pointerProperties, pointerCount);
Jeff Browne839a582010-04-22 18:58:52 -0700421 mSampleEventTimes.clear();
422 mSamplePointerCoords.clear();
423 addSample(eventTime, pointerCoords);
424}
425
Jeff Brown3e341462011-02-14 17:03:18 -0800426void MotionEvent::copyFrom(const MotionEvent* other, bool keepHistory) {
427 InputEvent::initialize(other->mDeviceId, other->mSource);
428 mAction = other->mAction;
429 mFlags = other->mFlags;
430 mEdgeFlags = other->mEdgeFlags;
431 mMetaState = other->mMetaState;
Jeff Browne959ed22011-05-06 18:20:01 -0700432 mButtonState = other->mButtonState;
Jeff Brown3e341462011-02-14 17:03:18 -0800433 mXOffset = other->mXOffset;
434 mYOffset = other->mYOffset;
435 mXPrecision = other->mXPrecision;
436 mYPrecision = other->mYPrecision;
437 mDownTime = other->mDownTime;
Jeff Browne959ed22011-05-06 18:20:01 -0700438 mPointerProperties = other->mPointerProperties;
Jeff Brown3e341462011-02-14 17:03:18 -0800439
440 if (keepHistory) {
441 mSampleEventTimes = other->mSampleEventTimes;
442 mSamplePointerCoords = other->mSamplePointerCoords;
443 } else {
444 mSampleEventTimes.clear();
445 mSampleEventTimes.push(other->getEventTime());
446 mSamplePointerCoords.clear();
447 size_t pointerCount = other->getPointerCount();
448 size_t historySize = other->getHistorySize();
449 mSamplePointerCoords.appendArray(other->mSamplePointerCoords.array()
450 + (historySize * pointerCount), pointerCount);
451 }
452}
453
Jeff Browne839a582010-04-22 18:58:52 -0700454void MotionEvent::addSample(
455 int64_t eventTime,
456 const PointerCoords* pointerCoords) {
457 mSampleEventTimes.push(eventTime);
458 mSamplePointerCoords.appendArray(pointerCoords, getPointerCount());
459}
460
Jeff Brown3e341462011-02-14 17:03:18 -0800461const PointerCoords* MotionEvent::getRawPointerCoords(size_t pointerIndex) const {
462 return &mSamplePointerCoords[getHistorySize() * getPointerCount() + pointerIndex];
463}
464
465float MotionEvent::getRawAxisValue(int32_t axis, size_t pointerIndex) const {
466 return getRawPointerCoords(pointerIndex)->getAxisValue(axis);
467}
468
469float MotionEvent::getAxisValue(int32_t axis, size_t pointerIndex) const {
470 float value = getRawPointerCoords(pointerIndex)->getAxisValue(axis);
471 switch (axis) {
Jeff Brownb2d44352011-02-17 13:01:34 -0800472 case AMOTION_EVENT_AXIS_X:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400473 return value + mXOffset;
Jeff Brownb2d44352011-02-17 13:01:34 -0800474 case AMOTION_EVENT_AXIS_Y:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400475 return value + mYOffset;
Jeff Brown3e341462011-02-14 17:03:18 -0800476 }
477 return value;
478}
479
480const PointerCoords* MotionEvent::getHistoricalRawPointerCoords(
481 size_t pointerIndex, size_t historicalIndex) const {
482 return &mSamplePointerCoords[historicalIndex * getPointerCount() + pointerIndex];
483}
484
485float MotionEvent::getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex,
486 size_t historicalIndex) const {
487 return getHistoricalRawPointerCoords(pointerIndex, historicalIndex)->getAxisValue(axis);
488}
489
490float MotionEvent::getHistoricalAxisValue(int32_t axis, size_t pointerIndex,
491 size_t historicalIndex) const {
492 float value = getHistoricalRawPointerCoords(pointerIndex, historicalIndex)->getAxisValue(axis);
493 switch (axis) {
Jeff Brownb2d44352011-02-17 13:01:34 -0800494 case AMOTION_EVENT_AXIS_X:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400495 return value + mXOffset;
Jeff Brownb2d44352011-02-17 13:01:34 -0800496 case AMOTION_EVENT_AXIS_Y:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400497 return value + mYOffset;
Jeff Brown3e341462011-02-14 17:03:18 -0800498 }
499 return value;
500}
501
Jeff Brown15933542011-03-14 19:39:54 -0700502ssize_t MotionEvent::findPointerIndex(int32_t pointerId) const {
Jeff Browne959ed22011-05-06 18:20:01 -0700503 size_t pointerCount = mPointerProperties.size();
Jeff Brown15933542011-03-14 19:39:54 -0700504 for (size_t i = 0; i < pointerCount; i++) {
Jeff Browne959ed22011-05-06 18:20:01 -0700505 if (mPointerProperties.itemAt(i).id == pointerId) {
Jeff Brown15933542011-03-14 19:39:54 -0700506 return i;
507 }
508 }
509 return -1;
510}
511
Jeff Browne839a582010-04-22 18:58:52 -0700512void MotionEvent::offsetLocation(float xOffset, float yOffset) {
Jeff Brownf4a4ec22010-06-16 01:53:36 -0700513 mXOffset += xOffset;
514 mYOffset += yOffset;
Jeff Browne839a582010-04-22 18:58:52 -0700515}
516
Jeff Brown3e341462011-02-14 17:03:18 -0800517void MotionEvent::scale(float scaleFactor) {
518 mXOffset *= scaleFactor;
519 mYOffset *= scaleFactor;
520 mXPrecision *= scaleFactor;
521 mYPrecision *= scaleFactor;
522
523 size_t numSamples = mSamplePointerCoords.size();
524 for (size_t i = 0; i < numSamples; i++) {
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400525 mSamplePointerCoords.editItemAt(i).scale(scaleFactor);
Jeff Brown3e341462011-02-14 17:03:18 -0800526 }
527}
528
529#ifdef HAVE_ANDROID_OS
530static inline float transformAngle(const SkMatrix* matrix, float angleRadians) {
531 // Construct and transform a vector oriented at the specified clockwise angle from vertical.
532 // Coordinate system: down is increasing Y, right is increasing X.
533 SkPoint vector;
534 vector.fX = SkFloatToScalar(sinf(angleRadians));
535 vector.fY = SkFloatToScalar(-cosf(angleRadians));
536 matrix->mapVectors(& vector, 1);
537
538 // Derive the transformed vector's clockwise angle from vertical.
539 float result = atan2f(SkScalarToFloat(vector.fX), SkScalarToFloat(-vector.fY));
540 if (result < - M_PI_2) {
541 result += M_PI;
542 } else if (result > M_PI_2) {
543 result -= M_PI;
544 }
545 return result;
546}
547
548void MotionEvent::transform(const SkMatrix* matrix) {
549 float oldXOffset = mXOffset;
550 float oldYOffset = mYOffset;
551
552 // The tricky part of this implementation is to preserve the value of
553 // rawX and rawY. So we apply the transformation to the first point
554 // then derive an appropriate new X/Y offset that will preserve rawX and rawY.
555 SkPoint point;
556 float rawX = getRawX(0);
557 float rawY = getRawY(0);
558 matrix->mapXY(SkFloatToScalar(rawX + oldXOffset), SkFloatToScalar(rawY + oldYOffset),
559 & point);
560 float newX = SkScalarToFloat(point.fX);
561 float newY = SkScalarToFloat(point.fY);
562 float newXOffset = newX - rawX;
563 float newYOffset = newY - rawY;
564
565 mXOffset = newXOffset;
566 mYOffset = newYOffset;
567
568 // Apply the transformation to all samples.
569 size_t numSamples = mSamplePointerCoords.size();
570 for (size_t i = 0; i < numSamples; i++) {
571 PointerCoords& c = mSamplePointerCoords.editItemAt(i);
Jeff Brownb2d44352011-02-17 13:01:34 -0800572 float* xPtr = c.editAxisValue(AMOTION_EVENT_AXIS_X);
573 float* yPtr = c.editAxisValue(AMOTION_EVENT_AXIS_Y);
Jeff Brown3e341462011-02-14 17:03:18 -0800574 if (xPtr && yPtr) {
575 float x = *xPtr + oldXOffset;
576 float y = *yPtr + oldYOffset;
577 matrix->mapXY(SkFloatToScalar(x), SkFloatToScalar(y), & point);
578 *xPtr = SkScalarToFloat(point.fX) - newXOffset;
579 *yPtr = SkScalarToFloat(point.fY) - newYOffset;
580 }
581
Jeff Brownb2d44352011-02-17 13:01:34 -0800582 float* orientationPtr = c.editAxisValue(AMOTION_EVENT_AXIS_ORIENTATION);
Jeff Brown3e341462011-02-14 17:03:18 -0800583 if (orientationPtr) {
584 *orientationPtr = transformAngle(matrix, *orientationPtr);
585 }
586 }
587}
588
589status_t MotionEvent::readFromParcel(Parcel* parcel) {
590 size_t pointerCount = parcel->readInt32();
591 size_t sampleCount = parcel->readInt32();
592 if (pointerCount == 0 || pointerCount > MAX_POINTERS || sampleCount == 0) {
593 return BAD_VALUE;
594 }
595
596 mDeviceId = parcel->readInt32();
597 mSource = parcel->readInt32();
598 mAction = parcel->readInt32();
599 mFlags = parcel->readInt32();
600 mEdgeFlags = parcel->readInt32();
601 mMetaState = parcel->readInt32();
Jeff Browne959ed22011-05-06 18:20:01 -0700602 mButtonState = parcel->readInt32();
Jeff Brown3e341462011-02-14 17:03:18 -0800603 mXOffset = parcel->readFloat();
604 mYOffset = parcel->readFloat();
605 mXPrecision = parcel->readFloat();
606 mYPrecision = parcel->readFloat();
607 mDownTime = parcel->readInt64();
608
Jeff Browne959ed22011-05-06 18:20:01 -0700609 mPointerProperties.clear();
610 mPointerProperties.setCapacity(pointerCount);
Jeff Brown3e341462011-02-14 17:03:18 -0800611 mSampleEventTimes.clear();
612 mSampleEventTimes.setCapacity(sampleCount);
613 mSamplePointerCoords.clear();
614 mSamplePointerCoords.setCapacity(sampleCount * pointerCount);
615
616 for (size_t i = 0; i < pointerCount; i++) {
Jeff Browne959ed22011-05-06 18:20:01 -0700617 mPointerProperties.push();
618 PointerProperties& properties = mPointerProperties.editTop();
619 properties.id = parcel->readInt32();
620 properties.toolType = parcel->readInt32();
Jeff Brown3e341462011-02-14 17:03:18 -0800621 }
622
623 while (sampleCount-- > 0) {
624 mSampleEventTimes.push(parcel->readInt64());
625 for (size_t i = 0; i < pointerCount; i++) {
626 mSamplePointerCoords.push();
627 status_t status = mSamplePointerCoords.editTop().readFromParcel(parcel);
Jeff Brownb2d44352011-02-17 13:01:34 -0800628 if (status) {
Jeff Brown3e341462011-02-14 17:03:18 -0800629 return status;
630 }
631 }
632 }
633 return OK;
634}
635
636status_t MotionEvent::writeToParcel(Parcel* parcel) const {
Jeff Browne959ed22011-05-06 18:20:01 -0700637 size_t pointerCount = mPointerProperties.size();
Jeff Brown3e341462011-02-14 17:03:18 -0800638 size_t sampleCount = mSampleEventTimes.size();
639
640 parcel->writeInt32(pointerCount);
641 parcel->writeInt32(sampleCount);
642
643 parcel->writeInt32(mDeviceId);
644 parcel->writeInt32(mSource);
645 parcel->writeInt32(mAction);
646 parcel->writeInt32(mFlags);
647 parcel->writeInt32(mEdgeFlags);
648 parcel->writeInt32(mMetaState);
Jeff Browne959ed22011-05-06 18:20:01 -0700649 parcel->writeInt32(mButtonState);
Jeff Brown3e341462011-02-14 17:03:18 -0800650 parcel->writeFloat(mXOffset);
651 parcel->writeFloat(mYOffset);
652 parcel->writeFloat(mXPrecision);
653 parcel->writeFloat(mYPrecision);
654 parcel->writeInt64(mDownTime);
655
656 for (size_t i = 0; i < pointerCount; i++) {
Jeff Browne959ed22011-05-06 18:20:01 -0700657 const PointerProperties& properties = mPointerProperties.itemAt(i);
658 parcel->writeInt32(properties.id);
659 parcel->writeInt32(properties.toolType);
Jeff Brown3e341462011-02-14 17:03:18 -0800660 }
661
662 const PointerCoords* pc = mSamplePointerCoords.array();
663 for (size_t h = 0; h < sampleCount; h++) {
664 parcel->writeInt64(mSampleEventTimes.itemAt(h));
665 for (size_t i = 0; i < pointerCount; i++) {
666 status_t status = (pc++)->writeToParcel(parcel);
Jeff Brownb2d44352011-02-17 13:01:34 -0800667 if (status) {
Jeff Brown3e341462011-02-14 17:03:18 -0800668 return status;
669 }
670 }
671 }
672 return OK;
673}
674#endif
675
Jeff Brownd5ed2852011-03-02 19:23:13 -0800676bool MotionEvent::isTouchEvent(int32_t source, int32_t action) {
677 if (source & AINPUT_SOURCE_CLASS_POINTER) {
678 // Specifically excludes HOVER_MOVE and SCROLL.
679 switch (action & AMOTION_EVENT_ACTION_MASK) {
680 case AMOTION_EVENT_ACTION_DOWN:
681 case AMOTION_EVENT_ACTION_MOVE:
682 case AMOTION_EVENT_ACTION_UP:
683 case AMOTION_EVENT_ACTION_POINTER_DOWN:
684 case AMOTION_EVENT_ACTION_POINTER_UP:
685 case AMOTION_EVENT_ACTION_CANCEL:
686 case AMOTION_EVENT_ACTION_OUTSIDE:
687 return true;
688 }
689 }
690 return false;
691}
692
Jeff Brown3e341462011-02-14 17:03:18 -0800693
Jeff Brownfa773aa2011-03-09 17:39:48 -0800694// --- VelocityTracker ---
695
696VelocityTracker::VelocityTracker() {
697 clear();
698}
699
700void VelocityTracker::clear() {
701 mIndex = 0;
702 mMovements[0].idBits.clear();
Jeff Brown15933542011-03-14 19:39:54 -0700703 mActivePointerId = -1;
704}
705
706void VelocityTracker::clearPointers(BitSet32 idBits) {
707 BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value);
708 mMovements[mIndex].idBits = remainingIdBits;
709
710 if (mActivePointerId >= 0 && idBits.hasBit(mActivePointerId)) {
711 mActivePointerId = !remainingIdBits.isEmpty() ? remainingIdBits.firstMarkedBit() : -1;
712 }
Jeff Brownfa773aa2011-03-09 17:39:48 -0800713}
714
715void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions) {
716 if (++mIndex == HISTORY_SIZE) {
717 mIndex = 0;
718 }
Jeff Brown15933542011-03-14 19:39:54 -0700719
720 while (idBits.count() > MAX_POINTERS) {
721 idBits.clearBit(idBits.lastMarkedBit());
722 }
723
Jeff Brownfa773aa2011-03-09 17:39:48 -0800724 Movement& movement = mMovements[mIndex];
725 movement.eventTime = eventTime;
726 movement.idBits = idBits;
727 uint32_t count = idBits.count();
728 for (uint32_t i = 0; i < count; i++) {
729 movement.positions[i] = positions[i];
730 }
731
Jeff Brown15933542011-03-14 19:39:54 -0700732 if (mActivePointerId < 0 || !idBits.hasBit(mActivePointerId)) {
733 mActivePointerId = count != 0 ? idBits.firstMarkedBit() : -1;
734 }
735
Jeff Brownfa773aa2011-03-09 17:39:48 -0800736#if DEBUG_VELOCITY
Jeff Brown15933542011-03-14 19:39:54 -0700737 LOGD("VelocityTracker: addMovement eventTime=%lld, idBits=0x%08x, activePointerId=%d",
738 eventTime, idBits.value, mActivePointerId);
Jeff Brownfa773aa2011-03-09 17:39:48 -0800739 for (BitSet32 iterBits(idBits); !iterBits.isEmpty(); ) {
740 uint32_t id = iterBits.firstMarkedBit();
741 uint32_t index = idBits.getIndexOfBit(id);
742 iterBits.clearBit(id);
743 float vx, vy;
744 bool available = getVelocity(id, &vx, &vy);
745 if (available) {
Jeff Brown15933542011-03-14 19:39:54 -0700746 LOGD(" %d: position (%0.3f, %0.3f), vx=%0.3f, vy=%0.3f, speed=%0.3f",
Jeff Brownfa773aa2011-03-09 17:39:48 -0800747 id, positions[index].x, positions[index].y, vx, vy, sqrtf(vx * vx + vy * vy));
748 } else {
Jeff Brown23e0c8c2011-04-01 16:15:13 -0700749 LOG_ASSERT(vx == 0 && vy == 0);
Jeff Brownfa773aa2011-03-09 17:39:48 -0800750 LOGD(" %d: position (%0.3f, %0.3f), velocity not available",
751 id, positions[index].x, positions[index].y);
752 }
753 }
754#endif
755}
756
Jeff Brown15933542011-03-14 19:39:54 -0700757void VelocityTracker::addMovement(const MotionEvent* event) {
758 int32_t actionMasked = event->getActionMasked();
759
760 switch (actionMasked) {
761 case AMOTION_EVENT_ACTION_DOWN:
762 // Clear all pointers on down before adding the new movement.
763 clear();
764 break;
765 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
766 // Start a new movement trace for a pointer that just went down.
767 // We do this on down instead of on up because the client may want to query the
768 // final velocity for a pointer that just went up.
769 BitSet32 downIdBits;
770 downIdBits.markBit(event->getActionIndex());
771 clearPointers(downIdBits);
772 break;
773 }
774 case AMOTION_EVENT_ACTION_OUTSIDE:
775 case AMOTION_EVENT_ACTION_CANCEL:
776 case AMOTION_EVENT_ACTION_SCROLL:
777 case AMOTION_EVENT_ACTION_UP:
778 case AMOTION_EVENT_ACTION_POINTER_UP:
779 // Ignore these actions because they do not convey any new information about
780 // pointer movement. We also want to preserve the last known velocity of the pointers.
781 // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position
782 // of the pointers that went up. ACTION_POINTER_UP does include the new position of
783 // pointers that remained down but we will also receive an ACTION_MOVE with this
784 // information if any of them actually moved. Since we don't know how many pointers
785 // will be going up at once it makes sense to just wait for the following ACTION_MOVE
786 // before adding the movement.
787 return;
788 }
789
790 size_t pointerCount = event->getPointerCount();
791 if (pointerCount > MAX_POINTERS) {
792 pointerCount = MAX_POINTERS;
793 }
794
795 BitSet32 idBits;
796 for (size_t i = 0; i < pointerCount; i++) {
797 idBits.markBit(event->getPointerId(i));
798 }
799
800 nsecs_t eventTime;
801 Position positions[pointerCount];
802
803 size_t historySize = event->getHistorySize();
804 for (size_t h = 0; h < historySize; h++) {
805 eventTime = event->getHistoricalEventTime(h);
806 for (size_t i = 0; i < pointerCount; i++) {
807 positions[i].x = event->getHistoricalX(i, h);
808 positions[i].y = event->getHistoricalY(i, h);
809 }
810 addMovement(eventTime, idBits, positions);
811 }
812
813 eventTime = event->getEventTime();
814 for (size_t i = 0; i < pointerCount; i++) {
815 positions[i].x = event->getX(i);
816 positions[i].y = event->getY(i);
817 }
818 addMovement(eventTime, idBits, positions);
819}
820
Jeff Brownfa773aa2011-03-09 17:39:48 -0800821bool VelocityTracker::getVelocity(uint32_t id, float* outVx, float* outVy) const {
822 const Movement& newestMovement = mMovements[mIndex];
823 if (newestMovement.idBits.hasBit(id)) {
824 // Find the oldest sample that contains the pointer and that is not older than MAX_AGE.
825 nsecs_t minTime = newestMovement.eventTime - MAX_AGE;
826 uint32_t oldestIndex = mIndex;
827 uint32_t numTouches = 1;
828 do {
829 uint32_t nextOldestIndex = (oldestIndex == 0 ? HISTORY_SIZE : oldestIndex) - 1;
830 const Movement& nextOldestMovement = mMovements[nextOldestIndex];
831 if (!nextOldestMovement.idBits.hasBit(id)
832 || nextOldestMovement.eventTime < minTime) {
833 break;
834 }
835 oldestIndex = nextOldestIndex;
836 } while (++numTouches < HISTORY_SIZE);
837
Jeff Brown15933542011-03-14 19:39:54 -0700838 // Calculate an exponentially weighted moving average of the velocity estimate
839 // at different points in time measured relative to the oldest sample.
840 // This is essentially an IIR filter. Newer samples are weighted more heavily
841 // than older samples. Samples at equal time points are weighted more or less
842 // equally.
Jeff Brownfa773aa2011-03-09 17:39:48 -0800843 //
Jeff Brown15933542011-03-14 19:39:54 -0700844 // One tricky problem is that the sample data may be poorly conditioned.
Jeff Brownfa773aa2011-03-09 17:39:48 -0800845 // Sometimes samples arrive very close together in time which can cause us to
846 // overestimate the velocity at that time point. Most samples might be measured
Jeff Brown15933542011-03-14 19:39:54 -0700847 // 16ms apart but some consecutive samples could be only 0.5sm apart because
848 // the hardware or driver reports them irregularly or in bursts.
Jeff Brownfa773aa2011-03-09 17:39:48 -0800849 float accumVx = 0;
850 float accumVy = 0;
851 uint32_t index = oldestIndex;
852 uint32_t samplesUsed = 0;
853 const Movement& oldestMovement = mMovements[oldestIndex];
854 const Position& oldestPosition =
855 oldestMovement.positions[oldestMovement.idBits.getIndexOfBit(id)];
Jeff Brown15933542011-03-14 19:39:54 -0700856 nsecs_t lastDuration = 0;
Jeff Brown4815f2a2011-04-12 22:39:53 -0700857
Jeff Brownfa773aa2011-03-09 17:39:48 -0800858 while (numTouches-- > 1) {
859 if (++index == HISTORY_SIZE) {
860 index = 0;
861 }
862 const Movement& movement = mMovements[index];
863 nsecs_t duration = movement.eventTime - oldestMovement.eventTime;
Jeff Brown15933542011-03-14 19:39:54 -0700864
865 // If the duration between samples is small, we may significantly overestimate
866 // the velocity. Consequently, we impose a minimum duration constraint on the
867 // samples that we include in the calculation.
868 if (duration >= MIN_DURATION) {
Jeff Brownfa773aa2011-03-09 17:39:48 -0800869 const Position& position = movement.positions[movement.idBits.getIndexOfBit(id)];
870 float scale = 1000000000.0f / duration; // one over time delta in seconds
871 float vx = (position.x - oldestPosition.x) * scale;
872 float vy = (position.y - oldestPosition.y) * scale;
Jeff Brown15933542011-03-14 19:39:54 -0700873
874 accumVx = (accumVx * lastDuration + vx * duration) / (duration + lastDuration);
875 accumVy = (accumVy * lastDuration + vy * duration) / (duration + lastDuration);
876
877 lastDuration = duration;
Jeff Brownfa773aa2011-03-09 17:39:48 -0800878 samplesUsed += 1;
879 }
880 }
881
882 // Make sure we used at least one sample.
883 if (samplesUsed != 0) {
Jeff Brown4815f2a2011-04-12 22:39:53 -0700884 // Scale the velocity linearly if the window of samples is small.
885 nsecs_t totalDuration = newestMovement.eventTime - oldestMovement.eventTime;
886 if (totalDuration < MIN_WINDOW) {
887 float scale = float(totalDuration) / float(MIN_WINDOW);
888 accumVx *= scale;
889 accumVy *= scale;
890 }
891
Jeff Brownfa773aa2011-03-09 17:39:48 -0800892 *outVx = accumVx;
893 *outVy = accumVy;
894 return true;
895 }
896 }
897
898 // No data available for this pointer.
899 *outVx = 0;
900 *outVy = 0;
901 return false;
902}
903
904
Jeff Brown66888372010-11-29 17:37:49 -0800905// --- InputDeviceInfo ---
Jeff Browne57e8952010-07-23 21:28:06 -0700906
907InputDeviceInfo::InputDeviceInfo() {
908 initialize(-1, String8("uninitialized device info"));
909}
910
911InputDeviceInfo::InputDeviceInfo(const InputDeviceInfo& other) :
912 mId(other.mId), mName(other.mName), mSources(other.mSources),
913 mKeyboardType(other.mKeyboardType),
914 mMotionRanges(other.mMotionRanges) {
915}
916
917InputDeviceInfo::~InputDeviceInfo() {
918}
919
920void InputDeviceInfo::initialize(int32_t id, const String8& name) {
921 mId = id;
922 mName = name;
923 mSources = 0;
924 mKeyboardType = AINPUT_KEYBOARD_TYPE_NONE;
925 mMotionRanges.clear();
926}
927
Jeff Brown46689da2011-03-08 15:13:06 -0800928const InputDeviceInfo::MotionRange* InputDeviceInfo::getMotionRange(
929 int32_t axis, uint32_t source) const {
930 size_t numRanges = mMotionRanges.size();
931 for (size_t i = 0; i < numRanges; i++) {
932 const MotionRange& range = mMotionRanges.itemAt(i);
933 if (range.axis == axis && range.source == source) {
934 return &range;
935 }
936 }
937 return NULL;
Jeff Browne57e8952010-07-23 21:28:06 -0700938}
939
940void InputDeviceInfo::addSource(uint32_t source) {
941 mSources |= source;
942}
943
Jeff Brown46689da2011-03-08 15:13:06 -0800944void InputDeviceInfo::addMotionRange(int32_t axis, uint32_t source, float min, float max,
Jeff Browne57e8952010-07-23 21:28:06 -0700945 float flat, float fuzz) {
Jeff Brown46689da2011-03-08 15:13:06 -0800946 MotionRange range = { axis, source, min, max, flat, fuzz };
947 mMotionRanges.add(range);
Jeff Browne57e8952010-07-23 21:28:06 -0700948}
949
Jeff Brown46689da2011-03-08 15:13:06 -0800950void InputDeviceInfo::addMotionRange(const MotionRange& range) {
951 mMotionRanges.add(range);
Jeff Browne57e8952010-07-23 21:28:06 -0700952}
953
Jeff Browne839a582010-04-22 18:58:52 -0700954} // namespace android