Skip to main content

gpui_base/
value_mapping.rs

1use std::rc::Rc;
2
3/// How a slider maps its position to a value.
4///
5/// [`ValueMapping::Linear`] and [`ValueMapping::Logarithmic`] are the built-in
6/// mappings. [`ValueMapping::Custom`] takes a pair of inverse functions when a
7/// parameter follows its own curve.
8///
9/// The functions must be monotonic and inverse to each other. Inputs are
10/// clamped to `0.0..=1.0` and `min..=max`, and a non-finite result falls back
11/// to the low end.
12#[derive(Clone, Default)]
13pub enum ValueMapping {
14    /// Values change uniformly across the slider range.
15    #[default]
16    Linear,
17    /// The distance between values grows exponentially; `min` must be greater
18    /// than zero.
19    ///
20    /// This is useful for parameters with a large range where smaller changes
21    /// are more significant at lower values, such as volume, frequency, and
22    /// zoom.
23    ///
24    /// Moving the slider 1/3 of the way yields ~10, 2/3 yields ~100, and the
25    /// full range covers three orders of magnitude evenly.
26    Logarithmic,
27    /// A caller-supplied pair of inverse mappings between a value and its
28    /// fraction of the range.
29    Custom {
30        /// Maps a value inside `min..=max` to `0.0..=1.0`.
31        to_normalized: Rc<dyn Fn(f32) -> f32>,
32        /// Maps `0.0..=1.0` back to a value inside `min..=max`.
33        from_normalized: Rc<dyn Fn(f32) -> f32>,
34    },
35}
36
37impl ValueMapping {
38    /// Creates a custom mapping from a pair of inverse functions.
39    ///
40    /// `to_normalized` maps a value to its fraction of the range, and
41    /// `from_normalized` maps that fraction back to a value.
42    pub fn custom(
43        to_normalized: impl Fn(f32) -> f32 + 'static,
44        from_normalized: impl Fn(f32) -> f32 + 'static,
45    ) -> Self {
46        Self::Custom {
47            to_normalized: Rc::new(to_normalized),
48            from_normalized: Rc::new(from_normalized),
49        }
50    }
51
52    /// Whether this is the built-in linear mapping.
53    #[inline]
54    pub fn is_linear(&self) -> bool {
55        matches!(self, Self::Linear)
56    }
57
58    /// Whether this is the built-in logarithmic mapping.
59    #[inline]
60    pub fn is_logarithmic(&self) -> bool {
61        matches!(self, Self::Logarithmic)
62    }
63}