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