xref: /aosp_15_r20/frameworks/native/services/inputflinger/include/InputReaderBase.h (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
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 #pragma once
18 
19 #include <android/os/IInputConstants.h>
20 #include <input/DisplayViewport.h>
21 #include <input/Input.h>
22 #include <input/InputDevice.h>
23 #include <input/VelocityControl.h>
24 #include <input/VelocityTracker.h>
25 #include <stddef.h>
26 #include <ui/Rotation.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 "TouchpadHardwareState.h"
38 #include "VibrationElement.h"
39 #include "include/gestures.h"
40 
41 // Maximum supported size of a vibration pattern.
42 // Must be at least 2.
43 #define MAX_VIBRATE_PATTERN_SIZE 100
44 
45 namespace android {
46 
47 // --- InputReaderConfiguration ---
48 
49 /*
50  * Input reader configuration.
51  *
52  * Specifies various options that modify the behavior of the input reader.
53  */
54 struct InputReaderConfiguration {
55     // Describes changes that have occurred.
56     enum class Change : uint32_t {
57         // The mouse pointer speed changed.
58         POINTER_SPEED = 1u << 0,
59 
60         // The pointer gesture control changed.
61         POINTER_GESTURE_ENABLEMENT = 1u << 1,
62 
63         // The display size or orientation changed.
64         DISPLAY_INFO = 1u << 2,
65 
66         // The keyboard layouts must be reloaded.
67         KEYBOARD_LAYOUTS = 1u << 4,
68 
69         // The device name alias supplied by the may have changed for some devices.
70         DEVICE_ALIAS = 1u << 5,
71 
72         // The location calibration matrix changed.
73         TOUCH_AFFINE_TRANSFORMATION = 1u << 6,
74 
75         // The presence of an external stylus has changed.
76         EXTERNAL_STYLUS_PRESENCE = 1u << 7,
77 
78         // The pointer capture mode has changed.
79         POINTER_CAPTURE = 1u << 8,
80 
81         // The set of disabled input devices (disabledDevices) has changed.
82         ENABLED_STATE = 1u << 9,
83 
84         // The device type has been updated.
85         DEVICE_TYPE = 1u << 10,
86 
87         // The keyboard layout association has changed.
88         KEYBOARD_LAYOUT_ASSOCIATION = 1u << 11,
89 
90         // The stylus button reporting configurations has changed.
91         STYLUS_BUTTON_REPORTING = 1u << 12,
92 
93         // The touchpad settings changed.
94         TOUCHPAD_SETTINGS = 1u << 13,
95 
96         // The key remapping has changed.
97         KEY_REMAPPING = 1u << 14,
98 
99         // The mouse settings changed, this includes mouse reverse vertical scrolling and swap
100         // primary button.
101         MOUSE_SETTINGS = 1u << 15,
102 
103         // All devices must be reopened.
104         MUST_REOPEN = 1u << 31,
105     };
106 
107     // Gets the amount of time to disable virtual keys after the screen is touched
108     // in order to filter out accidental virtual key presses due to swiping gestures
109     // or taps near the edge of the display.  May be 0 to disable the feature.
110     nsecs_t virtualKeyQuietTime;
111 
112     // The excluded device names for the platform.
113     // Devices with these names will be ignored.
114     std::vector<std::string> excludedDeviceNames;
115 
116     // The associations between input ports and display ports.
117     // Used to determine which DisplayViewport should be tied to which InputDevice.
118     std::unordered_map<std::string, uint8_t> inputPortToDisplayPortAssociations;
119 
120     // The associations between input device ports and display unique ids.
121     // Used to determine which DisplayViewport should be tied to which InputDevice.
122     std::unordered_map<std::string, std::string> inputPortToDisplayUniqueIdAssociations;
123 
124     // The associations between input device descriptor and display unique ids.
125     // Used to determine which DisplayViewport should be tied to which InputDevice.
126     std::unordered_map<std::string, std::string> inputDeviceDescriptorToDisplayUniqueIdAssociations;
127 
128     // The associations between input device ports device types.
129     // This is used to determine which device type and source should be tied to which InputDevice.
130     std::unordered_map<std::string, std::string> deviceTypeAssociations;
131 
132     // The map from the input device physical port location to the input device layout info.
133     // Can be used to determine the layout of the keyboard device.
134     std::unordered_map<std::string, KeyboardLayoutInfo> keyboardLayoutAssociations;
135 
136     // The suggested display ID to show the cursor.
137     ui::LogicalDisplayId defaultPointerDisplayId;
138 
139     // The mouse pointer speed, as a number from -7 (slowest) to 7 (fastest).
140     int32_t mousePointerSpeed;
141 
142     // Displays on which an acceleration curve shouldn't be applied for pointer movements from mice.
143     std::set<ui::LogicalDisplayId> displaysWithMousePointerAccelerationDisabled;
144 
145     // Velocity control parameters for touchpad pointer movements on the old touchpad stack (based
146     // on TouchInputMapper).
147     //
148     // For mice, these are ignored and the values of mousePointerSpeed and
149     // mousePointerAccelerationEnabled used instead.
150     //
151     // TODO(b/281840344): remove this.
152     VelocityControlParameters pointerVelocityControlParameters;
153 
154     // Velocity control parameters for mouse wheel movements.
155     VelocityControlParameters wheelVelocityControlParameters;
156 
157     // True if pointer gestures are enabled.
158     bool pointerGesturesEnabled;
159 
160     // Quiet time between certain pointer gesture transitions.
161     // Time to allow for all fingers or buttons to settle into a stable state before
162     // starting a new gesture.
163     nsecs_t pointerGestureQuietInterval;
164 
165     // The minimum speed that a pointer must travel for us to consider switching the active
166     // touch pointer to it during a drag.  This threshold is set to avoid switching due
167     // to noise from a finger resting on the touch pad (perhaps just pressing it down).
168     float pointerGestureDragMinSwitchSpeed; // in pixels per second
169 
170     // Tap gesture delay time.
171     // The time between down and up must be less than this to be considered a tap.
172     nsecs_t pointerGestureTapInterval;
173 
174     // Tap drag gesture delay time.
175     // The time between the previous tap's up and the next down must be less than
176     // this to be considered a drag.  Otherwise, the previous tap is finished and a
177     // new tap begins.
178     //
179     // Note that the previous tap will be held down for this entire duration so this
180     // interval must be shorter than the long press timeout.
181     nsecs_t pointerGestureTapDragInterval;
182 
183     // The distance in pixels that the pointer is allowed to move from initial down
184     // to up and still be called a tap.
185     float pointerGestureTapSlop; // in pixels
186 
187     // Time after the first touch points go down to settle on an initial centroid.
188     // This is intended to be enough time to handle cases where the user puts down two
189     // fingers at almost but not quite exactly the same time.
190     nsecs_t pointerGestureMultitouchSettleInterval;
191 
192     // The transition from PRESS to SWIPE or FREEFORM gesture mode is made when
193     // at least two pointers have moved at least this far from their starting place.
194     float pointerGestureMultitouchMinDistance; // in pixels
195 
196     // The transition from PRESS to SWIPE gesture mode can only occur when the
197     // cosine of the angle between the two vectors is greater than or equal to than this value
198     // which indicates that the vectors are oriented in the same direction.
199     // When the vectors are oriented in the exactly same direction, the cosine is 1.0.
200     // (In exactly opposite directions, the cosine is -1.0.)
201     float pointerGestureSwipeTransitionAngleCosine;
202 
203     // The transition from PRESS to SWIPE gesture mode can only occur when the
204     // fingers are no more than this far apart relative to the diagonal size of
205     // the touch pad.  For example, a ratio of 0.5 means that the fingers must be
206     // no more than half the diagonal size of the touch pad apart.
207     float pointerGestureSwipeMaxWidthRatio;
208 
209     // The gesture movement speed factor relative to the size of the display.
210     // Movement speed applies when the fingers are moving in the same direction.
211     // Without acceleration, a full swipe of the touch pad diagonal in movement mode
212     // will cover this portion of the display diagonal.
213     float pointerGestureMovementSpeedRatio;
214 
215     // The gesture zoom speed factor relative to the size of the display.
216     // Zoom speed applies when the fingers are mostly moving relative to each other
217     // to execute a scale gesture or similar.
218     // Without acceleration, a full swipe of the touch pad diagonal in zoom mode
219     // will cover this portion of the display diagonal.
220     float pointerGestureZoomSpeedRatio;
221 
222     // The latest request to enable or disable Pointer Capture.
223     PointerCaptureRequest pointerCaptureRequest;
224 
225     // The touchpad pointer speed, as a number from -7 (slowest) to 7 (fastest).
226     int32_t touchpadPointerSpeed;
227 
228     // True to invert the touchpad scrolling direction, so that moving two fingers downwards on the
229     // touchpad scrolls the content upwards.
230     bool touchpadNaturalScrollingEnabled;
231 
232     // True to enable tap-to-click on touchpads.
233     bool touchpadTapToClickEnabled;
234 
235     // True to enable tap dragging on touchpads.
236     bool touchpadTapDraggingEnabled;
237 
238     // True if hardware state update notifications should be sent to the policy.
239     bool shouldNotifyTouchpadHardwareState;
240 
241     // True to enable a zone on the right-hand side of touchpads where clicks will be turned into
242     // context (a.k.a. "right") clicks.
243     bool touchpadRightClickZoneEnabled;
244 
245     // True to use three-finger tap as a customizable shortcut; false to use it as a middle-click.
246     bool touchpadThreeFingerTapShortcutEnabled;
247 
248     // True to enable system gestures (three- and four-finger swipes) on touchpads.
249     bool touchpadSystemGesturesEnabled;
250 
251     // The set of currently disabled input devices.
252     std::set<int32_t> disabledDevices;
253 
254     // True if stylus button reporting through motion events should be enabled, in which case
255     // stylus button state changes are reported through motion events.
256     bool stylusButtonMotionEventsEnabled;
257 
258     // True if a pointer icon should be shown for direct stylus pointers.
259     bool stylusPointerIconEnabled;
260 
261     // Keycodes to be remapped.
262     std::map<int32_t /* fromKeyCode */, int32_t /* toKeyCode */> keyRemapping;
263 
264     // True if the external mouse should have its vertical scrolling reversed, so that rotating the
265     // wheel downwards scrolls the content upwards.
266     bool mouseReverseVerticalScrollingEnabled;
267 
268     // True if the connected mouse should have its primary button (default: left click) swapped,
269     // so that the right click will be the primary action button and the left click will be the
270     // secondary action.
271     bool mouseSwapPrimaryButtonEnabled;
272 
InputReaderConfigurationInputReaderConfiguration273     InputReaderConfiguration()
274           : virtualKeyQuietTime(0),
275             defaultPointerDisplayId(ui::LogicalDisplayId::DEFAULT),
276             mousePointerSpeed(0),
277             displaysWithMousePointerAccelerationDisabled(),
278             pointerVelocityControlParameters(1.0f, 500.0f, 3000.0f,
279                                              static_cast<float>(
280                                                      android::os::IInputConstants::
281                                                              DEFAULT_POINTER_ACCELERATION)),
282             wheelVelocityControlParameters(1.0f, 15.0f, 50.0f, 4.0f),
283             pointerGesturesEnabled(true),
284             pointerGestureQuietInterval(100 * 1000000LL),            // 100 ms
285             pointerGestureDragMinSwitchSpeed(50),                    // 50 pixels per second
286             pointerGestureTapInterval(150 * 1000000LL),              // 150 ms
287             pointerGestureTapDragInterval(150 * 1000000LL),          // 150 ms
288             pointerGestureTapSlop(10.0f),                            // 10 pixels
289             pointerGestureMultitouchSettleInterval(100 * 1000000LL), // 100 ms
290             pointerGestureMultitouchMinDistance(15),                 // 15 pixels
291             pointerGestureSwipeTransitionAngleCosine(0.2588f),       // cosine of 75 degrees
292             pointerGestureSwipeMaxWidthRatio(0.25f),
293             pointerGestureMovementSpeedRatio(0.8f),
294             pointerGestureZoomSpeedRatio(0.3f),
295             pointerCaptureRequest(),
296             touchpadPointerSpeed(0),
297             touchpadNaturalScrollingEnabled(true),
298             touchpadTapToClickEnabled(true),
299             touchpadTapDraggingEnabled(false),
300             shouldNotifyTouchpadHardwareState(false),
301             touchpadRightClickZoneEnabled(false),
302             touchpadThreeFingerTapShortcutEnabled(false),
303             touchpadSystemGesturesEnabled(true),
304             stylusButtonMotionEventsEnabled(true),
305             stylusPointerIconEnabled(false),
306             mouseReverseVerticalScrollingEnabled(false),
307             mouseSwapPrimaryButtonEnabled(false) {}
308 
309     std::optional<DisplayViewport> getDisplayViewportByType(ViewportType type) const;
310     std::optional<DisplayViewport> getDisplayViewportByUniqueId(const std::string& uniqueDisplayId)
311             const;
312     std::optional<DisplayViewport> getDisplayViewportByPort(uint8_t physicalPort) const;
313     std::optional<DisplayViewport> getDisplayViewportById(ui::LogicalDisplayId displayId) const;
314     void setDisplayViewports(const std::vector<DisplayViewport>& viewports);
315 
316     void dump(std::string& dump) const;
317     void dumpViewport(std::string& dump, const DisplayViewport& viewport) const;
318 
319 private:
320     std::vector<DisplayViewport> mDisplays;
321 };
322 
323 using ConfigurationChanges = ftl::Flags<InputReaderConfiguration::Change>;
324 
325 // --- InputReaderInterface ---
326 
327 /* The interface for the InputReader shared library.
328  *
329  * Manages one or more threads that process raw input events and sends cooked event data to an
330  * input listener.
331  *
332  * The implementation must guarantee thread safety for this interface. However, since the input
333  * listener is NOT thread safe, all calls to the listener must happen from the same thread.
334  */
335 class InputReaderInterface {
336 public:
InputReaderInterface()337     InputReaderInterface() {}
~InputReaderInterface()338     virtual ~InputReaderInterface() {}
339     /* Dumps the state of the input reader.
340      *
341      * This method may be called on any thread (usually by the input manager). */
342     virtual void dump(std::string& dump) = 0;
343 
344     /* Called by the heartbeat to ensures that the reader has not deadlocked. */
345     virtual void monitor() = 0;
346 
347     /* Makes the reader start processing events from the kernel. */
348     virtual status_t start() = 0;
349 
350     /* Makes the reader stop processing any more events. */
351     virtual status_t stop() = 0;
352 
353     /* Gets information about all input devices.
354      *
355      * This method may be called on any thread (usually by the input manager).
356      */
357     virtual std::vector<InputDeviceInfo> getInputDevices() const = 0;
358 
359     /* Query current input state. */
360     virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask, int32_t scanCode) = 0;
361     virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask, int32_t keyCode) = 0;
362     virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t sw) = 0;
363 
364     virtual int32_t getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const = 0;
365 
366     /* Toggle Caps Lock */
367     virtual void toggleCapsLockState(int32_t deviceId) = 0;
368 
369     /* Resets locked modifier state */
370     virtual void resetLockedModifierState() = 0;
371 
372     /* Determine whether physical keys exist for the given framework-domain key codes. */
373     virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask,
374                          const std::vector<int32_t>& keyCodes, uint8_t* outFlags) = 0;
375 
376     /* Requests that a reconfiguration of all input devices.
377      * The changes flag is a bitfield that indicates what has changed and whether
378      * the input devices must all be reopened. */
379     virtual void requestRefreshConfiguration(ConfigurationChanges changes) = 0;
380 
381     /* Controls the vibrator of a particular input device. */
382     virtual void vibrate(int32_t deviceId, const VibrationSequence& sequence, ssize_t repeat,
383                          int32_t token) = 0;
384     virtual void cancelVibrate(int32_t deviceId, int32_t token) = 0;
385 
386     virtual bool isVibrating(int32_t deviceId) = 0;
387 
388     virtual std::vector<int32_t> getVibratorIds(int32_t deviceId) = 0;
389     /* Get battery level of a particular input device. */
390     virtual std::optional<int32_t> getBatteryCapacity(int32_t deviceId) = 0;
391     /* Get battery status of a particular input device. */
392     virtual std::optional<int32_t> getBatteryStatus(int32_t deviceId) = 0;
393     /* Get the device path for the battery of an input device. */
394     virtual std::optional<std::string> getBatteryDevicePath(int32_t deviceId) = 0;
395 
396     virtual std::vector<InputDeviceLightInfo> getLights(int32_t deviceId) = 0;
397 
398     virtual std::vector<InputDeviceSensorInfo> getSensors(int32_t deviceId) = 0;
399 
400     virtual std::optional<HardwareProperties> getTouchpadHardwareProperties(int32_t deviceId) = 0;
401 
402     /* Return true if the device can send input events to the specified display. */
403     virtual bool canDispatchToDisplay(int32_t deviceId, ui::LogicalDisplayId displayId) = 0;
404 
405     /* Enable sensor in input reader mapper. */
406     virtual bool enableSensor(int32_t deviceId, InputDeviceSensorType sensorType,
407                               std::chrono::microseconds samplingPeriod,
408                               std::chrono::microseconds maxBatchReportLatency) = 0;
409 
410     /* Disable sensor in input reader mapper. */
411     virtual void disableSensor(int32_t deviceId, InputDeviceSensorType sensorType) = 0;
412 
413     /* Flush sensor data in input reader mapper. */
414     virtual void flushSensor(int32_t deviceId, InputDeviceSensorType sensorType) = 0;
415 
416     /* Set color for the light */
417     virtual bool setLightColor(int32_t deviceId, int32_t lightId, int32_t color) = 0;
418     /* Set player ID for the light */
419     virtual bool setLightPlayerId(int32_t deviceId, int32_t lightId, int32_t playerId) = 0;
420     /* Get light color */
421     virtual std::optional<int32_t> getLightColor(int32_t deviceId, int32_t lightId) = 0;
422     /* Get light player ID */
423     virtual std::optional<int32_t> getLightPlayerId(int32_t deviceId, int32_t lightId) = 0;
424 
425     /* Get the Bluetooth address of an input device, if known. */
426     virtual std::optional<std::string> getBluetoothAddress(int32_t deviceId) const = 0;
427 
428     /* Sysfs node change reported. Recreate device if required to incorporate the new sysfs nodes */
429     virtual void sysfsNodeChanged(const std::string& sysfsNodePath) = 0;
430 
431     /* Get the ID of the InputDevice that was used most recently.
432      *
433      * Returns ReservedInputDeviceId::INVALID_INPUT_DEVICE_ID if no device has been used since boot.
434      */
435     virtual DeviceId getLastUsedInputDeviceId() = 0;
436 
437     /* Notifies that mouse cursor faded due to typing. */
438     virtual void notifyMouseCursorFadedOnTyping() = 0;
439 
440     /* Set whether the given input device can wake up the kernel from sleep
441      * when it generates input events. By default, usually only internal (built-in)
442      * input devices can wake the kernel from sleep. For an external input device
443      * that supports remote wakeup to be able to wake the kernel, this must be called
444      * after each time the device is connected/added.
445      *
446      * Returns true if setting power wakeup was successful.
447      */
448     virtual bool setKernelWakeEnabled(int32_t deviceId, bool enabled) = 0;
449 };
450 
451 // --- TouchAffineTransformation ---
452 
453 struct TouchAffineTransformation {
454     float x_scale;
455     float x_ymix;
456     float x_offset;
457     float y_xmix;
458     float y_scale;
459     float y_offset;
460 
TouchAffineTransformationTouchAffineTransformation461     TouchAffineTransformation() :
462         x_scale(1.0f), x_ymix(0.0f), x_offset(0.0f),
463         y_xmix(0.0f), y_scale(1.0f), y_offset(0.0f) {
464     }
465 
TouchAffineTransformationTouchAffineTransformation466     TouchAffineTransformation(float xscale, float xymix, float xoffset,
467             float yxmix, float yscale, float yoffset) :
468         x_scale(xscale), x_ymix(xymix), x_offset(xoffset),
469         y_xmix(yxmix), y_scale(yscale), y_offset(yoffset) {
470     }
471 
472     void applyTo(float& x, float& y) const;
473 };
474 
475 // --- InputReaderPolicyInterface ---
476 
477 /*
478  * Input reader policy interface.
479  *
480  * The input reader policy is used by the input reader to interact with the Window Manager
481  * and other system components.
482  *
483  * The actual implementation is partially supported by callbacks into the DVM
484  * via JNI.  This interface is also mocked in the unit tests.
485  *
486  * These methods will NOT re-enter the input reader interface, so they may be called from
487  * any method in the input reader interface.
488  */
489 class InputReaderPolicyInterface : public virtual RefBase {
490 protected:
InputReaderPolicyInterface()491     InputReaderPolicyInterface() { }
~InputReaderPolicyInterface()492     virtual ~InputReaderPolicyInterface() { }
493 
494 public:
495     /* Gets the input reader configuration. */
496     virtual void getReaderConfiguration(InputReaderConfiguration* outConfig) = 0;
497 
498     /* Notifies the input reader policy that some input devices have changed
499      * and provides information about all current input devices.
500      */
501     virtual void notifyInputDevicesChanged(const std::vector<InputDeviceInfo>& inputDevices) = 0;
502 
503     /* Sends the hardware state of a connected touchpad */
504     virtual void notifyTouchpadHardwareState(const SelfContainedHardwareState& schs,
505                                              int32_t deviceId) = 0;
506 
507     /* Sends the Info of gestures that happen on the touchpad. */
508     virtual void notifyTouchpadGestureInfo(GestureType type, int32_t deviceId) = 0;
509 
510     /* Notifies the policy that the user has performed a three-finger touchpad tap. */
511     virtual void notifyTouchpadThreeFingerTap() = 0;
512 
513     /* Gets the keyboard layout for a particular input device. */
514     virtual std::shared_ptr<KeyCharacterMap> getKeyboardLayoutOverlay(
515             const InputDeviceIdentifier& identifier,
516             const std::optional<KeyboardLayoutInfo> keyboardLayoutInfo) = 0;
517 
518     /* Gets a user-supplied alias for a particular input device, or an empty string if none. */
519     virtual std::string getDeviceAlias(const InputDeviceIdentifier& identifier) = 0;
520 
521     /* Gets the affine calibration associated with the specified device. */
522     virtual TouchAffineTransformation getTouchAffineTransformation(
523             const std::string& inputDeviceDescriptor, ui::Rotation surfaceRotation) = 0;
524     /* Notifies the input reader policy that a stylus gesture has started. */
525     virtual void notifyStylusGestureStarted(int32_t deviceId, nsecs_t eventTime) = 0;
526 
527     /* Returns true if any InputConnection is currently active. */
528     virtual bool isInputMethodConnectionActive() = 0;
529 
530     /* Gets the viewport of a particular display that the pointer device is associated with. If
531      * the pointer device is not associated with any display, it should ADISPLAY_IS_NONE to get
532      * the viewport that should be used. The device should get a new viewport using this method
533      * every time there is a display configuration change. The logical bounds of the viewport should
534      * be used as the range of possible values for pointing devices, like mice and touchpads.
535      */
536     virtual std::optional<DisplayViewport> getPointerViewportForAssociatedDisplay(
537             ui::LogicalDisplayId associatedDisplayId = ui::LogicalDisplayId::INVALID) = 0;
538 };
539 
540 } // namespace android
541