blob: 0d258231fc53e8bc15b97c9834a0e8cbafb43311 [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 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)) {
Jeff Brown5873ce42011-07-27 16:04:54 -0700283 if (value == 0) {
284 return OK; // axes with value 0 do not need to be stored
285 }
Jeff Brown3ea4de82011-02-19 01:08:02 -0800286 uint32_t count = __builtin_popcountll(bits);
287 if (count >= MAX_AXES) {
288 tooManyAxes(axis);
289 return NO_MEMORY;
290 }
291 bits |= axisBit;
292 for (uint32_t i = count; i > index; i--) {
293 values[i] = values[i - 1];
294 }
295 }
296 values[index] = value;
297 return OK;
298}
299
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400300static inline void scaleAxisValue(PointerCoords& c, int axis, float scaleFactor) {
Jeff Brown5873ce42011-07-27 16:04:54 -0700301 float value = c.getAxisValue(axis);
302 if (value != 0) {
303 c.setAxisValue(axis, value * scaleFactor);
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400304 }
305}
306
307void PointerCoords::scale(float scaleFactor) {
308 // No need to scale pressure or size since they are normalized.
309 // No need to scale orientation since it is meaningless to do so.
310 scaleAxisValue(*this, AMOTION_EVENT_AXIS_X, scaleFactor);
311 scaleAxisValue(*this, AMOTION_EVENT_AXIS_Y, scaleFactor);
312 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOUCH_MAJOR, scaleFactor);
313 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOUCH_MINOR, scaleFactor);
314 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOOL_MAJOR, scaleFactor);
315 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOOL_MINOR, scaleFactor);
316}
317
Jeff Brown3e341462011-02-14 17:03:18 -0800318#ifdef HAVE_ANDROID_OS
319status_t PointerCoords::readFromParcel(Parcel* parcel) {
Jeff Brown3ea4de82011-02-19 01:08:02 -0800320 bits = parcel->readInt64();
Jeff Brown3e341462011-02-14 17:03:18 -0800321
Jeff Brown3ea4de82011-02-19 01:08:02 -0800322 uint32_t count = __builtin_popcountll(bits);
Jeff Brown3e341462011-02-14 17:03:18 -0800323 if (count > MAX_AXES) {
324 return BAD_VALUE;
325 }
326
327 for (uint32_t i = 0; i < count; i++) {
328 values[i] = parcel->readInt32();
329 }
330 return OK;
331}
332
333status_t PointerCoords::writeToParcel(Parcel* parcel) const {
Jeff Brown3ea4de82011-02-19 01:08:02 -0800334 parcel->writeInt64(bits);
Jeff Brown3e341462011-02-14 17:03:18 -0800335
Jeff Brown3ea4de82011-02-19 01:08:02 -0800336 uint32_t count = __builtin_popcountll(bits);
Jeff Brown3e341462011-02-14 17:03:18 -0800337 for (uint32_t i = 0; i < count; i++) {
338 parcel->writeInt32(values[i]);
339 }
340 return OK;
341}
342#endif
343
344void PointerCoords::tooManyAxes(int axis) {
345 LOGW("Could not set value for axis %d because the PointerCoords structure is full and "
346 "cannot contain more than %d axis values.", axis, int(MAX_AXES));
347}
348
Jeff Brownfa773aa2011-03-09 17:39:48 -0800349bool PointerCoords::operator==(const PointerCoords& other) const {
350 if (bits != other.bits) {
351 return false;
352 }
353 uint32_t count = __builtin_popcountll(bits);
354 for (uint32_t i = 0; i < count; i++) {
355 if (values[i] != other.values[i]) {
356 return false;
357 }
358 }
359 return true;
360}
361
362void PointerCoords::copyFrom(const PointerCoords& other) {
363 bits = other.bits;
364 uint32_t count = __builtin_popcountll(bits);
365 for (uint32_t i = 0; i < count; i++) {
366 values[i] = other.values[i];
367 }
368}
369
Jeff Brown3e341462011-02-14 17:03:18 -0800370
Jeff Browne959ed22011-05-06 18:20:01 -0700371// --- PointerProperties ---
372
373bool PointerProperties::operator==(const PointerProperties& other) const {
374 return id == other.id
375 && toolType == other.toolType;
376}
377
378void PointerProperties::copyFrom(const PointerProperties& other) {
379 id = other.id;
380 toolType = other.toolType;
381}
382
383
Jeff Brown66888372010-11-29 17:37:49 -0800384// --- MotionEvent ---
Jeff Browne839a582010-04-22 18:58:52 -0700385
386void MotionEvent::initialize(
387 int32_t deviceId,
Jeff Brown5c1ed842010-07-14 18:48:53 -0700388 int32_t source,
Jeff Browne839a582010-04-22 18:58:52 -0700389 int32_t action,
Jeff Brownaf30ff62010-09-01 17:01:00 -0700390 int32_t flags,
Jeff Browne839a582010-04-22 18:58:52 -0700391 int32_t edgeFlags,
392 int32_t metaState,
Jeff Browne959ed22011-05-06 18:20:01 -0700393 int32_t buttonState,
Jeff Brownf4a4ec22010-06-16 01:53:36 -0700394 float xOffset,
395 float yOffset,
Jeff Browne839a582010-04-22 18:58:52 -0700396 float xPrecision,
397 float yPrecision,
398 nsecs_t downTime,
399 nsecs_t eventTime,
400 size_t pointerCount,
Jeff Browne959ed22011-05-06 18:20:01 -0700401 const PointerProperties* pointerProperties,
Jeff Browne839a582010-04-22 18:58:52 -0700402 const PointerCoords* pointerCoords) {
Jeff Brown5c1ed842010-07-14 18:48:53 -0700403 InputEvent::initialize(deviceId, source);
Jeff Browne839a582010-04-22 18:58:52 -0700404 mAction = action;
Jeff Brownaf30ff62010-09-01 17:01:00 -0700405 mFlags = flags;
Jeff Browne839a582010-04-22 18:58:52 -0700406 mEdgeFlags = edgeFlags;
407 mMetaState = metaState;
Jeff Browne959ed22011-05-06 18:20:01 -0700408 mButtonState = buttonState;
Jeff Brownf4a4ec22010-06-16 01:53:36 -0700409 mXOffset = xOffset;
410 mYOffset = yOffset;
Jeff Browne839a582010-04-22 18:58:52 -0700411 mXPrecision = xPrecision;
412 mYPrecision = yPrecision;
413 mDownTime = downTime;
Jeff Browne959ed22011-05-06 18:20:01 -0700414 mPointerProperties.clear();
415 mPointerProperties.appendArray(pointerProperties, pointerCount);
Jeff Browne839a582010-04-22 18:58:52 -0700416 mSampleEventTimes.clear();
417 mSamplePointerCoords.clear();
418 addSample(eventTime, pointerCoords);
419}
420
Jeff Brown3e341462011-02-14 17:03:18 -0800421void MotionEvent::copyFrom(const MotionEvent* other, bool keepHistory) {
422 InputEvent::initialize(other->mDeviceId, other->mSource);
423 mAction = other->mAction;
424 mFlags = other->mFlags;
425 mEdgeFlags = other->mEdgeFlags;
426 mMetaState = other->mMetaState;
Jeff Browne959ed22011-05-06 18:20:01 -0700427 mButtonState = other->mButtonState;
Jeff Brown3e341462011-02-14 17:03:18 -0800428 mXOffset = other->mXOffset;
429 mYOffset = other->mYOffset;
430 mXPrecision = other->mXPrecision;
431 mYPrecision = other->mYPrecision;
432 mDownTime = other->mDownTime;
Jeff Browne959ed22011-05-06 18:20:01 -0700433 mPointerProperties = other->mPointerProperties;
Jeff Brown3e341462011-02-14 17:03:18 -0800434
435 if (keepHistory) {
436 mSampleEventTimes = other->mSampleEventTimes;
437 mSamplePointerCoords = other->mSamplePointerCoords;
438 } else {
439 mSampleEventTimes.clear();
440 mSampleEventTimes.push(other->getEventTime());
441 mSamplePointerCoords.clear();
442 size_t pointerCount = other->getPointerCount();
443 size_t historySize = other->getHistorySize();
444 mSamplePointerCoords.appendArray(other->mSamplePointerCoords.array()
445 + (historySize * pointerCount), pointerCount);
446 }
447}
448
Jeff Browne839a582010-04-22 18:58:52 -0700449void MotionEvent::addSample(
450 int64_t eventTime,
451 const PointerCoords* pointerCoords) {
452 mSampleEventTimes.push(eventTime);
453 mSamplePointerCoords.appendArray(pointerCoords, getPointerCount());
454}
455
Jeff Brown3e341462011-02-14 17:03:18 -0800456const PointerCoords* MotionEvent::getRawPointerCoords(size_t pointerIndex) const {
457 return &mSamplePointerCoords[getHistorySize() * getPointerCount() + pointerIndex];
458}
459
460float MotionEvent::getRawAxisValue(int32_t axis, size_t pointerIndex) const {
461 return getRawPointerCoords(pointerIndex)->getAxisValue(axis);
462}
463
464float MotionEvent::getAxisValue(int32_t axis, size_t pointerIndex) const {
465 float value = getRawPointerCoords(pointerIndex)->getAxisValue(axis);
466 switch (axis) {
Jeff Brownb2d44352011-02-17 13:01:34 -0800467 case AMOTION_EVENT_AXIS_X:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400468 return value + mXOffset;
Jeff Brownb2d44352011-02-17 13:01:34 -0800469 case AMOTION_EVENT_AXIS_Y:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400470 return value + mYOffset;
Jeff Brown3e341462011-02-14 17:03:18 -0800471 }
472 return value;
473}
474
475const PointerCoords* MotionEvent::getHistoricalRawPointerCoords(
476 size_t pointerIndex, size_t historicalIndex) const {
477 return &mSamplePointerCoords[historicalIndex * getPointerCount() + pointerIndex];
478}
479
480float MotionEvent::getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex,
481 size_t historicalIndex) const {
482 return getHistoricalRawPointerCoords(pointerIndex, historicalIndex)->getAxisValue(axis);
483}
484
485float MotionEvent::getHistoricalAxisValue(int32_t axis, size_t pointerIndex,
486 size_t historicalIndex) const {
487 float value = getHistoricalRawPointerCoords(pointerIndex, historicalIndex)->getAxisValue(axis);
488 switch (axis) {
Jeff Brownb2d44352011-02-17 13:01:34 -0800489 case AMOTION_EVENT_AXIS_X:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400490 return value + mXOffset;
Jeff Brownb2d44352011-02-17 13:01:34 -0800491 case AMOTION_EVENT_AXIS_Y:
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400492 return value + mYOffset;
Jeff Brown3e341462011-02-14 17:03:18 -0800493 }
494 return value;
495}
496
Jeff Brown15933542011-03-14 19:39:54 -0700497ssize_t MotionEvent::findPointerIndex(int32_t pointerId) const {
Jeff Browne959ed22011-05-06 18:20:01 -0700498 size_t pointerCount = mPointerProperties.size();
Jeff Brown15933542011-03-14 19:39:54 -0700499 for (size_t i = 0; i < pointerCount; i++) {
Jeff Browne959ed22011-05-06 18:20:01 -0700500 if (mPointerProperties.itemAt(i).id == pointerId) {
Jeff Brown15933542011-03-14 19:39:54 -0700501 return i;
502 }
503 }
504 return -1;
505}
506
Jeff Browne839a582010-04-22 18:58:52 -0700507void MotionEvent::offsetLocation(float xOffset, float yOffset) {
Jeff Brownf4a4ec22010-06-16 01:53:36 -0700508 mXOffset += xOffset;
509 mYOffset += yOffset;
Jeff Browne839a582010-04-22 18:58:52 -0700510}
511
Jeff Brown3e341462011-02-14 17:03:18 -0800512void MotionEvent::scale(float scaleFactor) {
513 mXOffset *= scaleFactor;
514 mYOffset *= scaleFactor;
515 mXPrecision *= scaleFactor;
516 mYPrecision *= scaleFactor;
517
518 size_t numSamples = mSamplePointerCoords.size();
519 for (size_t i = 0; i < numSamples; i++) {
Dianne Hackborn16fe3c22011-04-27 18:52:56 -0400520 mSamplePointerCoords.editItemAt(i).scale(scaleFactor);
Jeff Brown3e341462011-02-14 17:03:18 -0800521 }
522}
523
524#ifdef HAVE_ANDROID_OS
525static inline float transformAngle(const SkMatrix* matrix, float angleRadians) {
526 // Construct and transform a vector oriented at the specified clockwise angle from vertical.
527 // Coordinate system: down is increasing Y, right is increasing X.
528 SkPoint vector;
529 vector.fX = SkFloatToScalar(sinf(angleRadians));
530 vector.fY = SkFloatToScalar(-cosf(angleRadians));
531 matrix->mapVectors(& vector, 1);
532
533 // Derive the transformed vector's clockwise angle from vertical.
534 float result = atan2f(SkScalarToFloat(vector.fX), SkScalarToFloat(-vector.fY));
535 if (result < - M_PI_2) {
536 result += M_PI;
537 } else if (result > M_PI_2) {
538 result -= M_PI;
539 }
540 return result;
541}
542
543void MotionEvent::transform(const SkMatrix* matrix) {
544 float oldXOffset = mXOffset;
545 float oldYOffset = mYOffset;
546
547 // The tricky part of this implementation is to preserve the value of
548 // rawX and rawY. So we apply the transformation to the first point
549 // then derive an appropriate new X/Y offset that will preserve rawX and rawY.
550 SkPoint point;
551 float rawX = getRawX(0);
552 float rawY = getRawY(0);
553 matrix->mapXY(SkFloatToScalar(rawX + oldXOffset), SkFloatToScalar(rawY + oldYOffset),
554 & point);
555 float newX = SkScalarToFloat(point.fX);
556 float newY = SkScalarToFloat(point.fY);
557 float newXOffset = newX - rawX;
558 float newYOffset = newY - rawY;
559
560 mXOffset = newXOffset;
561 mYOffset = newYOffset;
562
563 // Apply the transformation to all samples.
564 size_t numSamples = mSamplePointerCoords.size();
565 for (size_t i = 0; i < numSamples; i++) {
566 PointerCoords& c = mSamplePointerCoords.editItemAt(i);
Jeff Brown5873ce42011-07-27 16:04:54 -0700567 float x = c.getAxisValue(AMOTION_EVENT_AXIS_X) + oldXOffset;
568 float y = c.getAxisValue(AMOTION_EVENT_AXIS_Y) + oldYOffset;
569 matrix->mapXY(SkFloatToScalar(x), SkFloatToScalar(y), &point);
570 c.setAxisValue(AMOTION_EVENT_AXIS_X, SkScalarToFloat(point.fX) - newXOffset);
571 c.setAxisValue(AMOTION_EVENT_AXIS_Y, SkScalarToFloat(point.fY) - newYOffset);
Jeff Brown3e341462011-02-14 17:03:18 -0800572
Jeff Brown5873ce42011-07-27 16:04:54 -0700573 float orientation = c.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION);
574 c.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, transformAngle(matrix, orientation));
Jeff Brown3e341462011-02-14 17:03:18 -0800575 }
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();
Jeff Browne959ed22011-05-06 18:20:01 -0700591 mButtonState = parcel->readInt32();
Jeff Brown3e341462011-02-14 17:03:18 -0800592 mXOffset = parcel->readFloat();
593 mYOffset = parcel->readFloat();
594 mXPrecision = parcel->readFloat();
595 mYPrecision = parcel->readFloat();
596 mDownTime = parcel->readInt64();
597
Jeff Browne959ed22011-05-06 18:20:01 -0700598 mPointerProperties.clear();
599 mPointerProperties.setCapacity(pointerCount);
Jeff Brown3e341462011-02-14 17:03:18 -0800600 mSampleEventTimes.clear();
601 mSampleEventTimes.setCapacity(sampleCount);
602 mSamplePointerCoords.clear();
603 mSamplePointerCoords.setCapacity(sampleCount * pointerCount);
604
605 for (size_t i = 0; i < pointerCount; i++) {
Jeff Browne959ed22011-05-06 18:20:01 -0700606 mPointerProperties.push();
607 PointerProperties& properties = mPointerProperties.editTop();
608 properties.id = parcel->readInt32();
609 properties.toolType = parcel->readInt32();
Jeff Brown3e341462011-02-14 17:03:18 -0800610 }
611
612 while (sampleCount-- > 0) {
613 mSampleEventTimes.push(parcel->readInt64());
614 for (size_t i = 0; i < pointerCount; i++) {
615 mSamplePointerCoords.push();
616 status_t status = mSamplePointerCoords.editTop().readFromParcel(parcel);
Jeff Brownb2d44352011-02-17 13:01:34 -0800617 if (status) {
Jeff Brown3e341462011-02-14 17:03:18 -0800618 return status;
619 }
620 }
621 }
622 return OK;
623}
624
625status_t MotionEvent::writeToParcel(Parcel* parcel) const {
Jeff Browne959ed22011-05-06 18:20:01 -0700626 size_t pointerCount = mPointerProperties.size();
Jeff Brown3e341462011-02-14 17:03:18 -0800627 size_t sampleCount = mSampleEventTimes.size();
628
629 parcel->writeInt32(pointerCount);
630 parcel->writeInt32(sampleCount);
631
632 parcel->writeInt32(mDeviceId);
633 parcel->writeInt32(mSource);
634 parcel->writeInt32(mAction);
635 parcel->writeInt32(mFlags);
636 parcel->writeInt32(mEdgeFlags);
637 parcel->writeInt32(mMetaState);
Jeff Browne959ed22011-05-06 18:20:01 -0700638 parcel->writeInt32(mButtonState);
Jeff Brown3e341462011-02-14 17:03:18 -0800639 parcel->writeFloat(mXOffset);
640 parcel->writeFloat(mYOffset);
641 parcel->writeFloat(mXPrecision);
642 parcel->writeFloat(mYPrecision);
643 parcel->writeInt64(mDownTime);
644
645 for (size_t i = 0; i < pointerCount; i++) {
Jeff Browne959ed22011-05-06 18:20:01 -0700646 const PointerProperties& properties = mPointerProperties.itemAt(i);
647 parcel->writeInt32(properties.id);
648 parcel->writeInt32(properties.toolType);
Jeff Brown3e341462011-02-14 17:03:18 -0800649 }
650
651 const PointerCoords* pc = mSamplePointerCoords.array();
652 for (size_t h = 0; h < sampleCount; h++) {
653 parcel->writeInt64(mSampleEventTimes.itemAt(h));
654 for (size_t i = 0; i < pointerCount; i++) {
655 status_t status = (pc++)->writeToParcel(parcel);
Jeff Brownb2d44352011-02-17 13:01:34 -0800656 if (status) {
Jeff Brown3e341462011-02-14 17:03:18 -0800657 return status;
658 }
659 }
660 }
661 return OK;
662}
663#endif
664
Jeff Brownd5ed2852011-03-02 19:23:13 -0800665bool MotionEvent::isTouchEvent(int32_t source, int32_t action) {
666 if (source & AINPUT_SOURCE_CLASS_POINTER) {
667 // Specifically excludes HOVER_MOVE and SCROLL.
668 switch (action & AMOTION_EVENT_ACTION_MASK) {
669 case AMOTION_EVENT_ACTION_DOWN:
670 case AMOTION_EVENT_ACTION_MOVE:
671 case AMOTION_EVENT_ACTION_UP:
672 case AMOTION_EVENT_ACTION_POINTER_DOWN:
673 case AMOTION_EVENT_ACTION_POINTER_UP:
674 case AMOTION_EVENT_ACTION_CANCEL:
675 case AMOTION_EVENT_ACTION_OUTSIDE:
676 return true;
677 }
678 }
679 return false;
680}
681
Jeff Brown3e341462011-02-14 17:03:18 -0800682
Jeff Brownfa773aa2011-03-09 17:39:48 -0800683// --- VelocityTracker ---
684
Jeff Brownadab6202011-06-01 12:33:19 -0700685const uint32_t VelocityTracker::HISTORY_SIZE;
686const nsecs_t VelocityTracker::MAX_AGE;
Jeff Brownadab6202011-06-01 12:33:19 -0700687const nsecs_t VelocityTracker::MIN_DURATION;
688
Jeff Brownfa773aa2011-03-09 17:39:48 -0800689VelocityTracker::VelocityTracker() {
690 clear();
691}
692
693void VelocityTracker::clear() {
694 mIndex = 0;
695 mMovements[0].idBits.clear();
Jeff Brown15933542011-03-14 19:39:54 -0700696 mActivePointerId = -1;
697}
698
699void VelocityTracker::clearPointers(BitSet32 idBits) {
700 BitSet32 remainingIdBits(mMovements[mIndex].idBits.value & ~idBits.value);
701 mMovements[mIndex].idBits = remainingIdBits;
702
703 if (mActivePointerId >= 0 && idBits.hasBit(mActivePointerId)) {
704 mActivePointerId = !remainingIdBits.isEmpty() ? remainingIdBits.firstMarkedBit() : -1;
705 }
Jeff Brownfa773aa2011-03-09 17:39:48 -0800706}
707
708void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits, const Position* positions) {
709 if (++mIndex == HISTORY_SIZE) {
710 mIndex = 0;
711 }
Jeff Brown15933542011-03-14 19:39:54 -0700712
713 while (idBits.count() > MAX_POINTERS) {
Jeff Brown5873ce42011-07-27 16:04:54 -0700714 idBits.clearLastMarkedBit();
Jeff Brown15933542011-03-14 19:39:54 -0700715 }
716
Jeff Brownfa773aa2011-03-09 17:39:48 -0800717 Movement& movement = mMovements[mIndex];
718 movement.eventTime = eventTime;
719 movement.idBits = idBits;
720 uint32_t count = idBits.count();
721 for (uint32_t i = 0; i < count; i++) {
722 movement.positions[i] = positions[i];
723 }
724
Jeff Brown15933542011-03-14 19:39:54 -0700725 if (mActivePointerId < 0 || !idBits.hasBit(mActivePointerId)) {
726 mActivePointerId = count != 0 ? idBits.firstMarkedBit() : -1;
727 }
728
Jeff Brownfa773aa2011-03-09 17:39:48 -0800729#if DEBUG_VELOCITY
Jeff Brown15933542011-03-14 19:39:54 -0700730 LOGD("VelocityTracker: addMovement eventTime=%lld, idBits=0x%08x, activePointerId=%d",
731 eventTime, idBits.value, mActivePointerId);
Jeff Brownfa773aa2011-03-09 17:39:48 -0800732 for (BitSet32 iterBits(idBits); !iterBits.isEmpty(); ) {
733 uint32_t id = iterBits.firstMarkedBit();
734 uint32_t index = idBits.getIndexOfBit(id);
735 iterBits.clearBit(id);
736 float vx, vy;
737 bool available = getVelocity(id, &vx, &vy);
738 if (available) {
Jeff Brown15933542011-03-14 19:39:54 -0700739 LOGD(" %d: position (%0.3f, %0.3f), vx=%0.3f, vy=%0.3f, speed=%0.3f",
Jeff Brownfa773aa2011-03-09 17:39:48 -0800740 id, positions[index].x, positions[index].y, vx, vy, sqrtf(vx * vx + vy * vy));
741 } else {
Jeff Brown23e0c8c2011-04-01 16:15:13 -0700742 LOG_ASSERT(vx == 0 && vy == 0);
Jeff Brownfa773aa2011-03-09 17:39:48 -0800743 LOGD(" %d: position (%0.3f, %0.3f), velocity not available",
744 id, positions[index].x, positions[index].y);
745 }
746 }
747#endif
748}
749
Jeff Brown15933542011-03-14 19:39:54 -0700750void VelocityTracker::addMovement(const MotionEvent* event) {
751 int32_t actionMasked = event->getActionMasked();
752
753 switch (actionMasked) {
754 case AMOTION_EVENT_ACTION_DOWN:
Jeff Brown137c3c52011-09-09 15:39:35 -0700755 case AMOTION_EVENT_ACTION_HOVER_ENTER:
Jeff Brown15933542011-03-14 19:39:54 -0700756 // Clear all pointers on down before adding the new movement.
757 clear();
758 break;
759 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
760 // Start a new movement trace for a pointer that just went down.
761 // We do this on down instead of on up because the client may want to query the
762 // final velocity for a pointer that just went up.
763 BitSet32 downIdBits;
Jeff Brown5873ce42011-07-27 16:04:54 -0700764 downIdBits.markBit(event->getPointerId(event->getActionIndex()));
Jeff Brown15933542011-03-14 19:39:54 -0700765 clearPointers(downIdBits);
766 break;
767 }
Jeff Brown137c3c52011-09-09 15:39:35 -0700768 case AMOTION_EVENT_ACTION_MOVE:
769 case AMOTION_EVENT_ACTION_HOVER_MOVE:
770 break;
771 default:
772 // Ignore all other actions because they do not convey any new information about
Jeff Brown15933542011-03-14 19:39:54 -0700773 // pointer movement. We also want to preserve the last known velocity of the pointers.
774 // Note that ACTION_UP and ACTION_POINTER_UP always report the last known position
775 // of the pointers that went up. ACTION_POINTER_UP does include the new position of
776 // pointers that remained down but we will also receive an ACTION_MOVE with this
777 // information if any of them actually moved. Since we don't know how many pointers
778 // will be going up at once it makes sense to just wait for the following ACTION_MOVE
779 // before adding the movement.
780 return;
781 }
782
783 size_t pointerCount = event->getPointerCount();
784 if (pointerCount > MAX_POINTERS) {
785 pointerCount = MAX_POINTERS;
786 }
787
788 BitSet32 idBits;
789 for (size_t i = 0; i < pointerCount; i++) {
790 idBits.markBit(event->getPointerId(i));
791 }
792
793 nsecs_t eventTime;
794 Position positions[pointerCount];
795
796 size_t historySize = event->getHistorySize();
797 for (size_t h = 0; h < historySize; h++) {
798 eventTime = event->getHistoricalEventTime(h);
799 for (size_t i = 0; i < pointerCount; i++) {
800 positions[i].x = event->getHistoricalX(i, h);
801 positions[i].y = event->getHistoricalY(i, h);
802 }
803 addMovement(eventTime, idBits, positions);
804 }
805
806 eventTime = event->getEventTime();
807 for (size_t i = 0; i < pointerCount; i++) {
808 positions[i].x = event->getX(i);
809 positions[i].y = event->getY(i);
810 }
811 addMovement(eventTime, idBits, positions);
812}
813
Jeff Brownfa773aa2011-03-09 17:39:48 -0800814bool VelocityTracker::getVelocity(uint32_t id, float* outVx, float* outVy) const {
815 const Movement& newestMovement = mMovements[mIndex];
816 if (newestMovement.idBits.hasBit(id)) {
Jeff Brown137c3c52011-09-09 15:39:35 -0700817 const Position& newestPosition = newestMovement.getPosition(id);
Jeff Brownfa773aa2011-03-09 17:39:48 -0800818 float accumVx = 0;
819 float accumVy = 0;
Jeff Brown137c3c52011-09-09 15:39:35 -0700820 float duration = 0;
Jeff Brown4815f2a2011-04-12 22:39:53 -0700821
Jeff Brown137c3c52011-09-09 15:39:35 -0700822 // Iterate over movement samples in reverse time order and accumulate velocity.
823 uint32_t index = mIndex;
824 do {
825 index = (index == 0 ? HISTORY_SIZE : index) - 1;
Jeff Brownfa773aa2011-03-09 17:39:48 -0800826 const Movement& movement = mMovements[index];
Jeff Brown137c3c52011-09-09 15:39:35 -0700827 if (!movement.idBits.hasBit(id)) {
828 break;
Jeff Brownfa773aa2011-03-09 17:39:48 -0800829 }
Jeff Brown137c3c52011-09-09 15:39:35 -0700830
831 nsecs_t age = newestMovement.eventTime - movement.eventTime;
832 if (age > MAX_AGE) {
833 break;
834 }
835
836 const Position& position = movement.getPosition(id);
837 accumVx += newestPosition.x - position.x;
838 accumVy += newestPosition.y - position.y;
839 duration += age;
840 } while (index != mIndex);
Jeff Brownfa773aa2011-03-09 17:39:48 -0800841
842 // Make sure we used at least one sample.
Jeff Brown137c3c52011-09-09 15:39:35 -0700843 if (duration >= MIN_DURATION) {
844 float scale = 1000000000.0f / duration; // one over time delta in seconds
845 *outVx = accumVx * scale;
846 *outVy = accumVy * scale;
Jeff Brownfa773aa2011-03-09 17:39:48 -0800847 return true;
848 }
849 }
850
851 // No data available for this pointer.
852 *outVx = 0;
853 *outVy = 0;
854 return false;
855}
856
857
Jeff Brownadab6202011-06-01 12:33:19 -0700858// --- VelocityControl ---
859
860const nsecs_t VelocityControl::STOP_TIME;
861
862VelocityControl::VelocityControl() {
863 reset();
864}
865
866void VelocityControl::setParameters(const VelocityControlParameters& parameters) {
867 mParameters = parameters;
868 reset();
869}
870
871void VelocityControl::reset() {
872 mLastMovementTime = LLONG_MIN;
873 mRawPosition.x = 0;
874 mRawPosition.y = 0;
875 mVelocityTracker.clear();
876}
877
878void VelocityControl::move(nsecs_t eventTime, float* deltaX, float* deltaY) {
879 if ((deltaX && *deltaX) || (deltaY && *deltaY)) {
880 if (eventTime >= mLastMovementTime + STOP_TIME) {
881#if DEBUG_ACCELERATION
882 LOGD("VelocityControl: stopped, last movement was %0.3fms ago",
883 (eventTime - mLastMovementTime) * 0.000001f);
884#endif
885 reset();
886 }
887
888 mLastMovementTime = eventTime;
889 if (deltaX) {
890 mRawPosition.x += *deltaX;
891 }
892 if (deltaY) {
893 mRawPosition.y += *deltaY;
894 }
895 mVelocityTracker.addMovement(eventTime, BitSet32(BitSet32::valueForBit(0)), &mRawPosition);
896
897 float vx, vy;
898 float scale = mParameters.scale;
899 if (mVelocityTracker.getVelocity(0, &vx, &vy)) {
900 float speed = hypotf(vx, vy) * scale;
901 if (speed >= mParameters.highThreshold) {
902 // Apply full acceleration above the high speed threshold.
903 scale *= mParameters.acceleration;
904 } else if (speed > mParameters.lowThreshold) {
905 // Linearly interpolate the acceleration to apply between the low and high
906 // speed thresholds.
907 scale *= 1 + (speed - mParameters.lowThreshold)
908 / (mParameters.highThreshold - mParameters.lowThreshold)
909 * (mParameters.acceleration - 1);
910 }
911
912#if DEBUG_ACCELERATION
913 LOGD("VelocityControl(%0.3f, %0.3f, %0.3f, %0.3f): "
914 "vx=%0.3f, vy=%0.3f, speed=%0.3f, accel=%0.3f",
915 mParameters.scale, mParameters.lowThreshold, mParameters.highThreshold,
916 mParameters.acceleration,
917 vx, vy, speed, scale / mParameters.scale);
918#endif
919 } else {
920#if DEBUG_ACCELERATION
921 LOGD("VelocityControl(%0.3f, %0.3f, %0.3f, %0.3f): unknown velocity",
922 mParameters.scale, mParameters.lowThreshold, mParameters.highThreshold,
923 mParameters.acceleration);
924#endif
925 }
926
927 if (deltaX) {
928 *deltaX *= scale;
929 }
930 if (deltaY) {
931 *deltaY *= scale;
932 }
933 }
934}
935
936
Jeff Brown66888372010-11-29 17:37:49 -0800937// --- InputDeviceInfo ---
Jeff Browne57e8952010-07-23 21:28:06 -0700938
939InputDeviceInfo::InputDeviceInfo() {
940 initialize(-1, String8("uninitialized device info"));
941}
942
943InputDeviceInfo::InputDeviceInfo(const InputDeviceInfo& other) :
944 mId(other.mId), mName(other.mName), mSources(other.mSources),
945 mKeyboardType(other.mKeyboardType),
946 mMotionRanges(other.mMotionRanges) {
947}
948
949InputDeviceInfo::~InputDeviceInfo() {
950}
951
952void InputDeviceInfo::initialize(int32_t id, const String8& name) {
953 mId = id;
954 mName = name;
955 mSources = 0;
956 mKeyboardType = AINPUT_KEYBOARD_TYPE_NONE;
957 mMotionRanges.clear();
958}
959
Jeff Brown46689da2011-03-08 15:13:06 -0800960const InputDeviceInfo::MotionRange* InputDeviceInfo::getMotionRange(
961 int32_t axis, uint32_t source) const {
962 size_t numRanges = mMotionRanges.size();
963 for (size_t i = 0; i < numRanges; i++) {
964 const MotionRange& range = mMotionRanges.itemAt(i);
965 if (range.axis == axis && range.source == source) {
966 return &range;
967 }
968 }
969 return NULL;
Jeff Browne57e8952010-07-23 21:28:06 -0700970}
971
972void InputDeviceInfo::addSource(uint32_t source) {
973 mSources |= source;
974}
975
Jeff Brown46689da2011-03-08 15:13:06 -0800976void InputDeviceInfo::addMotionRange(int32_t axis, uint32_t source, float min, float max,
Jeff Browne57e8952010-07-23 21:28:06 -0700977 float flat, float fuzz) {
Jeff Brown46689da2011-03-08 15:13:06 -0800978 MotionRange range = { axis, source, min, max, flat, fuzz };
979 mMotionRanges.add(range);
Jeff Browne57e8952010-07-23 21:28:06 -0700980}
981
Jeff Brown46689da2011-03-08 15:13:06 -0800982void InputDeviceInfo::addMotionRange(const MotionRange& range) {
983 mMotionRanges.add(range);
Jeff Browne57e8952010-07-23 21:28:06 -0700984}
985
Jeff Browne839a582010-04-22 18:58:52 -0700986} // namespace android