• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <string.h>
24 
25 #include <android-base/logging.h>
26 #include <android-base/stringprintf.h>
27 #include <cutils/compiler.h>
28 #include <gui/constants.h>
29 #include <input/DisplayViewport.h>
30 #include <input/Input.h>
31 #include <input/InputDevice.h>
32 #include <input/InputEventLabels.h>
33 
34 #ifdef __linux__
35 #include <binder/Parcel.h>
36 #endif
37 #ifdef __ANDROID__
38 #include <sys/random.h>
39 #endif
40 
41 using android::base::StringPrintf;
42 
43 namespace android {
44 
45 namespace {
46 
transformAngle(const ui::Transform & transform,float angleRadians)47 float transformAngle(const ui::Transform& transform, float angleRadians) {
48     // Construct and transform a vector oriented at the specified clockwise angle from vertical.
49     // Coordinate system: down is increasing Y, right is increasing X.
50     float x = sinf(angleRadians);
51     float y = -cosf(angleRadians);
52     vec2 transformedPoint = transform.transform(x, y);
53 
54     // Determine how the origin is transformed by the matrix so that we
55     // can transform orientation vectors.
56     const vec2 origin = transform.transform(0, 0);
57 
58     transformedPoint.x -= origin.x;
59     transformedPoint.y -= origin.y;
60 
61     // Derive the transformed vector's clockwise angle from vertical.
62     // The return value of atan2f is in range [-pi, pi] which conforms to the orientation API.
63     return atan2f(transformedPoint.x, -transformedPoint.y);
64 }
65 
shouldDisregardTransformation(uint32_t source)66 bool shouldDisregardTransformation(uint32_t source) {
67     // Do not apply any transformations to axes from joysticks, touchpads, or relative mice.
68     return isFromSource(source, AINPUT_SOURCE_CLASS_JOYSTICK) ||
69             isFromSource(source, AINPUT_SOURCE_CLASS_POSITION) ||
70             isFromSource(source, AINPUT_SOURCE_MOUSE_RELATIVE);
71 }
72 
shouldDisregardOffset(uint32_t source)73 bool shouldDisregardOffset(uint32_t source) {
74     // Pointer events are the only type of events that refer to absolute coordinates on the display,
75     // so we should apply the entire window transform. For other types of events, we should make
76     // sure to not apply the window translation/offset.
77     return !isFromSource(source, AINPUT_SOURCE_CLASS_POINTER);
78 }
79 
80 } // namespace
81 
motionClassificationToString(MotionClassification classification)82 const char* motionClassificationToString(MotionClassification classification) {
83     switch (classification) {
84         case MotionClassification::NONE:
85             return "NONE";
86         case MotionClassification::AMBIGUOUS_GESTURE:
87             return "AMBIGUOUS_GESTURE";
88         case MotionClassification::DEEP_PRESS:
89             return "DEEP_PRESS";
90     }
91 }
92 
motionToolTypeToString(int32_t toolType)93 const char* motionToolTypeToString(int32_t toolType) {
94     switch (toolType) {
95         case AMOTION_EVENT_TOOL_TYPE_UNKNOWN:
96             return "UNKNOWN";
97         case AMOTION_EVENT_TOOL_TYPE_FINGER:
98             return "FINGER";
99         case AMOTION_EVENT_TOOL_TYPE_STYLUS:
100             return "STYLUS";
101         case AMOTION_EVENT_TOOL_TYPE_MOUSE:
102             return "MOUSE";
103         case AMOTION_EVENT_TOOL_TYPE_ERASER:
104             return "ERASER";
105         case AMOTION_EVENT_TOOL_TYPE_PALM:
106             return "PALM";
107         default:
108             return "INVALID";
109     }
110 }
111 
112 // --- IdGenerator ---
IdGenerator(Source source)113 IdGenerator::IdGenerator(Source source) : mSource(source) {}
114 
nextId() const115 int32_t IdGenerator::nextId() const {
116     constexpr uint32_t SEQUENCE_NUMBER_MASK = ~SOURCE_MASK;
117     int32_t id = 0;
118 
119 // Avoid building against syscall getrandom(2) on host, which will fail build on Mac. Host doesn't
120 // use sequence number so just always return mSource.
121 #ifdef __ANDROID__
122     constexpr size_t BUF_LEN = sizeof(id);
123     size_t totalBytes = 0;
124     while (totalBytes < BUF_LEN) {
125         ssize_t bytes = TEMP_FAILURE_RETRY(getrandom(&id, BUF_LEN, GRND_NONBLOCK));
126         if (CC_UNLIKELY(bytes < 0)) {
127             ALOGW("Failed to fill in random number for sequence number: %s.", strerror(errno));
128             id = 0;
129             break;
130         }
131         totalBytes += bytes;
132     }
133 #endif // __ANDROID__
134 
135     return (id & SEQUENCE_NUMBER_MASK) | static_cast<int32_t>(mSource);
136 }
137 
138 // --- InputEvent ---
139 
transformWithoutTranslation(const ui::Transform & transform,const vec2 & xy)140 vec2 transformWithoutTranslation(const ui::Transform& transform, const vec2& xy) {
141     const vec2 transformedXy = transform.transform(xy);
142     const vec2 transformedOrigin = transform.transform(0, 0);
143     return transformedXy - transformedOrigin;
144 }
145 
inputEventTypeToString(int32_t type)146 const char* inputEventTypeToString(int32_t type) {
147     switch (type) {
148         case AINPUT_EVENT_TYPE_KEY: {
149             return "KEY";
150         }
151         case AINPUT_EVENT_TYPE_MOTION: {
152             return "MOTION";
153         }
154         case AINPUT_EVENT_TYPE_FOCUS: {
155             return "FOCUS";
156         }
157         case AINPUT_EVENT_TYPE_CAPTURE: {
158             return "CAPTURE";
159         }
160         case AINPUT_EVENT_TYPE_DRAG: {
161             return "DRAG";
162         }
163         case AINPUT_EVENT_TYPE_TOUCH_MODE: {
164             return "TOUCH_MODE";
165         }
166     }
167     return "UNKNOWN";
168 }
169 
inputEventSourceToString(int32_t source)170 std::string inputEventSourceToString(int32_t source) {
171     if (source == AINPUT_SOURCE_UNKNOWN) {
172         return "UNKNOWN";
173     }
174     if (source == static_cast<int32_t>(AINPUT_SOURCE_ANY)) {
175         return "ANY";
176     }
177     static const std::map<int32_t, const char*> SOURCES{
178             {AINPUT_SOURCE_KEYBOARD, "KEYBOARD"},
179             {AINPUT_SOURCE_DPAD, "DPAD"},
180             {AINPUT_SOURCE_GAMEPAD, "GAMEPAD"},
181             {AINPUT_SOURCE_TOUCHSCREEN, "TOUCHSCREEN"},
182             {AINPUT_SOURCE_MOUSE, "MOUSE"},
183             {AINPUT_SOURCE_STYLUS, "STYLUS"},
184             {AINPUT_SOURCE_BLUETOOTH_STYLUS, "BLUETOOTH_STYLUS"},
185             {AINPUT_SOURCE_TRACKBALL, "TRACKBALL"},
186             {AINPUT_SOURCE_MOUSE_RELATIVE, "MOUSE_RELATIVE"},
187             {AINPUT_SOURCE_TOUCHPAD, "TOUCHPAD"},
188             {AINPUT_SOURCE_TOUCH_NAVIGATION, "TOUCH_NAVIGATION"},
189             {AINPUT_SOURCE_JOYSTICK, "JOYSTICK"},
190             {AINPUT_SOURCE_HDMI, "HDMI"},
191             {AINPUT_SOURCE_SENSOR, "SENSOR"},
192             {AINPUT_SOURCE_ROTARY_ENCODER, "ROTARY_ENCODER"},
193     };
194     std::string result;
195     for (const auto& [source_entry, str] : SOURCES) {
196         if ((source & source_entry) == source_entry) {
197             if (!result.empty()) {
198                 result += " | ";
199             }
200             result += str;
201         }
202     }
203     if (result.empty()) {
204         result = StringPrintf("0x%08x", source);
205     }
206     return result;
207 }
208 
isFromSource(uint32_t source,uint32_t test)209 bool isFromSource(uint32_t source, uint32_t test) {
210     return (source & test) == test;
211 }
212 
verifiedKeyEventFromKeyEvent(const KeyEvent & event)213 VerifiedKeyEvent verifiedKeyEventFromKeyEvent(const KeyEvent& event) {
214     return {{VerifiedInputEvent::Type::KEY, event.getDeviceId(), event.getEventTime(),
215              event.getSource(), event.getDisplayId()},
216             event.getAction(),
217             event.getFlags() & VERIFIED_KEY_EVENT_FLAGS,
218             event.getDownTime(),
219             event.getKeyCode(),
220             event.getScanCode(),
221             event.getMetaState(),
222             event.getRepeatCount()};
223 }
224 
verifiedMotionEventFromMotionEvent(const MotionEvent & event)225 VerifiedMotionEvent verifiedMotionEventFromMotionEvent(const MotionEvent& event) {
226     return {{VerifiedInputEvent::Type::MOTION, event.getDeviceId(), event.getEventTime(),
227              event.getSource(), event.getDisplayId()},
228             event.getRawX(0),
229             event.getRawY(0),
230             event.getActionMasked(),
231             event.getFlags() & VERIFIED_MOTION_EVENT_FLAGS,
232             event.getDownTime(),
233             event.getMetaState(),
234             event.getButtonState()};
235 }
236 
initialize(int32_t id,int32_t deviceId,uint32_t source,int32_t displayId,std::array<uint8_t,32> hmac)237 void InputEvent::initialize(int32_t id, int32_t deviceId, uint32_t source, int32_t displayId,
238                             std::array<uint8_t, 32> hmac) {
239     mId = id;
240     mDeviceId = deviceId;
241     mSource = source;
242     mDisplayId = displayId;
243     mHmac = hmac;
244 }
245 
initialize(const InputEvent & from)246 void InputEvent::initialize(const InputEvent& from) {
247     mId = from.mId;
248     mDeviceId = from.mDeviceId;
249     mSource = from.mSource;
250     mDisplayId = from.mDisplayId;
251     mHmac = from.mHmac;
252 }
253 
nextId()254 int32_t InputEvent::nextId() {
255     static IdGenerator idGen(IdGenerator::Source::OTHER);
256     return idGen.nextId();
257 }
258 
259 // --- KeyEvent ---
260 
getLabel(int32_t keyCode)261 const char* KeyEvent::getLabel(int32_t keyCode) {
262     return InputEventLookup::getLabelByKeyCode(keyCode);
263 }
264 
getKeyCodeFromLabel(const char * label)265 int32_t KeyEvent::getKeyCodeFromLabel(const char* label) {
266     return InputEventLookup::getKeyCodeByLabel(label);
267 }
268 
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)269 void KeyEvent::initialize(int32_t id, int32_t deviceId, uint32_t source, int32_t displayId,
270                           std::array<uint8_t, 32> hmac, int32_t action, int32_t flags,
271                           int32_t keyCode, int32_t scanCode, int32_t metaState, int32_t repeatCount,
272                           nsecs_t downTime, nsecs_t eventTime) {
273     InputEvent::initialize(id, deviceId, source, displayId, hmac);
274     mAction = action;
275     mFlags = flags;
276     mKeyCode = keyCode;
277     mScanCode = scanCode;
278     mMetaState = metaState;
279     mRepeatCount = repeatCount;
280     mDownTime = downTime;
281     mEventTime = eventTime;
282 }
283 
initialize(const KeyEvent & from)284 void KeyEvent::initialize(const KeyEvent& from) {
285     InputEvent::initialize(from);
286     mAction = from.mAction;
287     mFlags = from.mFlags;
288     mKeyCode = from.mKeyCode;
289     mScanCode = from.mScanCode;
290     mMetaState = from.mMetaState;
291     mRepeatCount = from.mRepeatCount;
292     mDownTime = from.mDownTime;
293     mEventTime = from.mEventTime;
294 }
295 
actionToString(int32_t action)296 const char* KeyEvent::actionToString(int32_t action) {
297     // Convert KeyEvent action to string
298     switch (action) {
299         case AKEY_EVENT_ACTION_DOWN:
300             return "DOWN";
301         case AKEY_EVENT_ACTION_UP:
302             return "UP";
303         case AKEY_EVENT_ACTION_MULTIPLE:
304             return "MULTIPLE";
305     }
306     return "UNKNOWN";
307 }
308 
309 // --- PointerCoords ---
310 
getAxisValue(int32_t axis) const311 float PointerCoords::getAxisValue(int32_t axis) const {
312     if (axis < 0 || axis > 63 || !BitSet64::hasBit(bits, axis)){
313         return 0;
314     }
315     return values[BitSet64::getIndexOfBit(bits, axis)];
316 }
317 
setAxisValue(int32_t axis,float value)318 status_t PointerCoords::setAxisValue(int32_t axis, float value) {
319     if (axis < 0 || axis > 63) {
320         return NAME_NOT_FOUND;
321     }
322 
323     uint32_t index = BitSet64::getIndexOfBit(bits, axis);
324     if (!BitSet64::hasBit(bits, axis)) {
325         if (value == 0) {
326             return OK; // axes with value 0 do not need to be stored
327         }
328 
329         uint32_t count = BitSet64::count(bits);
330         if (count >= MAX_AXES) {
331             tooManyAxes(axis);
332             return NO_MEMORY;
333         }
334         BitSet64::markBit(bits, axis);
335         for (uint32_t i = count; i > index; i--) {
336             values[i] = values[i - 1];
337         }
338     }
339 
340     values[index] = value;
341     return OK;
342 }
343 
scaleAxisValue(PointerCoords & c,int axis,float scaleFactor)344 static inline void scaleAxisValue(PointerCoords& c, int axis, float scaleFactor) {
345     float value = c.getAxisValue(axis);
346     if (value != 0) {
347         c.setAxisValue(axis, value * scaleFactor);
348     }
349 }
350 
scale(float globalScaleFactor,float windowXScale,float windowYScale)351 void PointerCoords::scale(float globalScaleFactor, float windowXScale, float windowYScale) {
352     // No need to scale pressure or size since they are normalized.
353     // No need to scale orientation since it is meaningless to do so.
354 
355     // If there is a global scale factor, it is included in the windowX/YScale
356     // so we don't need to apply it twice to the X/Y axes.
357     // However we don't want to apply any windowXYScale not included in the global scale
358     // to the TOUCH_MAJOR/MINOR coordinates.
359     scaleAxisValue(*this, AMOTION_EVENT_AXIS_X, windowXScale);
360     scaleAxisValue(*this, AMOTION_EVENT_AXIS_Y, windowYScale);
361     scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOUCH_MAJOR, globalScaleFactor);
362     scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOUCH_MINOR, globalScaleFactor);
363     scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOOL_MAJOR, globalScaleFactor);
364     scaleAxisValue(*this, AMOTION_EVENT_AXIS_TOOL_MINOR, globalScaleFactor);
365     scaleAxisValue(*this, AMOTION_EVENT_AXIS_RELATIVE_X, windowXScale);
366     scaleAxisValue(*this, AMOTION_EVENT_AXIS_RELATIVE_Y, windowYScale);
367 }
368 
369 #ifdef __linux__
readFromParcel(Parcel * parcel)370 status_t PointerCoords::readFromParcel(Parcel* parcel) {
371     bits = parcel->readInt64();
372 
373     uint32_t count = BitSet64::count(bits);
374     if (count > MAX_AXES) {
375         return BAD_VALUE;
376     }
377 
378     for (uint32_t i = 0; i < count; i++) {
379         values[i] = parcel->readFloat();
380     }
381     return OK;
382 }
383 
writeToParcel(Parcel * parcel) const384 status_t PointerCoords::writeToParcel(Parcel* parcel) const {
385     parcel->writeInt64(bits);
386 
387     uint32_t count = BitSet64::count(bits);
388     for (uint32_t i = 0; i < count; i++) {
389         parcel->writeFloat(values[i]);
390     }
391     return OK;
392 }
393 #endif
394 
tooManyAxes(int axis)395 void PointerCoords::tooManyAxes(int axis) {
396     ALOGW("Could not set value for axis %d because the PointerCoords structure is full and "
397             "cannot contain more than %d axis values.", axis, int(MAX_AXES));
398 }
399 
operator ==(const PointerCoords & other) const400 bool PointerCoords::operator==(const PointerCoords& other) const {
401     if (bits != other.bits) {
402         return false;
403     }
404     uint32_t count = BitSet64::count(bits);
405     for (uint32_t i = 0; i < count; i++) {
406         if (values[i] != other.values[i]) {
407             return false;
408         }
409     }
410     return true;
411 }
412 
copyFrom(const PointerCoords & other)413 void PointerCoords::copyFrom(const PointerCoords& other) {
414     bits = other.bits;
415     uint32_t count = BitSet64::count(bits);
416     for (uint32_t i = 0; i < count; i++) {
417         values[i] = other.values[i];
418     }
419 }
420 
transform(const ui::Transform & transform)421 void PointerCoords::transform(const ui::Transform& transform) {
422     const vec2 xy = transform.transform(getXYValue());
423     setAxisValue(AMOTION_EVENT_AXIS_X, xy.x);
424     setAxisValue(AMOTION_EVENT_AXIS_Y, xy.y);
425 
426     if (BitSet64::hasBit(bits, AMOTION_EVENT_AXIS_RELATIVE_X) ||
427         BitSet64::hasBit(bits, AMOTION_EVENT_AXIS_RELATIVE_Y)) {
428         const ui::Transform rotation(transform.getOrientation());
429         const vec2 relativeXy = rotation.transform(getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
430                                                    getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y));
431         setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, relativeXy.x);
432         setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, relativeXy.y);
433     }
434 
435     if (BitSet64::hasBit(bits, AMOTION_EVENT_AXIS_ORIENTATION)) {
436         const float val = getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION);
437         setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, transformAngle(transform, val));
438     }
439 }
440 
441 // --- PointerProperties ---
442 
operator ==(const PointerProperties & other) const443 bool PointerProperties::operator==(const PointerProperties& other) const {
444     return id == other.id
445             && toolType == other.toolType;
446 }
447 
copyFrom(const PointerProperties & other)448 void PointerProperties::copyFrom(const PointerProperties& other) {
449     id = other.id;
450     toolType = other.toolType;
451 }
452 
453 
454 // --- MotionEvent ---
455 
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,const ui::Transform & rawTransform,nsecs_t downTime,nsecs_t eventTime,size_t pointerCount,const PointerProperties * pointerProperties,const PointerCoords * pointerCoords)456 void MotionEvent::initialize(int32_t id, int32_t deviceId, uint32_t source, int32_t displayId,
457                              std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton,
458                              int32_t flags, int32_t edgeFlags, int32_t metaState,
459                              int32_t buttonState, MotionClassification classification,
460                              const ui::Transform& transform, float xPrecision, float yPrecision,
461                              float rawXCursorPosition, float rawYCursorPosition,
462                              const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
463                              size_t pointerCount, const PointerProperties* pointerProperties,
464                              const PointerCoords* pointerCoords) {
465     InputEvent::initialize(id, deviceId, source, displayId, hmac);
466     mAction = action;
467     mActionButton = actionButton;
468     mFlags = flags;
469     mEdgeFlags = edgeFlags;
470     mMetaState = metaState;
471     mButtonState = buttonState;
472     mClassification = classification;
473     mTransform = transform;
474     mXPrecision = xPrecision;
475     mYPrecision = yPrecision;
476     mRawXCursorPosition = rawXCursorPosition;
477     mRawYCursorPosition = rawYCursorPosition;
478     mRawTransform = rawTransform;
479     mDownTime = downTime;
480     mPointerProperties.clear();
481     mPointerProperties.insert(mPointerProperties.end(), &pointerProperties[0],
482                               &pointerProperties[pointerCount]);
483     mSampleEventTimes.clear();
484     mSamplePointerCoords.clear();
485     addSample(eventTime, pointerCoords);
486 }
487 
copyFrom(const MotionEvent * other,bool keepHistory)488 void MotionEvent::copyFrom(const MotionEvent* other, bool keepHistory) {
489     InputEvent::initialize(other->mId, other->mDeviceId, other->mSource, other->mDisplayId,
490                            other->mHmac);
491     mAction = other->mAction;
492     mActionButton = other->mActionButton;
493     mFlags = other->mFlags;
494     mEdgeFlags = other->mEdgeFlags;
495     mMetaState = other->mMetaState;
496     mButtonState = other->mButtonState;
497     mClassification = other->mClassification;
498     mTransform = other->mTransform;
499     mXPrecision = other->mXPrecision;
500     mYPrecision = other->mYPrecision;
501     mRawXCursorPosition = other->mRawXCursorPosition;
502     mRawYCursorPosition = other->mRawYCursorPosition;
503     mRawTransform = other->mRawTransform;
504     mDownTime = other->mDownTime;
505     mPointerProperties = other->mPointerProperties;
506 
507     if (keepHistory) {
508         mSampleEventTimes = other->mSampleEventTimes;
509         mSamplePointerCoords = other->mSamplePointerCoords;
510     } else {
511         mSampleEventTimes.clear();
512         mSampleEventTimes.push_back(other->getEventTime());
513         mSamplePointerCoords.clear();
514         size_t pointerCount = other->getPointerCount();
515         size_t historySize = other->getHistorySize();
516         mSamplePointerCoords
517                 .insert(mSamplePointerCoords.end(),
518                         &other->mSamplePointerCoords[historySize * pointerCount],
519                         &other->mSamplePointerCoords[historySize * pointerCount + pointerCount]);
520     }
521 }
522 
addSample(int64_t eventTime,const PointerCoords * pointerCoords)523 void MotionEvent::addSample(
524         int64_t eventTime,
525         const PointerCoords* pointerCoords) {
526     mSampleEventTimes.push_back(eventTime);
527     mSamplePointerCoords.insert(mSamplePointerCoords.end(), &pointerCoords[0],
528                                 &pointerCoords[getPointerCount()]);
529 }
530 
getSurfaceRotation() const531 int MotionEvent::getSurfaceRotation() const {
532     // The surface rotation is the rotation from the window's coordinate space to that of the
533     // display. Since the event's transform takes display space coordinates to window space, the
534     // returned surface rotation is the inverse of the rotation for the surface.
535     switch (mTransform.getOrientation()) {
536         case ui::Transform::ROT_0:
537             return DISPLAY_ORIENTATION_0;
538         case ui::Transform::ROT_90:
539             return DISPLAY_ORIENTATION_270;
540         case ui::Transform::ROT_180:
541             return DISPLAY_ORIENTATION_180;
542         case ui::Transform::ROT_270:
543             return DISPLAY_ORIENTATION_90;
544         default:
545             return -1;
546     }
547 }
548 
getXCursorPosition() const549 float MotionEvent::getXCursorPosition() const {
550     vec2 vals = mTransform.transform(getRawXCursorPosition(), getRawYCursorPosition());
551     return vals.x;
552 }
553 
getYCursorPosition() const554 float MotionEvent::getYCursorPosition() const {
555     vec2 vals = mTransform.transform(getRawXCursorPosition(), getRawYCursorPosition());
556     return vals.y;
557 }
558 
setCursorPosition(float x,float y)559 void MotionEvent::setCursorPosition(float x, float y) {
560     ui::Transform inverse = mTransform.inverse();
561     vec2 vals = inverse.transform(x, y);
562     mRawXCursorPosition = vals.x;
563     mRawYCursorPosition = vals.y;
564 }
565 
getRawPointerCoords(size_t pointerIndex) const566 const PointerCoords* MotionEvent::getRawPointerCoords(size_t pointerIndex) const {
567     if (CC_UNLIKELY(pointerIndex < 0 || pointerIndex >= getPointerCount())) {
568         LOG(FATAL) << __func__ << ": Invalid pointer index " << pointerIndex << " for " << *this;
569     }
570     const size_t position = getHistorySize() * getPointerCount() + pointerIndex;
571     if (CC_UNLIKELY(position < 0 || position >= mSamplePointerCoords.size())) {
572         LOG(FATAL) << __func__ << ": Invalid array index " << position << " for " << *this;
573     }
574     return &mSamplePointerCoords[position];
575 }
576 
getRawAxisValue(int32_t axis,size_t pointerIndex) const577 float MotionEvent::getRawAxisValue(int32_t axis, size_t pointerIndex) const {
578     return getHistoricalRawAxisValue(axis, pointerIndex, getHistorySize());
579 }
580 
getAxisValue(int32_t axis,size_t pointerIndex) const581 float MotionEvent::getAxisValue(int32_t axis, size_t pointerIndex) const {
582     return getHistoricalAxisValue(axis, pointerIndex, getHistorySize());
583 }
584 
getHistoricalRawPointerCoords(size_t pointerIndex,size_t historicalIndex) const585 const PointerCoords* MotionEvent::getHistoricalRawPointerCoords(
586         size_t pointerIndex, size_t historicalIndex) const {
587     if (CC_UNLIKELY(pointerIndex < 0 || pointerIndex >= getPointerCount())) {
588         LOG(FATAL) << __func__ << ": Invalid pointer index " << pointerIndex << " for " << *this;
589     }
590     if (CC_UNLIKELY(historicalIndex < 0 || historicalIndex > getHistorySize())) {
591         LOG(FATAL) << __func__ << ": Invalid historical index " << historicalIndex << " for "
592                    << *this;
593     }
594     const size_t position = historicalIndex * getPointerCount() + pointerIndex;
595     if (CC_UNLIKELY(position < 0 || position >= mSamplePointerCoords.size())) {
596         LOG(FATAL) << __func__ << ": Invalid array index " << position << " for " << *this;
597     }
598     return &mSamplePointerCoords[position];
599 }
600 
getHistoricalRawAxisValue(int32_t axis,size_t pointerIndex,size_t historicalIndex) const601 float MotionEvent::getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex,
602                                              size_t historicalIndex) const {
603     const PointerCoords& coords = *getHistoricalRawPointerCoords(pointerIndex, historicalIndex);
604     return calculateTransformedAxisValue(axis, mSource, mRawTransform, coords);
605 }
606 
getHistoricalAxisValue(int32_t axis,size_t pointerIndex,size_t historicalIndex) const607 float MotionEvent::getHistoricalAxisValue(int32_t axis, size_t pointerIndex,
608                                           size_t historicalIndex) const {
609     const PointerCoords& coords = *getHistoricalRawPointerCoords(pointerIndex, historicalIndex);
610     return calculateTransformedAxisValue(axis, mSource, mTransform, coords);
611 }
612 
findPointerIndex(int32_t pointerId) const613 ssize_t MotionEvent::findPointerIndex(int32_t pointerId) const {
614     size_t pointerCount = mPointerProperties.size();
615     for (size_t i = 0; i < pointerCount; i++) {
616         if (mPointerProperties[i].id == pointerId) {
617             return i;
618         }
619     }
620     return -1;
621 }
622 
offsetLocation(float xOffset,float yOffset)623 void MotionEvent::offsetLocation(float xOffset, float yOffset) {
624     float currXOffset = mTransform.tx();
625     float currYOffset = mTransform.ty();
626     mTransform.set(currXOffset + xOffset, currYOffset + yOffset);
627 }
628 
scale(float globalScaleFactor)629 void MotionEvent::scale(float globalScaleFactor) {
630     mTransform.set(mTransform.tx() * globalScaleFactor, mTransform.ty() * globalScaleFactor);
631     mRawTransform.set(mRawTransform.tx() * globalScaleFactor,
632                       mRawTransform.ty() * globalScaleFactor);
633     mXPrecision *= globalScaleFactor;
634     mYPrecision *= globalScaleFactor;
635 
636     size_t numSamples = mSamplePointerCoords.size();
637     for (size_t i = 0; i < numSamples; i++) {
638         mSamplePointerCoords[i].scale(globalScaleFactor, globalScaleFactor, globalScaleFactor);
639     }
640 }
641 
transform(const std::array<float,9> & matrix)642 void MotionEvent::transform(const std::array<float, 9>& matrix) {
643     // We want to preserve the raw axes values stored in the PointerCoords, so we just update the
644     // transform using the values passed in.
645     ui::Transform newTransform;
646     newTransform.set(matrix);
647     mTransform = newTransform * mTransform;
648 }
649 
applyTransform(const std::array<float,9> & matrix)650 void MotionEvent::applyTransform(const std::array<float, 9>& matrix) {
651     ui::Transform transform;
652     transform.set(matrix);
653 
654     // Apply the transformation to all samples.
655     std::for_each(mSamplePointerCoords.begin(), mSamplePointerCoords.end(),
656                   [&transform](PointerCoords& c) { c.transform(transform); });
657 
658     if (mRawXCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION &&
659         mRawYCursorPosition != AMOTION_EVENT_INVALID_CURSOR_POSITION) {
660         const vec2 cursor = transform.transform(mRawXCursorPosition, mRawYCursorPosition);
661         mRawXCursorPosition = cursor.x;
662         mRawYCursorPosition = cursor.y;
663     }
664 }
665 
666 #ifdef __linux__
readFromParcel(ui::Transform & transform,const Parcel & parcel)667 static status_t readFromParcel(ui::Transform& transform, const Parcel& parcel) {
668     float dsdx, dtdx, tx, dtdy, dsdy, ty;
669     status_t status = parcel.readFloat(&dsdx);
670     status |= parcel.readFloat(&dtdx);
671     status |= parcel.readFloat(&tx);
672     status |= parcel.readFloat(&dtdy);
673     status |= parcel.readFloat(&dsdy);
674     status |= parcel.readFloat(&ty);
675 
676     transform.set({dsdx, dtdx, tx, dtdy, dsdy, ty, 0, 0, 1});
677     return status;
678 }
679 
writeToParcel(const ui::Transform & transform,Parcel & parcel)680 static status_t writeToParcel(const ui::Transform& transform, Parcel& parcel) {
681     status_t status = parcel.writeFloat(transform.dsdx());
682     status |= parcel.writeFloat(transform.dtdx());
683     status |= parcel.writeFloat(transform.tx());
684     status |= parcel.writeFloat(transform.dtdy());
685     status |= parcel.writeFloat(transform.dsdy());
686     status |= parcel.writeFloat(transform.ty());
687     return status;
688 }
689 
readFromParcel(Parcel * parcel)690 status_t MotionEvent::readFromParcel(Parcel* parcel) {
691     size_t pointerCount = parcel->readInt32();
692     size_t sampleCount = parcel->readInt32();
693     if (pointerCount == 0 || pointerCount > MAX_POINTERS ||
694             sampleCount == 0 || sampleCount > MAX_SAMPLES) {
695         return BAD_VALUE;
696     }
697 
698     mId = parcel->readInt32();
699     mDeviceId = parcel->readInt32();
700     mSource = parcel->readUint32();
701     mDisplayId = parcel->readInt32();
702     std::vector<uint8_t> hmac;
703     status_t result = parcel->readByteVector(&hmac);
704     if (result != OK || hmac.size() != 32) {
705         return BAD_VALUE;
706     }
707     std::move(hmac.begin(), hmac.begin() + hmac.size(), mHmac.begin());
708     mAction = parcel->readInt32();
709     mActionButton = parcel->readInt32();
710     mFlags = parcel->readInt32();
711     mEdgeFlags = parcel->readInt32();
712     mMetaState = parcel->readInt32();
713     mButtonState = parcel->readInt32();
714     mClassification = static_cast<MotionClassification>(parcel->readByte());
715 
716     result = android::readFromParcel(mTransform, *parcel);
717     if (result != OK) {
718         return result;
719     }
720     mXPrecision = parcel->readFloat();
721     mYPrecision = parcel->readFloat();
722     mRawXCursorPosition = parcel->readFloat();
723     mRawYCursorPosition = parcel->readFloat();
724 
725     result = android::readFromParcel(mRawTransform, *parcel);
726     if (result != OK) {
727         return result;
728     }
729     mDownTime = parcel->readInt64();
730 
731     mPointerProperties.clear();
732     mPointerProperties.reserve(pointerCount);
733     mSampleEventTimes.clear();
734     mSampleEventTimes.reserve(sampleCount);
735     mSamplePointerCoords.clear();
736     mSamplePointerCoords.reserve(sampleCount * pointerCount);
737 
738     for (size_t i = 0; i < pointerCount; i++) {
739         mPointerProperties.push_back({});
740         PointerProperties& properties = mPointerProperties.back();
741         properties.id = parcel->readInt32();
742         properties.toolType = parcel->readInt32();
743     }
744 
745     while (sampleCount > 0) {
746         sampleCount--;
747         mSampleEventTimes.push_back(parcel->readInt64());
748         for (size_t i = 0; i < pointerCount; i++) {
749             mSamplePointerCoords.push_back({});
750             status_t status = mSamplePointerCoords.back().readFromParcel(parcel);
751             if (status) {
752                 return status;
753             }
754         }
755     }
756     return OK;
757 }
758 
writeToParcel(Parcel * parcel) const759 status_t MotionEvent::writeToParcel(Parcel* parcel) const {
760     size_t pointerCount = mPointerProperties.size();
761     size_t sampleCount = mSampleEventTimes.size();
762 
763     parcel->writeInt32(pointerCount);
764     parcel->writeInt32(sampleCount);
765 
766     parcel->writeInt32(mId);
767     parcel->writeInt32(mDeviceId);
768     parcel->writeUint32(mSource);
769     parcel->writeInt32(mDisplayId);
770     std::vector<uint8_t> hmac(mHmac.begin(), mHmac.end());
771     parcel->writeByteVector(hmac);
772     parcel->writeInt32(mAction);
773     parcel->writeInt32(mActionButton);
774     parcel->writeInt32(mFlags);
775     parcel->writeInt32(mEdgeFlags);
776     parcel->writeInt32(mMetaState);
777     parcel->writeInt32(mButtonState);
778     parcel->writeByte(static_cast<int8_t>(mClassification));
779 
780     status_t result = android::writeToParcel(mTransform, *parcel);
781     if (result != OK) {
782         return result;
783     }
784     parcel->writeFloat(mXPrecision);
785     parcel->writeFloat(mYPrecision);
786     parcel->writeFloat(mRawXCursorPosition);
787     parcel->writeFloat(mRawYCursorPosition);
788 
789     result = android::writeToParcel(mRawTransform, *parcel);
790     if (result != OK) {
791         return result;
792     }
793     parcel->writeInt64(mDownTime);
794 
795     for (size_t i = 0; i < pointerCount; i++) {
796         const PointerProperties& properties = mPointerProperties[i];
797         parcel->writeInt32(properties.id);
798         parcel->writeInt32(properties.toolType);
799     }
800 
801     const PointerCoords* pc = mSamplePointerCoords.data();
802     for (size_t h = 0; h < sampleCount; h++) {
803         parcel->writeInt64(mSampleEventTimes[h]);
804         for (size_t i = 0; i < pointerCount; i++) {
805             status_t status = (pc++)->writeToParcel(parcel);
806             if (status) {
807                 return status;
808             }
809         }
810     }
811     return OK;
812 }
813 #endif
814 
isTouchEvent(uint32_t source,int32_t action)815 bool MotionEvent::isTouchEvent(uint32_t source, int32_t action) {
816     if (isFromSource(source, AINPUT_SOURCE_CLASS_POINTER)) {
817         // Specifically excludes HOVER_MOVE and SCROLL.
818         switch (action & AMOTION_EVENT_ACTION_MASK) {
819         case AMOTION_EVENT_ACTION_DOWN:
820         case AMOTION_EVENT_ACTION_MOVE:
821         case AMOTION_EVENT_ACTION_UP:
822         case AMOTION_EVENT_ACTION_POINTER_DOWN:
823         case AMOTION_EVENT_ACTION_POINTER_UP:
824         case AMOTION_EVENT_ACTION_CANCEL:
825         case AMOTION_EVENT_ACTION_OUTSIDE:
826             return true;
827         }
828     }
829     return false;
830 }
831 
getLabel(int32_t axis)832 const char* MotionEvent::getLabel(int32_t axis) {
833     return InputEventLookup::getAxisLabel(axis);
834 }
835 
getAxisFromLabel(const char * label)836 int32_t MotionEvent::getAxisFromLabel(const char* label) {
837     return InputEventLookup::getAxisByLabel(label);
838 }
839 
actionToString(int32_t action)840 std::string MotionEvent::actionToString(int32_t action) {
841     // Convert MotionEvent action to string
842     switch (action & AMOTION_EVENT_ACTION_MASK) {
843         case AMOTION_EVENT_ACTION_DOWN:
844             return "DOWN";
845         case AMOTION_EVENT_ACTION_UP:
846             return "UP";
847         case AMOTION_EVENT_ACTION_MOVE:
848             return "MOVE";
849         case AMOTION_EVENT_ACTION_CANCEL:
850             return "CANCEL";
851         case AMOTION_EVENT_ACTION_OUTSIDE:
852             return "OUTSIDE";
853         case AMOTION_EVENT_ACTION_POINTER_DOWN:
854             return StringPrintf("POINTER_DOWN(%" PRId32 ")", MotionEvent::getActionIndex(action));
855         case AMOTION_EVENT_ACTION_POINTER_UP:
856             return StringPrintf("POINTER_UP(%" PRId32 ")", MotionEvent::getActionIndex(action));
857         case AMOTION_EVENT_ACTION_HOVER_MOVE:
858             return "HOVER_MOVE";
859         case AMOTION_EVENT_ACTION_SCROLL:
860             return "SCROLL";
861         case AMOTION_EVENT_ACTION_HOVER_ENTER:
862             return "HOVER_ENTER";
863         case AMOTION_EVENT_ACTION_HOVER_EXIT:
864             return "HOVER_EXIT";
865         case AMOTION_EVENT_ACTION_BUTTON_PRESS:
866             return "BUTTON_PRESS";
867         case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
868             return "BUTTON_RELEASE";
869     }
870     return android::base::StringPrintf("%" PRId32, action);
871 }
872 
873 // Apply the given transformation to the point without checking whether the entire transform
874 // should be disregarded altogether for the provided source.
calculateTransformedXYUnchecked(uint32_t source,const ui::Transform & transform,const vec2 & xy)875 static inline vec2 calculateTransformedXYUnchecked(uint32_t source, const ui::Transform& transform,
876                                                    const vec2& xy) {
877     return shouldDisregardOffset(source) ? transformWithoutTranslation(transform, xy)
878                                          : transform.transform(xy);
879 }
880 
calculateTransformedXY(uint32_t source,const ui::Transform & transform,const vec2 & xy)881 vec2 MotionEvent::calculateTransformedXY(uint32_t source, const ui::Transform& transform,
882                                          const vec2& xy) {
883     if (shouldDisregardTransformation(source)) {
884         return xy;
885     }
886     return calculateTransformedXYUnchecked(source, transform, xy);
887 }
888 
889 // Keep in sync with calculateTransformedCoords.
calculateTransformedAxisValue(int32_t axis,uint32_t source,const ui::Transform & transform,const PointerCoords & coords)890 float MotionEvent::calculateTransformedAxisValue(int32_t axis, uint32_t source,
891                                                  const ui::Transform& transform,
892                                                  const PointerCoords& coords) {
893     if (shouldDisregardTransformation(source)) {
894         return coords.getAxisValue(axis);
895     }
896 
897     if (axis == AMOTION_EVENT_AXIS_X || axis == AMOTION_EVENT_AXIS_Y) {
898         const vec2 xy = calculateTransformedXYUnchecked(source, transform, coords.getXYValue());
899         static_assert(AMOTION_EVENT_AXIS_X == 0 && AMOTION_EVENT_AXIS_Y == 1);
900         return xy[axis];
901     }
902 
903     if (axis == AMOTION_EVENT_AXIS_RELATIVE_X || axis == AMOTION_EVENT_AXIS_RELATIVE_Y) {
904         const vec2 relativeXy =
905                 transformWithoutTranslation(transform,
906                                             {coords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
907                                              coords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y)});
908         return axis == AMOTION_EVENT_AXIS_RELATIVE_X ? relativeXy.x : relativeXy.y;
909     }
910 
911     if (axis == AMOTION_EVENT_AXIS_ORIENTATION) {
912         return transformAngle(transform, coords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION));
913     }
914 
915     return coords.getAxisValue(axis);
916 }
917 
918 // Keep in sync with calculateTransformedAxisValue. This is an optimization of
919 // calculateTransformedAxisValue for all PointerCoords axes.
calculateTransformedCoords(uint32_t source,const ui::Transform & transform,const PointerCoords & coords)920 PointerCoords MotionEvent::calculateTransformedCoords(uint32_t source,
921                                                       const ui::Transform& transform,
922                                                       const PointerCoords& coords) {
923     if (shouldDisregardTransformation(source)) {
924         return coords;
925     }
926     PointerCoords out = coords;
927 
928     const vec2 xy = calculateTransformedXYUnchecked(source, transform, coords.getXYValue());
929     out.setAxisValue(AMOTION_EVENT_AXIS_X, xy.x);
930     out.setAxisValue(AMOTION_EVENT_AXIS_Y, xy.y);
931 
932     const vec2 relativeXy =
933             transformWithoutTranslation(transform,
934                                         {coords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
935                                          coords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y)});
936     out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, relativeXy.x);
937     out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, relativeXy.y);
938 
939     out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION,
940                      transformAngle(transform,
941                                     coords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION)));
942 
943     return out;
944 }
945 
operator <<(std::ostream & out,const MotionEvent & event)946 std::ostream& operator<<(std::ostream& out, const MotionEvent& event) {
947     out << "MotionEvent { action=" << MotionEvent::actionToString(event.getAction());
948     if (event.getActionButton() != 0) {
949         out << ", actionButton=" << std::to_string(event.getActionButton());
950     }
951     const size_t pointerCount = event.getPointerCount();
952     for (size_t i = 0; i < pointerCount; i++) {
953         out << ", id[" << i << "]=" << event.getPointerId(i);
954         float x = event.getX(i);
955         float y = event.getY(i);
956         if (x != 0 || y != 0) {
957             out << ", x[" << i << "]=" << x;
958             out << ", y[" << i << "]=" << y;
959         }
960         int toolType = event.getToolType(i);
961         if (toolType != AMOTION_EVENT_TOOL_TYPE_FINGER) {
962             out << ", toolType[" << i << "]=" << toolType;
963         }
964     }
965     if (event.getButtonState() != 0) {
966         out << ", buttonState=" << event.getButtonState();
967     }
968     if (event.getClassification() != MotionClassification::NONE) {
969         out << ", classification=" << motionClassificationToString(event.getClassification());
970     }
971     if (event.getMetaState() != 0) {
972         out << ", metaState=" << event.getMetaState();
973     }
974     if (event.getEdgeFlags() != 0) {
975         out << ", edgeFlags=" << event.getEdgeFlags();
976     }
977     if (pointerCount != 1) {
978         out << ", pointerCount=" << pointerCount;
979     }
980     if (event.getHistorySize() != 0) {
981         out << ", historySize=" << event.getHistorySize();
982     }
983     out << ", eventTime=" << event.getEventTime();
984     out << ", downTime=" << event.getDownTime();
985     out << ", deviceId=" << event.getDeviceId();
986     out << ", source=" << inputEventSourceToString(event.getSource());
987     out << ", displayId=" << event.getDisplayId();
988     out << ", eventId=" << event.getId();
989     out << "}";
990     return out;
991 }
992 
993 // --- FocusEvent ---
994 
initialize(int32_t id,bool hasFocus)995 void FocusEvent::initialize(int32_t id, bool hasFocus) {
996     InputEvent::initialize(id, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, AINPUT_SOURCE_UNKNOWN,
997                            ADISPLAY_ID_NONE, INVALID_HMAC);
998     mHasFocus = hasFocus;
999 }
1000 
initialize(const FocusEvent & from)1001 void FocusEvent::initialize(const FocusEvent& from) {
1002     InputEvent::initialize(from);
1003     mHasFocus = from.mHasFocus;
1004 }
1005 
1006 // --- CaptureEvent ---
1007 
initialize(int32_t id,bool pointerCaptureEnabled)1008 void CaptureEvent::initialize(int32_t id, bool pointerCaptureEnabled) {
1009     InputEvent::initialize(id, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, AINPUT_SOURCE_UNKNOWN,
1010                            ADISPLAY_ID_NONE, INVALID_HMAC);
1011     mPointerCaptureEnabled = pointerCaptureEnabled;
1012 }
1013 
initialize(const CaptureEvent & from)1014 void CaptureEvent::initialize(const CaptureEvent& from) {
1015     InputEvent::initialize(from);
1016     mPointerCaptureEnabled = from.mPointerCaptureEnabled;
1017 }
1018 
1019 // --- DragEvent ---
1020 
initialize(int32_t id,float x,float y,bool isExiting)1021 void DragEvent::initialize(int32_t id, float x, float y, bool isExiting) {
1022     InputEvent::initialize(id, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, AINPUT_SOURCE_UNKNOWN,
1023                            ADISPLAY_ID_NONE, INVALID_HMAC);
1024     mIsExiting = isExiting;
1025     mX = x;
1026     mY = y;
1027 }
1028 
initialize(const DragEvent & from)1029 void DragEvent::initialize(const DragEvent& from) {
1030     InputEvent::initialize(from);
1031     mIsExiting = from.mIsExiting;
1032     mX = from.mX;
1033     mY = from.mY;
1034 }
1035 
1036 // --- TouchModeEvent ---
1037 
initialize(int32_t id,bool isInTouchMode)1038 void TouchModeEvent::initialize(int32_t id, bool isInTouchMode) {
1039     InputEvent::initialize(id, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, AINPUT_SOURCE_UNKNOWN,
1040                            ADISPLAY_ID_NONE, INVALID_HMAC);
1041     mIsInTouchMode = isInTouchMode;
1042 }
1043 
initialize(const TouchModeEvent & from)1044 void TouchModeEvent::initialize(const TouchModeEvent& from) {
1045     InputEvent::initialize(from);
1046     mIsInTouchMode = from.mIsInTouchMode;
1047 }
1048 
1049 // --- PooledInputEventFactory ---
1050 
PooledInputEventFactory(size_t maxPoolSize)1051 PooledInputEventFactory::PooledInputEventFactory(size_t maxPoolSize) :
1052         mMaxPoolSize(maxPoolSize) {
1053 }
1054 
~PooledInputEventFactory()1055 PooledInputEventFactory::~PooledInputEventFactory() {
1056 }
1057 
createKeyEvent()1058 KeyEvent* PooledInputEventFactory::createKeyEvent() {
1059     if (mKeyEventPool.empty()) {
1060         return new KeyEvent();
1061     }
1062     KeyEvent* event = mKeyEventPool.front().release();
1063     mKeyEventPool.pop();
1064     return event;
1065 }
1066 
createMotionEvent()1067 MotionEvent* PooledInputEventFactory::createMotionEvent() {
1068     if (mMotionEventPool.empty()) {
1069         return new MotionEvent();
1070     }
1071     MotionEvent* event = mMotionEventPool.front().release();
1072     mMotionEventPool.pop();
1073     return event;
1074 }
1075 
createFocusEvent()1076 FocusEvent* PooledInputEventFactory::createFocusEvent() {
1077     if (mFocusEventPool.empty()) {
1078         return new FocusEvent();
1079     }
1080     FocusEvent* event = mFocusEventPool.front().release();
1081     mFocusEventPool.pop();
1082     return event;
1083 }
1084 
createCaptureEvent()1085 CaptureEvent* PooledInputEventFactory::createCaptureEvent() {
1086     if (mCaptureEventPool.empty()) {
1087         return new CaptureEvent();
1088     }
1089     CaptureEvent* event = mCaptureEventPool.front().release();
1090     mCaptureEventPool.pop();
1091     return event;
1092 }
1093 
createDragEvent()1094 DragEvent* PooledInputEventFactory::createDragEvent() {
1095     if (mDragEventPool.empty()) {
1096         return new DragEvent();
1097     }
1098     DragEvent* event = mDragEventPool.front().release();
1099     mDragEventPool.pop();
1100     return event;
1101 }
1102 
createTouchModeEvent()1103 TouchModeEvent* PooledInputEventFactory::createTouchModeEvent() {
1104     if (mTouchModeEventPool.empty()) {
1105         return new TouchModeEvent();
1106     }
1107     TouchModeEvent* event = mTouchModeEventPool.front().release();
1108     mTouchModeEventPool.pop();
1109     return event;
1110 }
1111 
recycle(InputEvent * event)1112 void PooledInputEventFactory::recycle(InputEvent* event) {
1113     switch (event->getType()) {
1114     case AINPUT_EVENT_TYPE_KEY:
1115         if (mKeyEventPool.size() < mMaxPoolSize) {
1116             mKeyEventPool.push(std::unique_ptr<KeyEvent>(static_cast<KeyEvent*>(event)));
1117             return;
1118         }
1119         break;
1120     case AINPUT_EVENT_TYPE_MOTION:
1121         if (mMotionEventPool.size() < mMaxPoolSize) {
1122             mMotionEventPool.push(std::unique_ptr<MotionEvent>(static_cast<MotionEvent*>(event)));
1123             return;
1124         }
1125         break;
1126     case AINPUT_EVENT_TYPE_FOCUS:
1127         if (mFocusEventPool.size() < mMaxPoolSize) {
1128             mFocusEventPool.push(std::unique_ptr<FocusEvent>(static_cast<FocusEvent*>(event)));
1129             return;
1130         }
1131         break;
1132     case AINPUT_EVENT_TYPE_CAPTURE:
1133         if (mCaptureEventPool.size() < mMaxPoolSize) {
1134             mCaptureEventPool.push(
1135                     std::unique_ptr<CaptureEvent>(static_cast<CaptureEvent*>(event)));
1136             return;
1137         }
1138         break;
1139     case AINPUT_EVENT_TYPE_DRAG:
1140         if (mDragEventPool.size() < mMaxPoolSize) {
1141             mDragEventPool.push(std::unique_ptr<DragEvent>(static_cast<DragEvent*>(event)));
1142             return;
1143         }
1144         break;
1145     case AINPUT_EVENT_TYPE_TOUCH_MODE:
1146         if (mTouchModeEventPool.size() < mMaxPoolSize) {
1147             mTouchModeEventPool.push(
1148                     std::unique_ptr<TouchModeEvent>(static_cast<TouchModeEvent*>(event)));
1149             return;
1150         }
1151         break;
1152     }
1153     delete event;
1154 }
1155 
1156 } // namespace android
1157