1 /*
2  * Copyright (C) 2018 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 _UI_INPUT_READER_BASE_H
18 #define _UI_INPUT_READER_BASE_H
19 
20 #include "PointerControllerInterface.h"
21 
22 #include <input/DisplayViewport.h>
23 #include <input/Input.h>
24 #include <input/InputDevice.h>
25 #include <input/VelocityControl.h>
26 #include <input/VelocityTracker.h>
27 #include <utils/Errors.h>
28 #include <utils/RefBase.h>
29 
30 #include <stddef.h>
31 #include <unistd.h>
32 #include <optional>
33 #include <set>
34 #include <unordered_map>
35 #include <vector>
36 
37 // Maximum supported size of a vibration pattern.
38 // Must be at least 2.
39 #define MAX_VIBRATE_PATTERN_SIZE 100
40 
41 // Maximum allowable delay value in a vibration pattern before
42 // which the delay will be truncated.
43 #define MAX_VIBRATE_PATTERN_DELAY_NSECS (1000000 * 1000000000LL)
44 
45 namespace android {
46 
47 // --- InputReaderInterface ---
48 
49 /* The interface for the InputReader shared library.
50  *
51  * Manages one or more threads that process raw input events and sends cooked event data to an
52  * input listener.
53  *
54  * The implementation must guarantee thread safety for this interface. However, since the input
55  * listener is NOT thread safe, all calls to the listener must happen from the same thread.
56  */
57 class InputReaderInterface : public virtual RefBase {
58 protected:
InputReaderInterface()59     InputReaderInterface() { }
~InputReaderInterface()60     virtual ~InputReaderInterface() { }
61 
62 public:
63     /* Dumps the state of the input reader.
64      *
65      * This method may be called on any thread (usually by the input manager). */
66     virtual void dump(std::string& dump) = 0;
67 
68     /* Called by the heartbeat to ensures that the reader has not deadlocked. */
69     virtual void monitor() = 0;
70 
71     /* Returns true if the input device is enabled. */
72     virtual bool isInputDeviceEnabled(int32_t deviceId) = 0;
73 
74     /* Makes the reader start processing events from the kernel. */
75     virtual status_t start() = 0;
76 
77     /* Makes the reader stop processing any more events. */
78     virtual status_t stop() = 0;
79 
80     /* Gets information about all input devices.
81      *
82      * This method may be called on any thread (usually by the input manager).
83      */
84     virtual void getInputDevices(std::vector<InputDeviceInfo>& outInputDevices) = 0;
85 
86     /* Query current input state. */
87     virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask,
88             int32_t scanCode) = 0;
89     virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
90             int32_t keyCode) = 0;
91     virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask,
92             int32_t sw) = 0;
93 
94     /* Toggle Caps Lock */
95     virtual void toggleCapsLockState(int32_t deviceId) = 0;
96 
97     /* Determine whether physical keys exist for the given framework-domain key codes. */
98     virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask,
99             size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) = 0;
100 
101     /* Requests that a reconfiguration of all input devices.
102      * The changes flag is a bitfield that indicates what has changed and whether
103      * the input devices must all be reopened. */
104     virtual void requestRefreshConfiguration(uint32_t changes) = 0;
105 
106     /* Controls the vibrator of a particular input device. */
107     virtual void vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
108             ssize_t repeat, int32_t token) = 0;
109     virtual void cancelVibrate(int32_t deviceId, int32_t token) = 0;
110 
111     /* Return true if the device can send input events to the specified display. */
112     virtual bool canDispatchToDisplay(int32_t deviceId, int32_t displayId) = 0;
113 };
114 
115 // --- InputReaderConfiguration ---
116 
117 /*
118  * Input reader configuration.
119  *
120  * Specifies various options that modify the behavior of the input reader.
121  */
122 struct InputReaderConfiguration {
123     // Describes changes that have occurred.
124     enum {
125         // The pointer speed changed.
126         CHANGE_POINTER_SPEED = 1 << 0,
127 
128         // The pointer gesture control changed.
129         CHANGE_POINTER_GESTURE_ENABLEMENT = 1 << 1,
130 
131         // The display size or orientation changed.
132         CHANGE_DISPLAY_INFO = 1 << 2,
133 
134         // The visible touches option changed.
135         CHANGE_SHOW_TOUCHES = 1 << 3,
136 
137         // The keyboard layouts must be reloaded.
138         CHANGE_KEYBOARD_LAYOUTS = 1 << 4,
139 
140         // The device name alias supplied by the may have changed for some devices.
141         CHANGE_DEVICE_ALIAS = 1 << 5,
142 
143         // The location calibration matrix changed.
144         CHANGE_TOUCH_AFFINE_TRANSFORMATION = 1 << 6,
145 
146         // The presence of an external stylus has changed.
147         CHANGE_EXTERNAL_STYLUS_PRESENCE = 1 << 7,
148 
149         // The pointer capture mode has changed.
150         CHANGE_POINTER_CAPTURE = 1 << 8,
151 
152         // The set of disabled input devices (disabledDevices) has changed.
153         CHANGE_ENABLED_STATE = 1 << 9,
154 
155         // All devices must be reopened.
156         CHANGE_MUST_REOPEN = 1 << 31,
157     };
158 
159     // Gets the amount of time to disable virtual keys after the screen is touched
160     // in order to filter out accidental virtual key presses due to swiping gestures
161     // or taps near the edge of the display.  May be 0 to disable the feature.
162     nsecs_t virtualKeyQuietTime;
163 
164     // The excluded device names for the platform.
165     // Devices with these names will be ignored.
166     std::vector<std::string> excludedDeviceNames;
167 
168     // The associations between input ports and display ports.
169     // Used to determine which DisplayViewport should be tied to which InputDevice.
170     std::unordered_map<std::string, uint8_t> portAssociations;
171 
172     // The suggested display ID to show the cursor.
173     int32_t defaultPointerDisplayId;
174 
175     // Velocity control parameters for mouse pointer movements.
176     VelocityControlParameters pointerVelocityControlParameters;
177 
178     // Velocity control parameters for mouse wheel movements.
179     VelocityControlParameters wheelVelocityControlParameters;
180 
181     // True if pointer gestures are enabled.
182     bool pointerGesturesEnabled;
183 
184     // Quiet time between certain pointer gesture transitions.
185     // Time to allow for all fingers or buttons to settle into a stable state before
186     // starting a new gesture.
187     nsecs_t pointerGestureQuietInterval;
188 
189     // The minimum speed that a pointer must travel for us to consider switching the active
190     // touch pointer to it during a drag.  This threshold is set to avoid switching due
191     // to noise from a finger resting on the touch pad (perhaps just pressing it down).
192     float pointerGestureDragMinSwitchSpeed; // in pixels per second
193 
194     // Tap gesture delay time.
195     // The time between down and up must be less than this to be considered a tap.
196     nsecs_t pointerGestureTapInterval;
197 
198     // Tap drag gesture delay time.
199     // The time between the previous tap's up and the next down must be less than
200     // this to be considered a drag.  Otherwise, the previous tap is finished and a
201     // new tap begins.
202     //
203     // Note that the previous tap will be held down for this entire duration so this
204     // interval must be shorter than the long press timeout.
205     nsecs_t pointerGestureTapDragInterval;
206 
207     // The distance in pixels that the pointer is allowed to move from initial down
208     // to up and still be called a tap.
209     float pointerGestureTapSlop; // in pixels
210 
211     // Time after the first touch points go down to settle on an initial centroid.
212     // This is intended to be enough time to handle cases where the user puts down two
213     // fingers at almost but not quite exactly the same time.
214     nsecs_t pointerGestureMultitouchSettleInterval;
215 
216     // The transition from PRESS to SWIPE or FREEFORM gesture mode is made when
217     // at least two pointers have moved at least this far from their starting place.
218     float pointerGestureMultitouchMinDistance; // in pixels
219 
220     // The transition from PRESS to SWIPE gesture mode can only occur when the
221     // cosine of the angle between the two vectors is greater than or equal to than this value
222     // which indicates that the vectors are oriented in the same direction.
223     // When the vectors are oriented in the exactly same direction, the cosine is 1.0.
224     // (In exactly opposite directions, the cosine is -1.0.)
225     float pointerGestureSwipeTransitionAngleCosine;
226 
227     // The transition from PRESS to SWIPE gesture mode can only occur when the
228     // fingers are no more than this far apart relative to the diagonal size of
229     // the touch pad.  For example, a ratio of 0.5 means that the fingers must be
230     // no more than half the diagonal size of the touch pad apart.
231     float pointerGestureSwipeMaxWidthRatio;
232 
233     // The gesture movement speed factor relative to the size of the display.
234     // Movement speed applies when the fingers are moving in the same direction.
235     // Without acceleration, a full swipe of the touch pad diagonal in movement mode
236     // will cover this portion of the display diagonal.
237     float pointerGestureMovementSpeedRatio;
238 
239     // The gesture zoom speed factor relative to the size of the display.
240     // Zoom speed applies when the fingers are mostly moving relative to each other
241     // to execute a scale gesture or similar.
242     // Without acceleration, a full swipe of the touch pad diagonal in zoom mode
243     // will cover this portion of the display diagonal.
244     float pointerGestureZoomSpeedRatio;
245 
246     // True to show the location of touches on the touch screen as spots.
247     bool showTouches;
248 
249     // True if pointer capture is enabled.
250     bool pointerCapture;
251 
252     // The set of currently disabled input devices.
253     std::set<int32_t> disabledDevices;
254 
InputReaderConfigurationInputReaderConfiguration255     InputReaderConfiguration() :
256             virtualKeyQuietTime(0),
257             pointerVelocityControlParameters(1.0f, 500.0f, 3000.0f, 3.0f),
258             wheelVelocityControlParameters(1.0f, 15.0f, 50.0f, 4.0f),
259             pointerGesturesEnabled(true),
260             pointerGestureQuietInterval(100 * 1000000LL), // 100 ms
261             pointerGestureDragMinSwitchSpeed(50), // 50 pixels per second
262             pointerGestureTapInterval(150 * 1000000LL), // 150 ms
263             pointerGestureTapDragInterval(150 * 1000000LL), // 150 ms
264             pointerGestureTapSlop(10.0f), // 10 pixels
265             pointerGestureMultitouchSettleInterval(100 * 1000000LL), // 100 ms
266             pointerGestureMultitouchMinDistance(15), // 15 pixels
267             pointerGestureSwipeTransitionAngleCosine(0.2588f), // cosine of 75 degrees
268             pointerGestureSwipeMaxWidthRatio(0.25f),
269             pointerGestureMovementSpeedRatio(0.8f),
270             pointerGestureZoomSpeedRatio(0.3f),
271             showTouches(false), pointerCapture(false) { }
272 
273     static std::string changesToString(uint32_t changes);
274 
275     std::optional<DisplayViewport> getDisplayViewportByType(ViewportType type) const;
276     std::optional<DisplayViewport> getDisplayViewportByUniqueId(const std::string& uniqueDisplayId)
277             const;
278     std::optional<DisplayViewport> getDisplayViewportByPort(uint8_t physicalPort) const;
279     std::optional<DisplayViewport> getDisplayViewportById(int32_t displayId) const;
280     void setDisplayViewports(const std::vector<DisplayViewport>& viewports);
281 
282 
283     void dump(std::string& dump) const;
284     void dumpViewport(std::string& dump, const DisplayViewport& viewport) const;
285 
286 private:
287     std::vector<DisplayViewport> mDisplays;
288 };
289 
290 // --- TouchAffineTransformation ---
291 
292 struct TouchAffineTransformation {
293     float x_scale;
294     float x_ymix;
295     float x_offset;
296     float y_xmix;
297     float y_scale;
298     float y_offset;
299 
TouchAffineTransformationTouchAffineTransformation300     TouchAffineTransformation() :
301         x_scale(1.0f), x_ymix(0.0f), x_offset(0.0f),
302         y_xmix(0.0f), y_scale(1.0f), y_offset(0.0f) {
303     }
304 
TouchAffineTransformationTouchAffineTransformation305     TouchAffineTransformation(float xscale, float xymix, float xoffset,
306             float yxmix, float yscale, float yoffset) :
307         x_scale(xscale), x_ymix(xymix), x_offset(xoffset),
308         y_xmix(yxmix), y_scale(yscale), y_offset(yoffset) {
309     }
310 
311     void applyTo(float& x, float& y) const;
312 };
313 
314 // --- InputReaderPolicyInterface ---
315 
316 /*
317  * Input reader policy interface.
318  *
319  * The input reader policy is used by the input reader to interact with the Window Manager
320  * and other system components.
321  *
322  * The actual implementation is partially supported by callbacks into the DVM
323  * via JNI.  This interface is also mocked in the unit tests.
324  *
325  * These methods will NOT re-enter the input reader interface, so they may be called from
326  * any method in the input reader interface.
327  */
328 class InputReaderPolicyInterface : public virtual RefBase {
329 protected:
InputReaderPolicyInterface()330     InputReaderPolicyInterface() { }
~InputReaderPolicyInterface()331     virtual ~InputReaderPolicyInterface() { }
332 
333 public:
334     /* Gets the input reader configuration. */
335     virtual void getReaderConfiguration(InputReaderConfiguration* outConfig) = 0;
336 
337     /* Gets a pointer controller associated with the specified cursor device (ie. a mouse). */
338     virtual sp<PointerControllerInterface> obtainPointerController(int32_t deviceId) = 0;
339 
340     /* Notifies the input reader policy that some input devices have changed
341      * and provides information about all current input devices.
342      */
343     virtual void notifyInputDevicesChanged(const std::vector<InputDeviceInfo>& inputDevices) = 0;
344 
345     /* Gets the keyboard layout for a particular input device. */
346     virtual sp<KeyCharacterMap> getKeyboardLayoutOverlay(
347             const InputDeviceIdentifier& identifier) = 0;
348 
349     /* Gets a user-supplied alias for a particular input device, or an empty string if none. */
350     virtual std::string getDeviceAlias(const InputDeviceIdentifier& identifier) = 0;
351 
352     /* Gets the affine calibration associated with the specified device. */
353     virtual TouchAffineTransformation getTouchAffineTransformation(
354             const std::string& inputDeviceDescriptor, int32_t surfaceRotation) = 0;
355 };
356 
357 } // namespace android
358 
359 #endif // _UI_INPUT_READER_COMMON_H
360