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 #ifndef _LIBINPUT_INPUT_H
18 #define _LIBINPUT_INPUT_H
19 
20 #pragma GCC system_header
21 
22 /**
23  * Native input event structures.
24  */
25 
26 #include <android/input.h>
27 #ifdef __linux__
28 #include <android/os/IInputConstants.h>
29 #endif
30 #include <math.h>
31 #include <stdint.h>
32 #include <ui/Transform.h>
33 #include <utils/BitSet.h>
34 #include <utils/KeyedVector.h>
35 #include <utils/RefBase.h>
36 #include <utils/Timers.h>
37 #include <utils/Vector.h>
38 #include <array>
39 #include <limits>
40 #include <queue>
41 
42 /*
43  * Additional private constants not defined in ndk/ui/input.h.
44  */
45 enum {
46 #ifdef __linux__
47     /* This event was generated or modified by accessibility service. */
48     AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT =
49             android::os::IInputConstants::INPUT_EVENT_FLAG_IS_ACCESSIBILITY_EVENT, // 0x800,
50 #else
51     AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT = 0x800,
52 #endif
53     /* Signifies that the key is being predispatched */
54     AKEY_EVENT_FLAG_PREDISPATCH = 0x20000000,
55 
56     /* Private control to determine when an app is tracking a key sequence. */
57     AKEY_EVENT_FLAG_START_TRACKING = 0x40000000,
58 
59     /* Key event is inconsistent with previously sent key events. */
60     AKEY_EVENT_FLAG_TAINTED = 0x80000000,
61 };
62 
63 enum {
64 
65     /**
66      * This flag indicates that the window that received this motion event is partly
67      * or wholly obscured by another visible window above it.  This flag is set to true
68      * even if the event did not directly pass through the obscured area.
69      * A security sensitive application can check this flag to identify situations in which
70      * a malicious application may have covered up part of its content for the purpose
71      * of misleading the user or hijacking touches.  An appropriate response might be
72      * to drop the suspect touches or to take additional precautions to confirm the user's
73      * actual intent.
74      */
75     AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED = 0x2,
76 
77     /**
78      * This flag indicates that the event has been generated by a gesture generator. It
79      * provides a hint to the GestureDetector to not apply any touch slop.
80      */
81     AMOTION_EVENT_FLAG_IS_GENERATED_GESTURE = 0x8,
82 
83     /**
84      * This flag indicates that the event will not cause a focus change if it is directed to an
85      * unfocused window, even if it an ACTION_DOWN. This is typically used with pointer
86      * gestures to allow the user to direct gestures to an unfocused window without bringing it
87      * into focus.
88      */
89     AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE = 0x40,
90 
91 #ifdef __linux__
92     /**
93      * This event was generated or modified by accessibility service.
94      */
95     AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT =
96             android::os::IInputConstants::INPUT_EVENT_FLAG_IS_ACCESSIBILITY_EVENT, // 0x800,
97 #else
98     AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT = 0x800,
99 #endif
100 
101     /* Motion event is inconsistent with previously sent motion events. */
102     AMOTION_EVENT_FLAG_TAINTED = 0x80000000,
103 };
104 
105 /**
106  * Allowed VerifiedKeyEvent flags. All other flags from KeyEvent do not get verified.
107  * These values must be kept in sync with VerifiedKeyEvent.java
108  */
109 constexpr int32_t VERIFIED_KEY_EVENT_FLAGS =
110         AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
111 
112 /**
113  * Allowed VerifiedMotionEventFlags. All other flags from MotionEvent do not get verified.
114  * These values must be kept in sync with VerifiedMotionEvent.java
115  */
116 constexpr int32_t VERIFIED_MOTION_EVENT_FLAGS = AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED |
117         AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED | AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
118 
119 /**
120  * This flag indicates that the point up event has been canceled.
121  * Typically this is used for palm event when the user has accidental touches.
122  * TODO: Adjust flag to public api
123  */
124 constexpr int32_t AMOTION_EVENT_FLAG_CANCELED = 0x20;
125 
126 enum {
127     /*
128      * Indicates that an input device has switches.
129      * This input source flag is hidden from the API because switches are only used by the system
130      * and applications have no way to interact with them.
131      */
132     AINPUT_SOURCE_SWITCH = 0x80000000,
133 };
134 
135 enum {
136     /**
137      * Constants for LEDs. Hidden from the API since we don't actually expose a way to interact
138      * with LEDs to developers
139      *
140      * NOTE: If you add LEDs here, you must also add them to InputEventLabels.h
141      */
142 
143     ALED_NUM_LOCK = 0x00,
144     ALED_CAPS_LOCK = 0x01,
145     ALED_SCROLL_LOCK = 0x02,
146     ALED_COMPOSE = 0x03,
147     ALED_KANA = 0x04,
148     ALED_SLEEP = 0x05,
149     ALED_SUSPEND = 0x06,
150     ALED_MUTE = 0x07,
151     ALED_MISC = 0x08,
152     ALED_MAIL = 0x09,
153     ALED_CHARGING = 0x0a,
154     ALED_CONTROLLER_1 = 0x10,
155     ALED_CONTROLLER_2 = 0x11,
156     ALED_CONTROLLER_3 = 0x12,
157     ALED_CONTROLLER_4 = 0x13,
158 };
159 
160 /* Maximum number of controller LEDs we support */
161 #define MAX_CONTROLLER_LEDS 4
162 
163 /*
164  * Maximum number of pointers supported per motion event.
165  * Smallest number of pointers is 1.
166  * (We want at least 10 but some touch controllers obstensibly configured for 10 pointers
167  * will occasionally emit 11.  There is not much harm making this constant bigger.)
168  */
169 #define MAX_POINTERS 16
170 
171 /*
172  * Maximum number of samples supported per motion event.
173  */
174 #define MAX_SAMPLES UINT16_MAX
175 
176 /*
177  * Maximum pointer id value supported in a motion event.
178  * Smallest pointer id is 0.
179  * (This is limited by our use of BitSet32 to track pointer assignments.)
180  */
181 #define MAX_POINTER_ID 31
182 
183 /*
184  * Declare a concrete type for the NDK's input event forward declaration.
185  */
186 struct AInputEvent {
~AInputEventAInputEvent187     virtual ~AInputEvent() { }
188 };
189 
190 /*
191  * Declare a concrete type for the NDK's input device forward declaration.
192  */
193 struct AInputDevice {
~AInputDeviceAInputDevice194     virtual ~AInputDevice() { }
195 };
196 
197 
198 namespace android {
199 
200 #ifdef __linux__
201 class Parcel;
202 #endif
203 
204 const char* inputEventTypeToString(int32_t type);
205 
206 /*
207  * Flags that flow alongside events in the input dispatch system to help with certain
208  * policy decisions such as waking from device sleep.
209  *
210  * These flags are also defined in frameworks/base/core/java/android/view/WindowManagerPolicy.java.
211  */
212 enum {
213     /* These flags originate in RawEvents and are generally set in the key map.
214      * NOTE: If you want a flag to be able to set in a keylayout file, then you must add it to
215      * InputEventLabels.h as well. */
216 
217     // Indicates that the event should wake the device.
218     POLICY_FLAG_WAKE = 0x00000001,
219 
220     // Indicates that the key is virtual, such as a capacitive button, and should
221     // generate haptic feedback.  Virtual keys may be suppressed for some time
222     // after a recent touch to prevent accidental activation of virtual keys adjacent
223     // to the touch screen during an edge swipe.
224     POLICY_FLAG_VIRTUAL = 0x00000002,
225 
226     // Indicates that the key is the special function modifier.
227     POLICY_FLAG_FUNCTION = 0x00000004,
228 
229     // Indicates that the key represents a special gesture that has been detected by
230     // the touch firmware or driver.  Causes touch events from the same device to be canceled.
231     POLICY_FLAG_GESTURE = 0x00000008,
232 
233     POLICY_FLAG_RAW_MASK = 0x0000ffff,
234 
235 #ifdef __linux__
236     POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY =
237             android::os::IInputConstants::POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
238 #else
239     POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY = 0x20000,
240 #endif
241 
242     /* These flags are set by the input dispatcher. */
243 
244     // Indicates that the input event was injected.
245     POLICY_FLAG_INJECTED = 0x01000000,
246 
247     // Indicates that the input event is from a trusted source such as a directly attached
248     // input device or an application with system-wide event injection permission.
249     POLICY_FLAG_TRUSTED = 0x02000000,
250 
251     // Indicates that the input event has passed through an input filter.
252     POLICY_FLAG_FILTERED = 0x04000000,
253 
254     // Disables automatic key repeating behavior.
255     POLICY_FLAG_DISABLE_KEY_REPEAT = 0x08000000,
256 
257     /* These flags are set by the input reader policy as it intercepts each event. */
258 
259     // Indicates that the device was in an interactive state when the
260     // event was intercepted.
261     POLICY_FLAG_INTERACTIVE = 0x20000000,
262 
263     // Indicates that the event should be dispatched to applications.
264     // The input event should still be sent to the InputDispatcher so that it can see all
265     // input events received include those that it will not deliver.
266     POLICY_FLAG_PASS_TO_USER = 0x40000000,
267 };
268 
269 /**
270  * Classifications of the current gesture, if available.
271  *
272  * The following values must be kept in sync with MotionEvent.java
273  */
274 enum class MotionClassification : uint8_t {
275     /**
276      * No classification is available.
277      */
278     NONE = 0,
279     /**
280      * Too early to classify the current gesture. Need more events. Look for changes in the
281      * upcoming motion events.
282      */
283     AMBIGUOUS_GESTURE = 1,
284     /**
285      * The current gesture likely represents a user intentionally exerting force on the touchscreen.
286      */
287     DEEP_PRESS = 2,
288 };
289 
290 /**
291  * String representation of MotionClassification
292  */
293 const char* motionClassificationToString(MotionClassification classification);
294 
295 /**
296  * Portion of FrameMetrics timeline of interest to input code.
297  */
298 enum GraphicsTimeline : size_t {
299     /** Time when the app sent the buffer to SurfaceFlinger. */
300     GPU_COMPLETED_TIME = 0,
301 
302     /** Time when the frame was presented on the display */
303     PRESENT_TIME = 1,
304 
305     /** Total size of the 'GraphicsTimeline' array. Must always be last. */
306     SIZE = 2
307 };
308 
309 /**
310  * Generator of unique numbers used to identify input events.
311  *
312  * Layout of ID:
313  *     |--------------------------|---------------------------|
314  *     |   2 bits for source      | 30 bits for random number |
315  *     |--------------------------|---------------------------|
316  */
317 class IdGenerator {
318 private:
319     static constexpr uint32_t SOURCE_SHIFT = 30;
320 
321 public:
322     // Used to divide integer space to ensure no conflict among these sources./
323     enum class Source : int32_t {
324         INPUT_READER = static_cast<int32_t>(0x0u << SOURCE_SHIFT),
325         INPUT_DISPATCHER = static_cast<int32_t>(0x1u << SOURCE_SHIFT),
326         OTHER = static_cast<int32_t>(0x3u << SOURCE_SHIFT), // E.g. app injected events
327     };
328     IdGenerator(Source source);
329 
330     int32_t nextId() const;
331 
332     // Extract source from given id.
getSource(int32_t id)333     static inline Source getSource(int32_t id) { return static_cast<Source>(SOURCE_MASK & id); }
334 
335 private:
336     const Source mSource;
337 
338     static constexpr int32_t SOURCE_MASK = static_cast<int32_t>(0x3u << SOURCE_SHIFT);
339 };
340 
341 /**
342  * Invalid value for cursor position. Used for non-mouse events, tests and injected events. Don't
343  * use it for direct comparison with any other value, because NaN isn't equal to itself according to
344  * IEEE 754. Use isnan() instead to check if a cursor position is valid.
345  */
346 constexpr float AMOTION_EVENT_INVALID_CURSOR_POSITION = std::numeric_limits<float>::quiet_NaN();
347 
348 /*
349  * Pointer coordinate data.
350  */
351 struct PointerCoords {
352     enum { MAX_AXES = 30 }; // 30 so that sizeof(PointerCoords) == 128
353 
354     // Bitfield of axes that are present in this structure.
355     uint64_t bits __attribute__((aligned(8)));
356 
357     // Values of axes that are stored in this structure packed in order by axis id
358     // for each axis that is present in the structure according to 'bits'.
359     float values[MAX_AXES];
360 
clearPointerCoords361     inline void clear() {
362         BitSet64::clear(bits);
363     }
364 
isEmptyPointerCoords365     bool isEmpty() const {
366         return BitSet64::isEmpty(bits);
367     }
368 
369     float getAxisValue(int32_t axis) const;
370     status_t setAxisValue(int32_t axis, float value);
371 
372     void scale(float globalScale);
373 
374     // Scale the pointer coordinates according to a global scale and a
375     // window scale. The global scale will be applied to TOUCH/TOOL_MAJOR/MINOR
376     // axes, however the window scaling will not.
377     void scale(float globalScale, float windowXScale, float windowYScale);
378     void applyOffset(float xOffset, float yOffset);
379 
380     void transform(const ui::Transform& transform);
381 
getXPointerCoords382     inline float getX() const {
383         return getAxisValue(AMOTION_EVENT_AXIS_X);
384     }
385 
getYPointerCoords386     inline float getY() const {
387         return getAxisValue(AMOTION_EVENT_AXIS_Y);
388     }
389 
getXYValuePointerCoords390     vec2 getXYValue() const { return vec2(getX(), getY()); }
391 
392 #ifdef __linux__
393     status_t readFromParcel(Parcel* parcel);
394     status_t writeToParcel(Parcel* parcel) const;
395 #endif
396 
397     bool operator==(const PointerCoords& other) const;
398     inline bool operator!=(const PointerCoords& other) const {
399         return !(*this == other);
400     }
401 
402     void copyFrom(const PointerCoords& other);
403 
404 private:
405     void tooManyAxes(int axis);
406 };
407 
408 /*
409  * Pointer property data.
410  */
411 struct PointerProperties {
412     // The id of the pointer.
413     int32_t id;
414 
415     // The pointer tool type.
416     int32_t toolType;
417 
clearPointerProperties418     inline void clear() {
419         id = -1;
420         toolType = 0;
421     }
422 
423     bool operator==(const PointerProperties& other) const;
424     inline bool operator!=(const PointerProperties& other) const {
425         return !(*this == other);
426     }
427 
428     void copyFrom(const PointerProperties& other);
429 };
430 
431 /*
432  * Input events.
433  */
434 class InputEvent : public AInputEvent {
435 public:
~InputEvent()436     virtual ~InputEvent() { }
437 
438     virtual int32_t getType() const = 0;
439 
getId()440     inline int32_t getId() const { return mId; }
441 
getDeviceId()442     inline int32_t getDeviceId() const { return mDeviceId; }
443 
getSource()444     inline uint32_t getSource() const { return mSource; }
445 
setSource(uint32_t source)446     inline void setSource(uint32_t source) { mSource = source; }
447 
getDisplayId()448     inline int32_t getDisplayId() const { return mDisplayId; }
449 
setDisplayId(int32_t displayId)450     inline void setDisplayId(int32_t displayId) { mDisplayId = displayId; }
451 
getHmac()452     inline std::array<uint8_t, 32> getHmac() const { return mHmac; }
453 
454     static int32_t nextId();
455 
456 protected:
457     void initialize(int32_t id, int32_t deviceId, uint32_t source, int32_t displayId,
458                     std::array<uint8_t, 32> hmac);
459 
460     void initialize(const InputEvent& from);
461 
462     int32_t mId;
463     int32_t mDeviceId;
464     uint32_t mSource;
465     int32_t mDisplayId;
466     std::array<uint8_t, 32> mHmac;
467 };
468 
469 /*
470  * Key events.
471  */
472 class KeyEvent : public InputEvent {
473 public:
~KeyEvent()474     virtual ~KeyEvent() { }
475 
getType()476     virtual int32_t getType() const { return AINPUT_EVENT_TYPE_KEY; }
477 
getAction()478     inline int32_t getAction() const { return mAction; }
479 
getFlags()480     inline int32_t getFlags() const { return mFlags; }
481 
setFlags(int32_t flags)482     inline void setFlags(int32_t flags) { mFlags = flags; }
483 
getKeyCode()484     inline int32_t getKeyCode() const { return mKeyCode; }
485 
getScanCode()486     inline int32_t getScanCode() const { return mScanCode; }
487 
getMetaState()488     inline int32_t getMetaState() const { return mMetaState; }
489 
getRepeatCount()490     inline int32_t getRepeatCount() const { return mRepeatCount; }
491 
getDownTime()492     inline nsecs_t getDownTime() const { return mDownTime; }
493 
getEventTime()494     inline nsecs_t getEventTime() const { return mEventTime; }
495 
496     static const char* getLabel(int32_t keyCode);
497     static int32_t getKeyCodeFromLabel(const char* label);
498 
499     void initialize(int32_t id, int32_t deviceId, uint32_t source, int32_t displayId,
500                     std::array<uint8_t, 32> hmac, int32_t action, int32_t flags, int32_t keyCode,
501                     int32_t scanCode, int32_t metaState, int32_t repeatCount, nsecs_t downTime,
502                     nsecs_t eventTime);
503     void initialize(const KeyEvent& from);
504 
505     static const char* actionToString(int32_t action);
506 
507 protected:
508     int32_t mAction;
509     int32_t mFlags;
510     int32_t mKeyCode;
511     int32_t mScanCode;
512     int32_t mMetaState;
513     int32_t mRepeatCount;
514     nsecs_t mDownTime;
515     nsecs_t mEventTime;
516 };
517 
518 /*
519  * Motion events.
520  */
521 class MotionEvent : public InputEvent {
522 public:
~MotionEvent()523     virtual ~MotionEvent() { }
524 
getType()525     virtual int32_t getType() const { return AINPUT_EVENT_TYPE_MOTION; }
526 
getAction()527     inline int32_t getAction() const { return mAction; }
528 
getActionMasked()529     inline int32_t getActionMasked() const { return mAction & AMOTION_EVENT_ACTION_MASK; }
530 
getActionIndex()531     inline int32_t getActionIndex() const {
532         return (mAction & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK)
533                 >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
534     }
535 
setAction(int32_t action)536     inline void setAction(int32_t action) { mAction = action; }
537 
getFlags()538     inline int32_t getFlags() const { return mFlags; }
539 
setFlags(int32_t flags)540     inline void setFlags(int32_t flags) { mFlags = flags; }
541 
getEdgeFlags()542     inline int32_t getEdgeFlags() const { return mEdgeFlags; }
543 
setEdgeFlags(int32_t edgeFlags)544     inline void setEdgeFlags(int32_t edgeFlags) { mEdgeFlags = edgeFlags; }
545 
getMetaState()546     inline int32_t getMetaState() const { return mMetaState; }
547 
setMetaState(int32_t metaState)548     inline void setMetaState(int32_t metaState) { mMetaState = metaState; }
549 
getButtonState()550     inline int32_t getButtonState() const { return mButtonState; }
551 
setButtonState(int32_t buttonState)552     inline void setButtonState(int32_t buttonState) { mButtonState = buttonState; }
553 
getClassification()554     inline MotionClassification getClassification() const { return mClassification; }
555 
getActionButton()556     inline int32_t getActionButton() const { return mActionButton; }
557 
setActionButton(int32_t button)558     inline void setActionButton(int32_t button) { mActionButton = button; }
559 
getXOffset()560     inline float getXOffset() const { return mTransform.tx(); }
561 
getYOffset()562     inline float getYOffset() const { return mTransform.ty(); }
563 
getTransform()564     inline ui::Transform getTransform() const { return mTransform; }
565 
getXPrecision()566     inline float getXPrecision() const { return mXPrecision; }
567 
getYPrecision()568     inline float getYPrecision() const { return mYPrecision; }
569 
getRawXCursorPosition()570     inline float getRawXCursorPosition() const { return mRawXCursorPosition; }
571 
572     float getXCursorPosition() const;
573 
getRawYCursorPosition()574     inline float getRawYCursorPosition() const { return mRawYCursorPosition; }
575 
576     float getYCursorPosition() const;
577 
578     void setCursorPosition(float x, float y);
579 
getDisplayOrientation()580     uint32_t getDisplayOrientation() const { return mDisplayOrientation; }
581 
getDisplaySize()582     int2 getDisplaySize() const { return {mDisplayWidth, mDisplayHeight}; }
583 
isValidCursorPosition(float x,float y)584     static inline bool isValidCursorPosition(float x, float y) { return !isnan(x) && !isnan(y); }
585 
getDownTime()586     inline nsecs_t getDownTime() const { return mDownTime; }
587 
setDownTime(nsecs_t downTime)588     inline void setDownTime(nsecs_t downTime) { mDownTime = downTime; }
589 
getPointerCount()590     inline size_t getPointerCount() const { return mPointerProperties.size(); }
591 
getPointerProperties(size_t pointerIndex)592     inline const PointerProperties* getPointerProperties(size_t pointerIndex) const {
593         return &mPointerProperties[pointerIndex];
594     }
595 
getPointerId(size_t pointerIndex)596     inline int32_t getPointerId(size_t pointerIndex) const {
597         return mPointerProperties[pointerIndex].id;
598     }
599 
getToolType(size_t pointerIndex)600     inline int32_t getToolType(size_t pointerIndex) const {
601         return mPointerProperties[pointerIndex].toolType;
602     }
603 
getEventTime()604     inline nsecs_t getEventTime() const { return mSampleEventTimes[getHistorySize()]; }
605 
606     /**
607      * The actual raw pointer coords: whatever comes from the input device without any external
608      * transforms applied.
609      */
610     const PointerCoords* getRawPointerCoords(size_t pointerIndex) const;
611 
612     /**
613      * This is the raw axis value. However, for X/Y axes, this currently applies a "compat-raw"
614      * transform because many apps (incorrectly) assumed that raw == oriented-screen-space.
615      * "compat raw" is raw coordinates with screen rotation applied.
616      */
617     float getRawAxisValue(int32_t axis, size_t pointerIndex) const;
618 
getRawX(size_t pointerIndex)619     inline float getRawX(size_t pointerIndex) const {
620         return getRawAxisValue(AMOTION_EVENT_AXIS_X, pointerIndex);
621     }
622 
getRawY(size_t pointerIndex)623     inline float getRawY(size_t pointerIndex) const {
624         return getRawAxisValue(AMOTION_EVENT_AXIS_Y, pointerIndex);
625     }
626 
627     float getAxisValue(int32_t axis, size_t pointerIndex) const;
628 
629     /**
630      * Get the X coordinate of the latest sample in this MotionEvent for pointer 'pointerIndex'.
631      * Identical to calling getHistoricalX(pointerIndex, getHistorySize()).
632      */
getX(size_t pointerIndex)633     inline float getX(size_t pointerIndex) const {
634         return getAxisValue(AMOTION_EVENT_AXIS_X, pointerIndex);
635     }
636 
637     /**
638      * Get the Y coordinate of the latest sample in this MotionEvent for pointer 'pointerIndex'.
639      * Identical to calling getHistoricalX(pointerIndex, getHistorySize()).
640      */
getY(size_t pointerIndex)641     inline float getY(size_t pointerIndex) const {
642         return getAxisValue(AMOTION_EVENT_AXIS_Y, pointerIndex);
643     }
644 
getPressure(size_t pointerIndex)645     inline float getPressure(size_t pointerIndex) const {
646         return getAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pointerIndex);
647     }
648 
getSize(size_t pointerIndex)649     inline float getSize(size_t pointerIndex) const {
650         return getAxisValue(AMOTION_EVENT_AXIS_SIZE, pointerIndex);
651     }
652 
getTouchMajor(size_t pointerIndex)653     inline float getTouchMajor(size_t pointerIndex) const {
654         return getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex);
655     }
656 
getTouchMinor(size_t pointerIndex)657     inline float getTouchMinor(size_t pointerIndex) const {
658         return getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex);
659     }
660 
getToolMajor(size_t pointerIndex)661     inline float getToolMajor(size_t pointerIndex) const {
662         return getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex);
663     }
664 
getToolMinor(size_t pointerIndex)665     inline float getToolMinor(size_t pointerIndex) const {
666         return getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex);
667     }
668 
getOrientation(size_t pointerIndex)669     inline float getOrientation(size_t pointerIndex) const {
670         return getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex);
671     }
672 
getHistorySize()673     inline size_t getHistorySize() const { return mSampleEventTimes.size() - 1; }
674 
getHistoricalEventTime(size_t historicalIndex)675     inline nsecs_t getHistoricalEventTime(size_t historicalIndex) const {
676         return mSampleEventTimes[historicalIndex];
677     }
678 
679     /**
680      * The actual raw pointer coords: whatever comes from the input device without any external
681      * transforms applied.
682      */
683     const PointerCoords* getHistoricalRawPointerCoords(
684             size_t pointerIndex, size_t historicalIndex) const;
685 
686     /**
687      * This is the raw axis value. However, for X/Y axes, this currently applies a "compat-raw"
688      * transform because many apps (incorrectly) assumed that raw == oriented-screen-space.
689      * "compat raw" is raw coordinates with screen rotation applied.
690      */
691     float getHistoricalRawAxisValue(int32_t axis, size_t pointerIndex,
692             size_t historicalIndex) const;
693 
getHistoricalRawX(size_t pointerIndex,size_t historicalIndex)694     inline float getHistoricalRawX(size_t pointerIndex, size_t historicalIndex) const {
695         return getHistoricalRawAxisValue(
696                 AMOTION_EVENT_AXIS_X, pointerIndex, historicalIndex);
697     }
698 
getHistoricalRawY(size_t pointerIndex,size_t historicalIndex)699     inline float getHistoricalRawY(size_t pointerIndex, size_t historicalIndex) const {
700         return getHistoricalRawAxisValue(
701                 AMOTION_EVENT_AXIS_Y, pointerIndex, historicalIndex);
702     }
703 
704     float getHistoricalAxisValue(int32_t axis, size_t pointerIndex, size_t historicalIndex) const;
705 
getHistoricalX(size_t pointerIndex,size_t historicalIndex)706     inline float getHistoricalX(size_t pointerIndex, size_t historicalIndex) const {
707         return getHistoricalAxisValue(
708                 AMOTION_EVENT_AXIS_X, pointerIndex, historicalIndex);
709     }
710 
getHistoricalY(size_t pointerIndex,size_t historicalIndex)711     inline float getHistoricalY(size_t pointerIndex, size_t historicalIndex) const {
712         return getHistoricalAxisValue(
713                 AMOTION_EVENT_AXIS_Y, pointerIndex, historicalIndex);
714     }
715 
getHistoricalPressure(size_t pointerIndex,size_t historicalIndex)716     inline float getHistoricalPressure(size_t pointerIndex, size_t historicalIndex) const {
717         return getHistoricalAxisValue(
718                 AMOTION_EVENT_AXIS_PRESSURE, pointerIndex, historicalIndex);
719     }
720 
getHistoricalSize(size_t pointerIndex,size_t historicalIndex)721     inline float getHistoricalSize(size_t pointerIndex, size_t historicalIndex) const {
722         return getHistoricalAxisValue(
723                 AMOTION_EVENT_AXIS_SIZE, pointerIndex, historicalIndex);
724     }
725 
getHistoricalTouchMajor(size_t pointerIndex,size_t historicalIndex)726     inline float getHistoricalTouchMajor(size_t pointerIndex, size_t historicalIndex) const {
727         return getHistoricalAxisValue(
728                 AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerIndex, historicalIndex);
729     }
730 
getHistoricalTouchMinor(size_t pointerIndex,size_t historicalIndex)731     inline float getHistoricalTouchMinor(size_t pointerIndex, size_t historicalIndex) const {
732         return getHistoricalAxisValue(
733                 AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerIndex, historicalIndex);
734     }
735 
getHistoricalToolMajor(size_t pointerIndex,size_t historicalIndex)736     inline float getHistoricalToolMajor(size_t pointerIndex, size_t historicalIndex) const {
737         return getHistoricalAxisValue(
738                 AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerIndex, historicalIndex);
739     }
740 
getHistoricalToolMinor(size_t pointerIndex,size_t historicalIndex)741     inline float getHistoricalToolMinor(size_t pointerIndex, size_t historicalIndex) const {
742         return getHistoricalAxisValue(
743                 AMOTION_EVENT_AXIS_TOOL_MINOR, pointerIndex, historicalIndex);
744     }
745 
getHistoricalOrientation(size_t pointerIndex,size_t historicalIndex)746     inline float getHistoricalOrientation(size_t pointerIndex, size_t historicalIndex) const {
747         return getHistoricalAxisValue(
748                 AMOTION_EVENT_AXIS_ORIENTATION, pointerIndex, historicalIndex);
749     }
750 
751     ssize_t findPointerIndex(int32_t pointerId) const;
752 
753     void initialize(int32_t id, int32_t deviceId, uint32_t source, int32_t displayId,
754                     std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton,
755                     int32_t flags, int32_t edgeFlags, int32_t metaState, int32_t buttonState,
756                     MotionClassification classification, const ui::Transform& transform,
757                     float xPrecision, float yPrecision, float rawXCursorPosition,
758                     float rawYCursorPosition, uint32_t displayOrientation, int32_t displayWidth,
759                     int32_t displayHeight, nsecs_t downTime, nsecs_t eventTime, size_t pointerCount,
760                     const PointerProperties* pointerProperties, const PointerCoords* pointerCoords);
761 
762     void copyFrom(const MotionEvent* other, bool keepHistory);
763 
764     void addSample(
765             nsecs_t eventTime,
766             const PointerCoords* pointerCoords);
767 
768     void offsetLocation(float xOffset, float yOffset);
769 
770     void scale(float globalScaleFactor);
771 
772     // Set 3x3 perspective matrix transformation.
773     // Matrix is in row-major form and compatible with SkMatrix.
774     void transform(const std::array<float, 9>& matrix);
775 
776     // Apply 3x3 perspective matrix transformation only to content (do not modify mTransform).
777     // Matrix is in row-major form and compatible with SkMatrix.
778     void applyTransform(const std::array<float, 9>& matrix);
779 
780 #ifdef __linux__
781     status_t readFromParcel(Parcel* parcel);
782     status_t writeToParcel(Parcel* parcel) const;
783 #endif
784 
785     static bool isTouchEvent(uint32_t source, int32_t action);
isTouchEvent()786     inline bool isTouchEvent() const {
787         return isTouchEvent(mSource, mAction);
788     }
789 
790     // Low-level accessors.
getPointerProperties()791     inline const PointerProperties* getPointerProperties() const {
792         return mPointerProperties.array();
793     }
getSampleEventTimes()794     inline const nsecs_t* getSampleEventTimes() const { return mSampleEventTimes.data(); }
getSamplePointerCoords()795     inline const PointerCoords* getSamplePointerCoords() const {
796             return mSamplePointerCoords.array();
797     }
798 
799     static const char* getLabel(int32_t axis);
800     static int32_t getAxisFromLabel(const char* label);
801 
802     static std::string actionToString(int32_t action);
803 
804 protected:
805     int32_t mAction;
806     int32_t mActionButton;
807     int32_t mFlags;
808     int32_t mEdgeFlags;
809     int32_t mMetaState;
810     int32_t mButtonState;
811     MotionClassification mClassification;
812     ui::Transform mTransform;
813     float mXPrecision;
814     float mYPrecision;
815     float mRawXCursorPosition;
816     float mRawYCursorPosition;
817     uint32_t mDisplayOrientation;
818     int32_t mDisplayWidth;
819     int32_t mDisplayHeight;
820     nsecs_t mDownTime;
821     Vector<PointerProperties> mPointerProperties;
822     std::vector<nsecs_t> mSampleEventTimes;
823     Vector<PointerCoords> mSamplePointerCoords;
824 };
825 
826 /*
827  * Focus events.
828  */
829 class FocusEvent : public InputEvent {
830 public:
~FocusEvent()831     virtual ~FocusEvent() {}
832 
getType()833     virtual int32_t getType() const override { return AINPUT_EVENT_TYPE_FOCUS; }
834 
getHasFocus()835     inline bool getHasFocus() const { return mHasFocus; }
836 
getInTouchMode()837     inline bool getInTouchMode() const { return mInTouchMode; }
838 
839     void initialize(int32_t id, bool hasFocus, bool inTouchMode);
840 
841     void initialize(const FocusEvent& from);
842 
843 protected:
844     bool mHasFocus;
845     bool mInTouchMode;
846 };
847 
848 /*
849  * Capture events.
850  */
851 class CaptureEvent : public InputEvent {
852 public:
~CaptureEvent()853     virtual ~CaptureEvent() {}
854 
getType()855     virtual int32_t getType() const override { return AINPUT_EVENT_TYPE_CAPTURE; }
856 
getPointerCaptureEnabled()857     inline bool getPointerCaptureEnabled() const { return mPointerCaptureEnabled; }
858 
859     void initialize(int32_t id, bool pointerCaptureEnabled);
860 
861     void initialize(const CaptureEvent& from);
862 
863 protected:
864     bool mPointerCaptureEnabled;
865 };
866 
867 /*
868  * Drag events.
869  */
870 class DragEvent : public InputEvent {
871 public:
~DragEvent()872     virtual ~DragEvent() {}
873 
getType()874     virtual int32_t getType() const override { return AINPUT_EVENT_TYPE_DRAG; }
875 
isExiting()876     inline bool isExiting() const { return mIsExiting; }
877 
getX()878     inline float getX() const { return mX; }
879 
getY()880     inline float getY() const { return mY; }
881 
882     void initialize(int32_t id, float x, float y, bool isExiting);
883 
884     void initialize(const DragEvent& from);
885 
886 protected:
887     bool mIsExiting;
888     float mX, mY;
889 };
890 
891 /**
892  * Base class for verified events.
893  * Do not create a VerifiedInputEvent explicitly.
894  * Use helper functions to create them from InputEvents.
895  */
896 struct __attribute__((__packed__)) VerifiedInputEvent {
897     enum class Type : int32_t {
898         KEY = AINPUT_EVENT_TYPE_KEY,
899         MOTION = AINPUT_EVENT_TYPE_MOTION,
900     };
901 
902     Type type;
903     int32_t deviceId;
904     nsecs_t eventTimeNanos;
905     uint32_t source;
906     int32_t displayId;
907 };
908 
909 /**
910  * Same as KeyEvent, but only contains the data that can be verified.
911  * If you update this class, you must also update VerifiedKeyEvent.java
912  */
913 struct __attribute__((__packed__)) VerifiedKeyEvent : public VerifiedInputEvent {
914     int32_t action;
915     nsecs_t downTimeNanos;
916     int32_t flags;
917     int32_t keyCode;
918     int32_t scanCode;
919     int32_t metaState;
920     int32_t repeatCount;
921 };
922 
923 /**
924  * Same as MotionEvent, but only contains the data that can be verified.
925  * If you update this class, you must also update VerifiedMotionEvent.java
926  */
927 struct __attribute__((__packed__)) VerifiedMotionEvent : public VerifiedInputEvent {
928     float rawX;
929     float rawY;
930     int32_t actionMasked;
931     nsecs_t downTimeNanos;
932     int32_t flags;
933     int32_t metaState;
934     int32_t buttonState;
935 };
936 
937 VerifiedKeyEvent verifiedKeyEventFromKeyEvent(const KeyEvent& event);
938 VerifiedMotionEvent verifiedMotionEventFromMotionEvent(const MotionEvent& event);
939 
940 /*
941  * Input event factory.
942  */
943 class InputEventFactoryInterface {
944 protected:
~InputEventFactoryInterface()945     virtual ~InputEventFactoryInterface() { }
946 
947 public:
InputEventFactoryInterface()948     InputEventFactoryInterface() { }
949 
950     virtual KeyEvent* createKeyEvent() = 0;
951     virtual MotionEvent* createMotionEvent() = 0;
952     virtual FocusEvent* createFocusEvent() = 0;
953     virtual CaptureEvent* createCaptureEvent() = 0;
954     virtual DragEvent* createDragEvent() = 0;
955 };
956 
957 /*
958  * A simple input event factory implementation that uses a single preallocated instance
959  * of each type of input event that are reused for each request.
960  */
961 class PreallocatedInputEventFactory : public InputEventFactoryInterface {
962 public:
PreallocatedInputEventFactory()963     PreallocatedInputEventFactory() { }
~PreallocatedInputEventFactory()964     virtual ~PreallocatedInputEventFactory() { }
965 
createKeyEvent()966     virtual KeyEvent* createKeyEvent() override { return &mKeyEvent; }
createMotionEvent()967     virtual MotionEvent* createMotionEvent() override { return &mMotionEvent; }
createFocusEvent()968     virtual FocusEvent* createFocusEvent() override { return &mFocusEvent; }
createCaptureEvent()969     virtual CaptureEvent* createCaptureEvent() override { return &mCaptureEvent; }
createDragEvent()970     virtual DragEvent* createDragEvent() override { return &mDragEvent; }
971 
972 private:
973     KeyEvent mKeyEvent;
974     MotionEvent mMotionEvent;
975     FocusEvent mFocusEvent;
976     CaptureEvent mCaptureEvent;
977     DragEvent mDragEvent;
978 };
979 
980 /*
981  * An input event factory implementation that maintains a pool of input events.
982  */
983 class PooledInputEventFactory : public InputEventFactoryInterface {
984 public:
985     explicit PooledInputEventFactory(size_t maxPoolSize = 20);
986     virtual ~PooledInputEventFactory();
987 
988     virtual KeyEvent* createKeyEvent() override;
989     virtual MotionEvent* createMotionEvent() override;
990     virtual FocusEvent* createFocusEvent() override;
991     virtual CaptureEvent* createCaptureEvent() override;
992     virtual DragEvent* createDragEvent() override;
993 
994     void recycle(InputEvent* event);
995 
996 private:
997     const size_t mMaxPoolSize;
998 
999     std::queue<std::unique_ptr<KeyEvent>> mKeyEventPool;
1000     std::queue<std::unique_ptr<MotionEvent>> mMotionEventPool;
1001     std::queue<std::unique_ptr<FocusEvent>> mFocusEventPool;
1002     std::queue<std::unique_ptr<CaptureEvent>> mCaptureEventPool;
1003     std::queue<std::unique_ptr<DragEvent>> mDragEventPool;
1004 };
1005 
1006 /*
1007  * Describes a unique request to enable or disable Pointer Capture.
1008  */
1009 struct PointerCaptureRequest {
1010 public:
PointerCaptureRequestPointerCaptureRequest1011     inline PointerCaptureRequest() : enable(false), seq(0) {}
PointerCaptureRequestPointerCaptureRequest1012     inline PointerCaptureRequest(bool enable, uint32_t seq) : enable(enable), seq(seq) {}
1013     inline bool operator==(const PointerCaptureRequest& other) const {
1014         return enable == other.enable && seq == other.seq;
1015     }
1016     explicit inline operator bool() const { return enable; }
1017 
1018     // True iff this is a request to enable Pointer Capture.
1019     bool enable;
1020 
1021     // The sequence number for the request.
1022     uint32_t seq;
1023 };
1024 
1025 } // namespace android
1026 
1027 #endif // _LIBINPUT_INPUT_H
1028