1 /*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "Input"
18 //#define LOG_NDEBUG 0
19
20 #include <attestation/HmacKeyManager.h>
21 #include <cutils/compiler.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <string.h>
25
26 #include <android-base/properties.h>
27 #include <android-base/stringprintf.h>
28 #include <gui/constants.h>
29 #include <input/Input.h>
30 #include <input/InputDevice.h>
31 #include <input/InputEventLabels.h>
32
33 #ifdef __linux__
34 #include <binder/Parcel.h>
35 #endif
36 #ifdef __ANDROID__
37 #include <sys/random.h>
38 #endif
39
40 using android::base::StringPrintf;
41
42 namespace android {
43
44 namespace {
45
46 // When per-window-input-rotation is enabled, InputFlinger works in the un-rotated display
47 // coordinates and SurfaceFlinger includes the display rotation in the input window transforms.
isPerWindowInputRotationEnabled()48 bool isPerWindowInputRotationEnabled() {
49 static const bool PER_WINDOW_INPUT_ROTATION =
50 base::GetBoolProperty("persist.debug.per_window_input_rotation", false);
51
52 return PER_WINDOW_INPUT_ROTATION;
53 }
54
transformAngle(const ui::Transform & transform,float angleRadians)55 float transformAngle(const ui::Transform& transform, float angleRadians) {
56 // Construct and transform a vector oriented at the specified clockwise angle from vertical.
57 // Coordinate system: down is increasing Y, right is increasing X.
58 float x = sinf(angleRadians);
59 float y = -cosf(angleRadians);
60 vec2 transformedPoint = transform.transform(x, y);
61
62 // Determine how the origin is transformed by the matrix so that we
63 // can transform orientation vectors.
64 const vec2 origin = transform.transform(0, 0);
65
66 transformedPoint.x -= origin.x;
67 transformedPoint.y -= origin.y;
68
69 // Derive the transformed vector's clockwise angle from vertical.
70 // The return value of atan2f is in range [-pi, pi] which conforms to the orientation API.
71 return atan2f(transformedPoint.x, -transformedPoint.y);
72 }
73
74 // Rotates the given point to the specified orientation. If the display width and height are
75 // provided, the point is rotated in the screen space. Otherwise, the point is rotated about the
76 // origin. This helper is used to avoid the extra overhead of creating new Transforms.
rotatePoint(uint32_t orientation,float x,float y,int32_t displayWidth=0,int32_t displayHeight=0)77 vec2 rotatePoint(uint32_t orientation, float x, float y, int32_t displayWidth = 0,
78 int32_t displayHeight = 0) {
79 if (orientation == ui::Transform::ROT_0) {
80 return {x, y};
81 }
82
83 vec2 xy(x, y);
84 if (orientation == ui::Transform::ROT_90) {
85 xy.x = displayHeight - y;
86 xy.y = x;
87 } else if (orientation == ui::Transform::ROT_180) {
88 xy.x = displayWidth - x;
89 xy.y = displayHeight - y;
90 } else if (orientation == ui::Transform::ROT_270) {
91 xy.x = y;
92 xy.y = displayWidth - x;
93 }
94 return xy;
95 }
96
applyTransformWithoutTranslation(const ui::Transform & transform,float x,float y)97 vec2 applyTransformWithoutTranslation(const ui::Transform& transform, float x, float y) {
98 const vec2 transformedXy = transform.transform(x, y);
99 const vec2 transformedOrigin = transform.transform(0, 0);
100 return transformedXy - transformedOrigin;
101 }
102
shouldDisregardWindowTranslation(uint32_t source)103 bool shouldDisregardWindowTranslation(uint32_t source) {
104 // Pointer events are the only type of events that refer to absolute coordinates on the display,
105 // so we should apply the entire window transform. For other types of events, we should make
106 // sure to not apply the window translation/offset.
107 return (source & AINPUT_SOURCE_CLASS_POINTER) == 0;
108 }
109
110 } // namespace
111
motionClassificationToString(MotionClassification classification)112 const char* motionClassificationToString(MotionClassification classification) {
113 switch (classification) {
114 case MotionClassification::NONE:
115 return "NONE";
116 case MotionClassification::AMBIGUOUS_GESTURE:
117 return "AMBIGUOUS_GESTURE";
118 case MotionClassification::DEEP_PRESS:
119 return "DEEP_PRESS";
120 }
121 }
122
123 // --- IdGenerator ---
IdGenerator(Source source)124 IdGenerator::IdGenerator(Source source) : mSource(source) {}
125
nextId() const126 int32_t IdGenerator::nextId() const {
127 constexpr uint32_t SEQUENCE_NUMBER_MASK = ~SOURCE_MASK;
128 int32_t id = 0;
129
130 // Avoid building against syscall getrandom(2) on host, which will fail build on Mac. Host doesn't
131 // use sequence number so just always return mSource.
132 #ifdef __ANDROID__
133 constexpr size_t BUF_LEN = sizeof(id);
134 size_t totalBytes = 0;
135 while (totalBytes < BUF_LEN) {
136 ssize_t bytes = TEMP_FAILURE_RETRY(getrandom(&id, BUF_LEN, GRND_NONBLOCK));
137 if (CC_UNLIKELY(bytes < 0)) {
138 ALOGW("Failed to fill in random number for sequence number: %s.", strerror(errno));
139 id = 0;
140 break;
141 }
142 totalBytes += bytes;
143 }
144 #endif // __ANDROID__
145
146 return (id & SEQUENCE_NUMBER_MASK) | static_cast<int32_t>(mSource);
147 }
148
149 // --- InputEvent ---
150
inputEventTypeToString(int32_t type)151 const char* inputEventTypeToString(int32_t type) {
152 switch (type) {
153 case AINPUT_EVENT_TYPE_KEY: {
154 return "KEY";
155 }
156 case AINPUT_EVENT_TYPE_MOTION: {
157 return "MOTION";
158 }
159 case AINPUT_EVENT_TYPE_FOCUS: {
160 return "FOCUS";
161 }
162 case AINPUT_EVENT_TYPE_CAPTURE: {
163 return "CAPTURE";
164 }
165 case AINPUT_EVENT_TYPE_DRAG: {
166 return "DRAG";
167 }
168 }
169 return "UNKNOWN";
170 }
171
verifiedKeyEventFromKeyEvent(const KeyEvent & event)172 VerifiedKeyEvent verifiedKeyEventFromKeyEvent(const KeyEvent& event) {
173 return {{VerifiedInputEvent::Type::KEY, event.getDeviceId(), event.getEventTime(),
174 event.getSource(), event.getDisplayId()},
175 event.getAction(),
176 event.getDownTime(),
177 event.getFlags() & VERIFIED_KEY_EVENT_FLAGS,
178 event.getKeyCode(),
179 event.getScanCode(),
180 event.getMetaState(),
181 event.getRepeatCount()};
182 }
183
verifiedMotionEventFromMotionEvent(const MotionEvent & event)184 VerifiedMotionEvent verifiedMotionEventFromMotionEvent(const MotionEvent& event) {
185 return {{VerifiedInputEvent::Type::MOTION, event.getDeviceId(), event.getEventTime(),
186 event.getSource(), event.getDisplayId()},
187 event.getRawX(0),
188 event.getRawY(0),
189 event.getActionMasked(),
190 event.getDownTime(),
191 event.getFlags() & VERIFIED_MOTION_EVENT_FLAGS,
192 event.getMetaState(),
193 event.getButtonState()};
194 }
195
initialize(int32_t id,int32_t deviceId,uint32_t source,int32_t displayId,std::array<uint8_t,32> hmac)196 void InputEvent::initialize(int32_t id, int32_t deviceId, uint32_t source, int32_t displayId,
197 std::array<uint8_t, 32> hmac) {
198 mId = id;
199 mDeviceId = deviceId;
200 mSource = source;
201 mDisplayId = displayId;
202 mHmac = hmac;
203 }
204
initialize(const InputEvent & from)205 void InputEvent::initialize(const InputEvent& from) {
206 mId = from.mId;
207 mDeviceId = from.mDeviceId;
208 mSource = from.mSource;
209 mDisplayId = from.mDisplayId;
210 mHmac = from.mHmac;
211 }
212
nextId()213 int32_t InputEvent::nextId() {
214 static IdGenerator idGen(IdGenerator::Source::OTHER);
215 return idGen.nextId();
216 }
217
218 // --- KeyEvent ---
219
getLabel(int32_t keyCode)220 const char* KeyEvent::getLabel(int32_t keyCode) {
221 return InputEventLookup::getLabelByKeyCode(keyCode);
222 }
223
getKeyCodeFromLabel(const char * label)224 int32_t KeyEvent::getKeyCodeFromLabel(const char* label) {
225 return InputEventLookup::getKeyCodeByLabel(label);
226 }
227
initialize(int32_t id,int32_t deviceId,uint32_t source,int32_t displayId,std::array<uint8_t,32> hmac,int32_t action,int32_t flags,int32_t keyCode,int32_t scanCode,int32_t metaState,int32_t repeatCount,nsecs_t downTime,nsecs_t eventTime)228 void KeyEvent::initialize(int32_t id, int32_t deviceId, uint32_t source, int32_t displayId,
229 std::array<uint8_t, 32> hmac, int32_t action, int32_t flags,
230 int32_t keyCode, int32_t scanCode, int32_t metaState, int32_t repeatCount,
231 nsecs_t downTime, nsecs_t eventTime) {
232 InputEvent::initialize(id, deviceId, source, displayId, hmac);
233 mAction = action;
234 mFlags = flags;
235 mKeyCode = keyCode;
236 mScanCode = scanCode;
237 mMetaState = metaState;
238 mRepeatCount = repeatCount;
239 mDownTime = downTime;
240 mEventTime = eventTime;
241 }
242
initialize(const KeyEvent & from)243 void KeyEvent::initialize(const KeyEvent& from) {
244 InputEvent::initialize(from);
245 mAction = from.mAction;
246 mFlags = from.mFlags;
247 mKeyCode = from.mKeyCode;
248 mScanCode = from.mScanCode;
249 mMetaState = from.mMetaState;
250 mRepeatCount = from.mRepeatCount;
251 mDownTime = from.mDownTime;
252 mEventTime = from.mEventTime;
253 }
254
actionToString(int32_t action)255 const char* KeyEvent::actionToString(int32_t action) {
256 // Convert KeyEvent action to string
257 switch (action) {
258 case AKEY_EVENT_ACTION_DOWN:
259 return "DOWN";
260 case AKEY_EVENT_ACTION_UP:
261 return "UP";
262 case AKEY_EVENT_ACTION_MULTIPLE:
263 return "MULTIPLE";
264 }
265 return "UNKNOWN";
266 }
267
268 // --- PointerCoords ---
269
getAxisValue(int32_t axis) const270 float PointerCoords::getAxisValue(int32_t axis) const {
271 if (axis < 0 || axis > 63 || !BitSet64::hasBit(bits, axis)){
272 return 0;
273 }
274 return values[BitSet64::getIndexOfBit(bits, axis)];
275 }
276
setAxisValue(int32_t axis,float value)277 status_t PointerCoords::setAxisValue(int32_t axis, float value) {
278 if (axis < 0 || axis > 63) {
279 return NAME_NOT_FOUND;
280 }
281
282 uint32_t index = BitSet64::getIndexOfBit(bits, axis);
283 if (!BitSet64::hasBit(bits, axis)) {
284 if (value == 0) {
285 return OK; // axes with value 0 do not need to be stored
286 }
287
288 uint32_t count = BitSet64::count(bits);
289 if (count >= MAX_AXES) {
290 tooManyAxes(axis);
291 return NO_MEMORY;
292 }
293 BitSet64::markBit(bits, axis);
294 for (uint32_t i = count; i > index; i--) {
295 values[i] = values[i - 1];
296 }
297 }
298
299 values[index] = value;
300 return OK;
301 }
302
scaleAxisValue(PointerCoords & c,int axis,float scaleFactor)303 static inline void scaleAxisValue(PointerCoords& c, int axis, float scaleFactor) {
304 float value = c.getAxisValue(axis);
305 if (value != 0) {
306 c.setAxisValue(axis, value * scaleFactor);
307 }
308 }
309
scale(float globalScaleFactor,float windowXScale,float windowYScale)310 void PointerCoords::scale(float globalScaleFactor, float windowXScale, float windowYScale) {
311 // No need to scale pressure or size since they are normalized.
312 // No need to scale orientation since it is meaningless to do so.
313
314 // If there is a global scale factor, it is included in the windowX/YScale
315 // so we don't need to apply it twice to the X/Y axes.
316 // However we don't want to apply any windowXYScale not included in the global scale
317 // to the TOUCH_MAJOR/MINOR coordinates.
318 scaleAxisValue(*this, AMOTION_EVENT_AXIS_X, windowXScale);
319 scaleAxisValue(*this, AMOTION_EVENT_AXIS_Y, windowYScale);
320 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOUCH_MAJOR, globalScaleFactor);
321 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOUCH_MINOR, globalScaleFactor);
322 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOOL_MAJOR, globalScaleFactor);
323 scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOOL_MINOR, globalScaleFactor);
324 scaleAxisValue(*this, AMOTION_EVENT_AXIS_RELATIVE_X, windowXScale);
325 scaleAxisValue(*this, AMOTION_EVENT_AXIS_RELATIVE_Y, windowYScale);
326 }
327
scale(float globalScaleFactor)328 void PointerCoords::scale(float globalScaleFactor) {
329 scale(globalScaleFactor, globalScaleFactor, globalScaleFactor);
330 }
331
applyOffset(float xOffset,float yOffset)332 void PointerCoords::applyOffset(float xOffset, float yOffset) {
333 setAxisValue(AMOTION_EVENT_AXIS_X, getX() + xOffset);
334 setAxisValue(AMOTION_EVENT_AXIS_Y, getY() + yOffset);
335 }
336
337 #ifdef __linux__
readFromParcel(Parcel * parcel)338 status_t PointerCoords::readFromParcel(Parcel* parcel) {
339 bits = parcel->readInt64();
340
341 uint32_t count = BitSet64::count(bits);
342 if (count > MAX_AXES) {
343 return BAD_VALUE;
344 }
345
346 for (uint32_t i = 0; i < count; i++) {
347 values[i] = parcel->readFloat();
348 }
349 return OK;
350 }
351
writeToParcel(Parcel * parcel) const352 status_t PointerCoords::writeToParcel(Parcel* parcel) const {
353 parcel->writeInt64(bits);
354
355 uint32_t count = BitSet64::count(bits);
356 for (uint32_t i = 0; i < count; i++) {
357 parcel->writeFloat(values[i]);
358 }
359 return OK;
360 }
361 #endif
362
tooManyAxes(int axis)363 void PointerCoords::tooManyAxes(int axis) {
364 ALOGW("Could not set value for axis %d because the PointerCoords structure is full and "
365 "cannot contain more than %d axis values.", axis, int(MAX_AXES));
366 }
367
operator ==(const PointerCoords & other) const368 bool PointerCoords::operator==(const PointerCoords& other) const {
369 if (bits != other.bits) {
370 return false;
371 }
372 uint32_t count = BitSet64::count(bits);
373 for (uint32_t i = 0; i < count; i++) {
374 if (values[i] != other.values[i]) {
375 return false;
376 }
377 }
378 return true;
379 }
380
copyFrom(const PointerCoords & other)381 void PointerCoords::copyFrom(const PointerCoords& other) {
382 bits = other.bits;
383 uint32_t count = BitSet64::count(bits);
384 for (uint32_t i = 0; i < count; i++) {
385 values[i] = other.values[i];
386 }
387 }
388
transform(const ui::Transform & transform)389 void PointerCoords::transform(const ui::Transform& transform) {
390 const vec2 xy = transform.transform(getXYValue());
391 setAxisValue(AMOTION_EVENT_AXIS_X, xy.x);
392 setAxisValue(AMOTION_EVENT_AXIS_Y, xy.y);
393
394 if (BitSet64::hasBit(bits, AMOTION_EVENT_AXIS_RELATIVE_X) ||
395 BitSet64::hasBit(bits, AMOTION_EVENT_AXIS_RELATIVE_Y)) {
396 const ui::Transform rotation(transform.getOrientation());
397 const vec2 relativeXy = rotation.transform(getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
398 getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y));
399 setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, relativeXy.x);
400 setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, relativeXy.y);
401 }
402
403 if (BitSet64::hasBit(bits, AMOTION_EVENT_AXIS_ORIENTATION)) {
404 const float val = getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION);
405 setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, transformAngle(transform, val));
406 }
407 }
408
409 // --- PointerProperties ---
410
operator ==(const PointerProperties & other) const411 bool PointerProperties::operator==(const PointerProperties& other) const {
412 return id == other.id
413 && toolType == other.toolType;
414 }
415
copyFrom(const PointerProperties & other)416 void PointerProperties::copyFrom(const PointerProperties& other) {
417 id = other.id;
418 toolType = other.toolType;
419 }
420
421
422 // --- MotionEvent ---
423
initialize(int32_t id,int32_t deviceId,uint32_t source,int32_t displayId,std::array<uint8_t,32> hmac,int32_t action,int32_t actionButton,int32_t flags,int32_t edgeFlags,int32_t metaState,int32_t buttonState,MotionClassification classification,const ui::Transform & transform,float xPrecision,float yPrecision,float rawXCursorPosition,float rawYCursorPosition,uint32_t displayOrientation,int32_t displayWidth,int32_t displayHeight,nsecs_t downTime,nsecs_t eventTime,size_t pointerCount,const PointerProperties * pointerProperties,const PointerCoords * pointerCoords)424 void MotionEvent::initialize(int32_t id, int32_t deviceId, uint32_t source, int32_t displayId,
425 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton,
426 int32_t flags, int32_t edgeFlags, int32_t metaState,
427 int32_t buttonState, MotionClassification classification,
428 const ui::Transform& transform, float xPrecision, float yPrecision,
429 float rawXCursorPosition, float rawYCursorPosition,
430 uint32_t displayOrientation, int32_t displayWidth,
431 int32_t displayHeight, nsecs_t downTime, nsecs_t eventTime,
432 size_t pointerCount, const PointerProperties* pointerProperties,
433 const PointerCoords* pointerCoords) {
434 InputEvent::initialize(id, deviceId, source, displayId, hmac);
435 mAction = action;
436 mActionButton = actionButton;
437 mFlags = flags;
438 mEdgeFlags = edgeFlags;
439 mMetaState = metaState;
440 mButtonState = buttonState;
441 mClassification = classification;
442 mTransform = transform;
443 mXPrecision = xPrecision;
444 mYPrecision = yPrecision;
445 mRawXCursorPosition = rawXCursorPosition;
446 mRawYCursorPosition = rawYCursorPosition;
447 mDisplayOrientation = displayOrientation;
448 mDisplayWidth = displayWidth;
449 mDisplayHeight = displayHeight;
450 mDownTime = downTime;
451 mPointerProperties.clear();
452 mPointerProperties.appendArray(pointerProperties, pointerCount);
453 mSampleEventTimes.clear();
454 mSamplePointerCoords.clear();
455 addSample(eventTime, pointerCoords);
456 }
457
copyFrom(const MotionEvent * other,bool keepHistory)458 void MotionEvent::copyFrom(const MotionEvent* other, bool keepHistory) {
459 InputEvent::initialize(other->mId, other->mDeviceId, other->mSource, other->mDisplayId,
460 other->mHmac);
461 mAction = other->mAction;
462 mActionButton = other->mActionButton;
463 mFlags = other->mFlags;
464 mEdgeFlags = other->mEdgeFlags;
465 mMetaState = other->mMetaState;
466 mButtonState = other->mButtonState;
467 mClassification = other->mClassification;
468 mTransform = other->mTransform;
469 mXPrecision = other->mXPrecision;
470 mYPrecision = other->mYPrecision;
471 mRawXCursorPosition = other->mRawXCursorPosition;
472 mRawYCursorPosition = other->mRawYCursorPosition;
473 mDisplayOrientation = other->mDisplayOrientation;
474 mDisplayWidth = other->mDisplayWidth;
475 mDisplayHeight = other->mDisplayHeight;
476 mDownTime = other->mDownTime;
477 mPointerProperties = other->mPointerProperties;
478
479 if (keepHistory) {
480 mSampleEventTimes = other->mSampleEventTimes;
481 mSamplePointerCoords = other->mSamplePointerCoords;
482 } else {
483 mSampleEventTimes.clear();
484 mSampleEventTimes.push_back(other->getEventTime());
485 mSamplePointerCoords.clear();
486 size_t pointerCount = other->getPointerCount();
487 size_t historySize = other->getHistorySize();
488 mSamplePointerCoords.appendArray(other->mSamplePointerCoords.array()
489 + (historySize * pointerCount), pointerCount);
490 }
491 }
492
addSample(int64_t eventTime,const PointerCoords * pointerCoords)493 void MotionEvent::addSample(
494 int64_t eventTime,
495 const PointerCoords* pointerCoords) {
496 mSampleEventTimes.push_back(eventTime);
497 mSamplePointerCoords.appendArray(pointerCoords, getPointerCount());
498 }
499
getXCursorPosition() const500 float MotionEvent::getXCursorPosition() const {
501 vec2 vals = mTransform.transform(getRawXCursorPosition(), getRawYCursorPosition());
502 return vals.x;
503 }
504
getYCursorPosition() const505 float MotionEvent::getYCursorPosition() const {
506 vec2 vals = mTransform.transform(getRawXCursorPosition(), getRawYCursorPosition());
507 return vals.y;
508 }
509
setCursorPosition(float x,float y)510 void MotionEvent::setCursorPosition(float x, float y) {
511 ui::Transform inverse = mTransform.inverse();
512 vec2 vals = inverse.transform(x, y);
513 mRawXCursorPosition = vals.x;
514 mRawYCursorPosition = vals.y;
515 }
516
getRawPointerCoords(size_t pointerIndex) const517 const PointerCoords* MotionEvent::getRawPointerCoords(size_t pointerIndex) const {
518 return &mSamplePointerCoords[getHistorySize() * getPointerCount() + pointerIndex];
519 }
520
getRawAxisValue(int32_t axis,size_t pointerIndex) const521 float MotionEvent::getRawAxisValue(int32_t axis, size_t pointerIndex) const {
522 return getHistoricalRawAxisValue(axis, pointerIndex, getHistorySize());
523 }
524
getAxisValue(int32_t axis,size_t pointerIndex) const525 float MotionEvent::getAxisValue(int32_t axis, size_t pointerIndex) const {
526 return getHistoricalAxisValue(axis, pointerIndex, getHistorySize());
527 }
528
getHistoricalRawPointerCoords(size_t pointerIndex,size_t historicalIndex) const529 const PointerCoords* MotionEvent::getHistoricalRawPointerCoords(
530 size_t pointerIndex, size_t historicalIndex) const {
531 return &mSamplePointerCoords[historicalIndex * getPointerCount() + pointerIndex];
532 }
533
getHistoricalRawAxisValue(int32_t axis,size_t pointerIndex,size_t historicalIndex) const534 float MotionEvent::getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex,
535 size_t historicalIndex) const {
536 const PointerCoords* coords = getHistoricalRawPointerCoords(pointerIndex, historicalIndex);
537
538 if (!isPerWindowInputRotationEnabled()) return coords->getAxisValue(axis);
539
540 if (axis == AMOTION_EVENT_AXIS_X || axis == AMOTION_EVENT_AXIS_Y) {
541 // For compatibility, convert raw coordinates into "oriented screen space". Once app
542 // developers are educated about getRaw, we can consider removing this.
543 const vec2 xy = shouldDisregardWindowTranslation(mSource)
544 ? rotatePoint(mDisplayOrientation, coords->getX(), coords->getY())
545 : rotatePoint(mDisplayOrientation, coords->getX(), coords->getY(), mDisplayWidth,
546 mDisplayHeight);
547 static_assert(AMOTION_EVENT_AXIS_X == 0 && AMOTION_EVENT_AXIS_Y == 1);
548 return xy[axis];
549 }
550
551 if (axis == AMOTION_EVENT_AXIS_RELATIVE_X || axis == AMOTION_EVENT_AXIS_RELATIVE_Y) {
552 // For compatibility, since we convert raw coordinates into "oriented screen space", we
553 // need to convert the relative axes into the same orientation for consistency.
554 const vec2 relativeXy = rotatePoint(mDisplayOrientation,
555 coords->getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
556 coords->getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y));
557 return axis == AMOTION_EVENT_AXIS_RELATIVE_X ? relativeXy.x : relativeXy.y;
558 }
559
560 return coords->getAxisValue(axis);
561 }
562
getHistoricalAxisValue(int32_t axis,size_t pointerIndex,size_t historicalIndex) const563 float MotionEvent::getHistoricalAxisValue(int32_t axis, size_t pointerIndex,
564 size_t historicalIndex) const {
565 const PointerCoords* coords = getHistoricalRawPointerCoords(pointerIndex, historicalIndex);
566
567 if (axis == AMOTION_EVENT_AXIS_X || axis == AMOTION_EVENT_AXIS_Y) {
568 const vec2 xy = shouldDisregardWindowTranslation(mSource)
569 ? applyTransformWithoutTranslation(mTransform, coords->getX(), coords->getY())
570 : mTransform.transform(coords->getXYValue());
571 static_assert(AMOTION_EVENT_AXIS_X == 0 && AMOTION_EVENT_AXIS_Y == 1);
572 return xy[axis];
573 }
574
575 if (axis == AMOTION_EVENT_AXIS_RELATIVE_X || axis == AMOTION_EVENT_AXIS_RELATIVE_Y) {
576 const vec2 relativeXy =
577 applyTransformWithoutTranslation(mTransform,
578 coords->getAxisValue(
579 AMOTION_EVENT_AXIS_RELATIVE_X),
580 coords->getAxisValue(
581 AMOTION_EVENT_AXIS_RELATIVE_Y));
582 return axis == AMOTION_EVENT_AXIS_RELATIVE_X ? relativeXy.x : relativeXy.y;
583 }
584
585 return coords->getAxisValue(axis);
586 }
587
findPointerIndex(int32_t pointerId) const588 ssize_t MotionEvent::findPointerIndex(int32_t pointerId) const {
589 size_t pointerCount = mPointerProperties.size();
590 for (size_t i = 0; i < pointerCount; i++) {
591 if (mPointerProperties.itemAt(i).id == pointerId) {
592 return i;
593 }
594 }
595 return -1;
596 }
597
offsetLocation(float xOffset,float yOffset)598 void MotionEvent::offsetLocation(float xOffset, float yOffset) {
599 float currXOffset = mTransform.tx();
600 float currYOffset = mTransform.ty();
601 mTransform.set(currXOffset + xOffset, currYOffset + yOffset);
602 }
603
scale(float globalScaleFactor)604 void MotionEvent::scale(float globalScaleFactor) {
605 mTransform.set(mTransform.tx() * globalScaleFactor, mTransform.ty() * globalScaleFactor);
606 mXPrecision *= globalScaleFactor;
607 mYPrecision *= globalScaleFactor;
608
609 size_t numSamples = mSamplePointerCoords.size();
610 for (size_t i = 0; i < numSamples; i++) {
611 mSamplePointerCoords.editItemAt(i).scale(globalScaleFactor, globalScaleFactor,
612 globalScaleFactor);
613 }
614 }
615
transform(const std::array<float,9> & matrix)616 void MotionEvent::transform(const std::array<float, 9>& matrix) {
617 // We want to preserve the raw axes values stored in the PointerCoords, so we just update the
618 // transform using the values passed in.
619 ui::Transform newTransform;
620 newTransform.set(matrix);
621 mTransform = newTransform * mTransform;
622
623 // We need to update the AXIS_ORIENTATION value here to maintain the old behavior where the
624 // orientation angle is not affected by the initial transformation set in the MotionEvent.
625 std::for_each(mSamplePointerCoords.begin(), mSamplePointerCoords.end(),
626 [&newTransform](PointerCoords& c) {
627 float orientation = c.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION);
628 c.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION,
629 transformAngle(newTransform, orientation));
630 });
631 }
632
applyTransform(const std::array<float,9> & matrix)633 void MotionEvent::applyTransform(const std::array<float, 9>& matrix) {
634 ui::Transform transform;
635 transform.set(matrix);
636
637 // Apply the transformation to all samples.
638 std::for_each(mSamplePointerCoords.begin(), mSamplePointerCoords.end(),
639 [&transform](PointerCoords& c) { c.transform(transform); });
640
641 if (mRawXCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
642 mRawYCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
643 const vec2 cursor = transform.transform(mRawXCursorPosition, mRawYCursorPosition);
644 mRawXCursorPosition = cursor.x;
645 mRawYCursorPosition = cursor.y;
646 }
647 }
648
649 #ifdef __linux__
readFromParcel(ui::Transform & transform,const Parcel & parcel)650 static status_t readFromParcel(ui::Transform& transform, const Parcel& parcel) {
651 float dsdx, dtdx, tx, dtdy, dsdy, ty;
652 status_t status = parcel.readFloat(&dsdx);
653 status |= parcel.readFloat(&dtdx);
654 status |= parcel.readFloat(&tx);
655 status |= parcel.readFloat(&dtdy);
656 status |= parcel.readFloat(&dsdy);
657 status |= parcel.readFloat(&ty);
658
659 transform.set({dsdx, dtdx, tx, dtdy, dsdy, ty, 0, 0, 1});
660 return status;
661 }
662
writeToParcel(const ui::Transform & transform,Parcel & parcel)663 static status_t writeToParcel(const ui::Transform& transform, Parcel& parcel) {
664 status_t status = parcel.writeFloat(transform.dsdx());
665 status |= parcel.writeFloat(transform.dtdx());
666 status |= parcel.writeFloat(transform.tx());
667 status |= parcel.writeFloat(transform.dtdy());
668 status |= parcel.writeFloat(transform.dsdy());
669 status |= parcel.writeFloat(transform.ty());
670 return status;
671 }
672
readFromParcel(Parcel * parcel)673 status_t MotionEvent::readFromParcel(Parcel* parcel) {
674 size_t pointerCount = parcel->readInt32();
675 size_t sampleCount = parcel->readInt32();
676 if (pointerCount == 0 || pointerCount > MAX_POINTERS ||
677 sampleCount == 0 || sampleCount > MAX_SAMPLES) {
678 return BAD_VALUE;
679 }
680
681 mId = parcel->readInt32();
682 mDeviceId = parcel->readInt32();
683 mSource = parcel->readUint32();
684 mDisplayId = parcel->readInt32();
685 std::vector<uint8_t> hmac;
686 status_t result = parcel->readByteVector(&hmac);
687 if (result != OK || hmac.size() != 32) {
688 return BAD_VALUE;
689 }
690 std::move(hmac.begin(), hmac.begin() + hmac.size(), mHmac.begin());
691 mAction = parcel->readInt32();
692 mActionButton = parcel->readInt32();
693 mFlags = parcel->readInt32();
694 mEdgeFlags = parcel->readInt32();
695 mMetaState = parcel->readInt32();
696 mButtonState = parcel->readInt32();
697 mClassification = static_cast<MotionClassification>(parcel->readByte());
698
699 result = android::readFromParcel(mTransform, *parcel);
700 if (result != OK) {
701 return result;
702 }
703 mXPrecision = parcel->readFloat();
704 mYPrecision = parcel->readFloat();
705 mRawXCursorPosition = parcel->readFloat();
706 mRawYCursorPosition = parcel->readFloat();
707 mDisplayOrientation = parcel->readUint32();
708 mDisplayWidth = parcel->readInt32();
709 mDisplayHeight = parcel->readInt32();
710 mDownTime = parcel->readInt64();
711
712 mPointerProperties.clear();
713 mPointerProperties.setCapacity(pointerCount);
714 mSampleEventTimes.clear();
715 mSampleEventTimes.reserve(sampleCount);
716 mSamplePointerCoords.clear();
717 mSamplePointerCoords.setCapacity(sampleCount * pointerCount);
718
719 for (size_t i = 0; i < pointerCount; i++) {
720 mPointerProperties.push();
721 PointerProperties& properties = mPointerProperties.editTop();
722 properties.id = parcel->readInt32();
723 properties.toolType = parcel->readInt32();
724 }
725
726 while (sampleCount > 0) {
727 sampleCount--;
728 mSampleEventTimes.push_back(parcel->readInt64());
729 for (size_t i = 0; i < pointerCount; i++) {
730 mSamplePointerCoords.push();
731 status_t status = mSamplePointerCoords.editTop().readFromParcel(parcel);
732 if (status) {
733 return status;
734 }
735 }
736 }
737 return OK;
738 }
739
writeToParcel(Parcel * parcel) const740 status_t MotionEvent::writeToParcel(Parcel* parcel) const {
741 size_t pointerCount = mPointerProperties.size();
742 size_t sampleCount = mSampleEventTimes.size();
743
744 parcel->writeInt32(pointerCount);
745 parcel->writeInt32(sampleCount);
746
747 parcel->writeInt32(mId);
748 parcel->writeInt32(mDeviceId);
749 parcel->writeUint32(mSource);
750 parcel->writeInt32(mDisplayId);
751 std::vector<uint8_t> hmac(mHmac.begin(), mHmac.end());
752 parcel->writeByteVector(hmac);
753 parcel->writeInt32(mAction);
754 parcel->writeInt32(mActionButton);
755 parcel->writeInt32(mFlags);
756 parcel->writeInt32(mEdgeFlags);
757 parcel->writeInt32(mMetaState);
758 parcel->writeInt32(mButtonState);
759 parcel->writeByte(static_cast<int8_t>(mClassification));
760
761 status_t result = android::writeToParcel(mTransform, *parcel);
762 if (result != OK) {
763 return result;
764 }
765 parcel->writeFloat(mXPrecision);
766 parcel->writeFloat(mYPrecision);
767 parcel->writeFloat(mRawXCursorPosition);
768 parcel->writeFloat(mRawYCursorPosition);
769 parcel->writeUint32(mDisplayOrientation);
770 parcel->writeInt32(mDisplayWidth);
771 parcel->writeInt32(mDisplayHeight);
772 parcel->writeInt64(mDownTime);
773
774 for (size_t i = 0; i < pointerCount; i++) {
775 const PointerProperties& properties = mPointerProperties.itemAt(i);
776 parcel->writeInt32(properties.id);
777 parcel->writeInt32(properties.toolType);
778 }
779
780 const PointerCoords* pc = mSamplePointerCoords.array();
781 for (size_t h = 0; h < sampleCount; h++) {
782 parcel->writeInt64(mSampleEventTimes[h]);
783 for (size_t i = 0; i < pointerCount; i++) {
784 status_t status = (pc++)->writeToParcel(parcel);
785 if (status) {
786 return status;
787 }
788 }
789 }
790 return OK;
791 }
792 #endif
793
isTouchEvent(uint32_t source,int32_t action)794 bool MotionEvent::isTouchEvent(uint32_t source, int32_t action) {
795 if (source & AINPUT_SOURCE_CLASS_POINTER) {
796 // Specifically excludes HOVER_MOVE and SCROLL.
797 switch (action & AMOTION_EVENT_ACTION_MASK) {
798 case AMOTION_EVENT_ACTION_DOWN:
799 case AMOTION_EVENT_ACTION_MOVE:
800 case AMOTION_EVENT_ACTION_UP:
801 case AMOTION_EVENT_ACTION_POINTER_DOWN:
802 case AMOTION_EVENT_ACTION_POINTER_UP:
803 case AMOTION_EVENT_ACTION_CANCEL:
804 case AMOTION_EVENT_ACTION_OUTSIDE:
805 return true;
806 }
807 }
808 return false;
809 }
810
getLabel(int32_t axis)811 const char* MotionEvent::getLabel(int32_t axis) {
812 return InputEventLookup::getAxisLabel(axis);
813 }
814
getAxisFromLabel(const char * label)815 int32_t MotionEvent::getAxisFromLabel(const char* label) {
816 return InputEventLookup::getAxisByLabel(label);
817 }
818
actionToString(int32_t action)819 std::string MotionEvent::actionToString(int32_t action) {
820 // Convert MotionEvent action to string
821 switch (action & AMOTION_EVENT_ACTION_MASK) {
822 case AMOTION_EVENT_ACTION_DOWN:
823 return "DOWN";
824 case AMOTION_EVENT_ACTION_UP:
825 return "UP";
826 case AMOTION_EVENT_ACTION_MOVE:
827 return "MOVE";
828 case AMOTION_EVENT_ACTION_CANCEL:
829 return "CANCEL";
830 case AMOTION_EVENT_ACTION_OUTSIDE:
831 return "OUTSIDE";
832 case AMOTION_EVENT_ACTION_POINTER_DOWN:
833 return "POINTER_DOWN";
834 case AMOTION_EVENT_ACTION_POINTER_UP:
835 return "POINTER_UP";
836 case AMOTION_EVENT_ACTION_HOVER_MOVE:
837 return "HOVER_MOVE";
838 case AMOTION_EVENT_ACTION_SCROLL:
839 return "SCROLL";
840 case AMOTION_EVENT_ACTION_HOVER_ENTER:
841 return "HOVER_ENTER";
842 case AMOTION_EVENT_ACTION_HOVER_EXIT:
843 return "HOVER_EXIT";
844 case AMOTION_EVENT_ACTION_BUTTON_PRESS:
845 return "BUTTON_PRESS";
846 case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
847 return "BUTTON_RELEASE";
848 }
849 return android::base::StringPrintf("%" PRId32, action);
850 }
851
852 // --- FocusEvent ---
853
initialize(int32_t id,bool hasFocus,bool inTouchMode)854 void FocusEvent::initialize(int32_t id, bool hasFocus, bool inTouchMode) {
855 InputEvent::initialize(id, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, AINPUT_SOURCE_UNKNOWN,
856 ADISPLAY_ID_NONE, INVALID_HMAC);
857 mHasFocus = hasFocus;
858 mInTouchMode = inTouchMode;
859 }
860
initialize(const FocusEvent & from)861 void FocusEvent::initialize(const FocusEvent& from) {
862 InputEvent::initialize(from);
863 mHasFocus = from.mHasFocus;
864 mInTouchMode = from.mInTouchMode;
865 }
866
867 // --- CaptureEvent ---
868
initialize(int32_t id,bool pointerCaptureEnabled)869 void CaptureEvent::initialize(int32_t id, bool pointerCaptureEnabled) {
870 InputEvent::initialize(id, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, AINPUT_SOURCE_UNKNOWN,
871 ADISPLAY_ID_NONE, INVALID_HMAC);
872 mPointerCaptureEnabled = pointerCaptureEnabled;
873 }
874
initialize(const CaptureEvent & from)875 void CaptureEvent::initialize(const CaptureEvent& from) {
876 InputEvent::initialize(from);
877 mPointerCaptureEnabled = from.mPointerCaptureEnabled;
878 }
879
880 // --- DragEvent ---
881
initialize(int32_t id,float x,float y,bool isExiting)882 void DragEvent::initialize(int32_t id, float x, float y, bool isExiting) {
883 InputEvent::initialize(id, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, AINPUT_SOURCE_UNKNOWN,
884 ADISPLAY_ID_NONE, INVALID_HMAC);
885 mIsExiting = isExiting;
886 mX = x;
887 mY = y;
888 }
889
initialize(const DragEvent & from)890 void DragEvent::initialize(const DragEvent& from) {
891 InputEvent::initialize(from);
892 mIsExiting = from.mIsExiting;
893 mX = from.mX;
894 mY = from.mY;
895 }
896
897 // --- PooledInputEventFactory ---
898
PooledInputEventFactory(size_t maxPoolSize)899 PooledInputEventFactory::PooledInputEventFactory(size_t maxPoolSize) :
900 mMaxPoolSize(maxPoolSize) {
901 }
902
~PooledInputEventFactory()903 PooledInputEventFactory::~PooledInputEventFactory() {
904 }
905
createKeyEvent()906 KeyEvent* PooledInputEventFactory::createKeyEvent() {
907 if (mKeyEventPool.empty()) {
908 return new KeyEvent();
909 }
910 KeyEvent* event = mKeyEventPool.front().release();
911 mKeyEventPool.pop();
912 return event;
913 }
914
createMotionEvent()915 MotionEvent* PooledInputEventFactory::createMotionEvent() {
916 if (mMotionEventPool.empty()) {
917 return new MotionEvent();
918 }
919 MotionEvent* event = mMotionEventPool.front().release();
920 mMotionEventPool.pop();
921 return event;
922 }
923
createFocusEvent()924 FocusEvent* PooledInputEventFactory::createFocusEvent() {
925 if (mFocusEventPool.empty()) {
926 return new FocusEvent();
927 }
928 FocusEvent* event = mFocusEventPool.front().release();
929 mFocusEventPool.pop();
930 return event;
931 }
932
createCaptureEvent()933 CaptureEvent* PooledInputEventFactory::createCaptureEvent() {
934 if (mCaptureEventPool.empty()) {
935 return new CaptureEvent();
936 }
937 CaptureEvent* event = mCaptureEventPool.front().release();
938 mCaptureEventPool.pop();
939 return event;
940 }
941
createDragEvent()942 DragEvent* PooledInputEventFactory::createDragEvent() {
943 if (mDragEventPool.empty()) {
944 return new DragEvent();
945 }
946 DragEvent* event = mDragEventPool.front().release();
947 mDragEventPool.pop();
948 return event;
949 }
950
recycle(InputEvent * event)951 void PooledInputEventFactory::recycle(InputEvent* event) {
952 switch (event->getType()) {
953 case AINPUT_EVENT_TYPE_KEY:
954 if (mKeyEventPool.size() < mMaxPoolSize) {
955 mKeyEventPool.push(std::unique_ptr<KeyEvent>(static_cast<KeyEvent*>(event)));
956 return;
957 }
958 break;
959 case AINPUT_EVENT_TYPE_MOTION:
960 if (mMotionEventPool.size() < mMaxPoolSize) {
961 mMotionEventPool.push(std::unique_ptr<MotionEvent>(static_cast<MotionEvent*>(event)));
962 return;
963 }
964 break;
965 case AINPUT_EVENT_TYPE_FOCUS:
966 if (mFocusEventPool.size() < mMaxPoolSize) {
967 mFocusEventPool.push(std::unique_ptr<FocusEvent>(static_cast<FocusEvent*>(event)));
968 return;
969 }
970 break;
971 case AINPUT_EVENT_TYPE_CAPTURE:
972 if (mCaptureEventPool.size() < mMaxPoolSize) {
973 mCaptureEventPool.push(
974 std::unique_ptr<CaptureEvent>(static_cast<CaptureEvent*>(event)));
975 return;
976 }
977 break;
978 case AINPUT_EVENT_TYPE_DRAG:
979 if (mDragEventPool.size() < mMaxPoolSize) {
980 mDragEventPool.push(std::unique_ptr<DragEvent>(static_cast<DragEvent*>(event)));
981 return;
982 }
983 break;
984 }
985 delete event;
986 }
987
988 } // namespace android
989