egui_fancy_knob 0.2.0

Feature-rich circular knob widget for egui, originally forked from egui_knob.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use egui::{Align2, Color32, Rect, Response, Sense, Stroke, Ui, Vec2, Widget};
use std::f32::consts::TAU;
use std::ops::RangeInclusive;

mod normalise;

use normalise::*;

const KNOB_FINE_DRAG_RATIO: f32 = 0.2;
const INFINITY: f32 = f32::INFINITY;

pub fn add_knob<F: Fn()>(ui: &mut Ui, knob: Knob<impl FnMut(f32)>, on_release: F) {
    let response = ui.add(knob);

    if response.drag_stopped() || response.lost_focus() {
        on_release();
    }
}

#[derive(Clone)]
struct KnobSpec {
    logarithmic: bool,
    /// For logarithmic knobs, the smallest positive value we are interested in before the knob
    /// switches to `0.0`.
    smallest_finite: f32,
    /// For logarithmic knobs, the largest positive value we are interested in before the knob
    /// switches to `INFINITY`.
    largest_finite: f32,
}

/// Position of the label relative to the knob
pub enum LabelPosition {
    Top,
    Bottom,
    Left,
    Right,
}

/// Visual style of the knob indicator
pub enum KnobStyle {
    /// A line extending from the center to the edge
    Wiper,
    /// A dot on the edge of the knob
    Dot,
}

/// A circular knob widget for egui that can be dragged to change a value
///
/// # Example
/// ```
/// let mut value = 0.5;
/// Knob::new(&mut value, 0.0, 1.0, KnobStyle::Wiper)
///     .with_size(50.0)
///     .with_label("Volume", LabelPosition::Bottom)
///     .with_step(0.1);
/// ```
pub struct Knob<F: FnMut(f32)> {
    value: f32,
    set_value: F,
    range: RangeInclusive<f32>,
    spec: KnobSpec,
    size: f32,
    font_size: f32,
    stroke_width: f32,
    knob_color: Color32,
    knob_dragging_color: Color32,
    line_color: Color32,
    text_color: Color32,
    label: Option<String>,
    label_position: LabelPosition,
    style: KnobStyle,
    label_offset: f32,
    label_format: Box<dyn FnMut(f32) -> String>,
    step: Option<f32>,
    neutral: Option<f32>,
    enabled: bool,
}

impl<F: FnMut(f32)> Knob<F> {
    /// Creates a new knob widget
    ///
    /// # Arguments
    /// * `value` - Mutable reference to the value controlled by the knob
    /// * `min` - Minimum value
    /// * `max` - Maximum value
    /// * `style` - Visual style of the knob indicator
    /// * `spec` - Parameters for a logarithmic knob
    pub fn new(value: f32, set_value: F, range: RangeInclusive<f32>, style: KnobStyle) -> Self {
        Self {
            value: value.clamp(*range.start(), *range.end()),
            set_value,
            range,
            spec: KnobSpec {
                logarithmic: false,
                smallest_finite: 1e-6,
                largest_finite: 1e6,
            },
            size: 40.0,
            font_size: 12.0,
            stroke_width: 2.0,
            knob_color: Color32::GRAY,
            knob_dragging_color: Color32::WHITE,
            line_color: Color32::GRAY,
            text_color: Color32::WHITE,
            label: None,
            label_position: LabelPosition::Bottom,
            style,
            label_offset: 1.0,
            label_format: Box::new(|v| {
                if v.abs() > 1e-2 || v == 0.0 {
                    format!("{:.2}", v)
                } else {
                    // Display values close to zero in scientific power notation.
                    // Otherwise they display as 0.0.
                    format!("{:+.1e}", v)
                }
            }),
            step: None,
            neutral: None,
            enabled: true,
        }
    }

    /// Sets the size of the knob
    pub fn with_size(mut self, size: f32) -> Self {
        self.size = size;
        self
    }

    /// Sets the font size for the label
    pub fn with_font_size(mut self, size: f32) -> Self {
        self.font_size = size;
        self
    }

    /// Sets the stroke width for the knob's outline and indicator
    pub fn with_stroke_width(mut self, width: f32) -> Self {
        self.stroke_width = width;
        self
    }

    /// Sets the colors for different parts of the knob
    ///
    /// # Arguments
    /// * `knob_color` - Color of the knob's outline
    /// * `line_color` - Color of the indicator
    /// * `text_color` - Color of the label text
    pub fn with_colors(
        mut self,
        knob_color: Color32,
        knob_dragging_color: Color32,
        line_color: Color32,
        text_color: Color32,
    ) -> Self {
        self.knob_color = knob_color;
        self.knob_dragging_color = knob_dragging_color;
        self.line_color = line_color;
        self.text_color = text_color;
        self
    }

    /// Adds a label to the knob
    ///
    /// # Arguments
    /// * `label` - Text to display
    /// * `position` - Position of the label relative to the knob
    pub fn with_label(mut self, label: impl Into<String>, position: LabelPosition) -> Self {
        self.label = Some(label.into());
        self.label_position = position;
        self
    }

    /// Sets the spacing between the knob and its label
    pub fn with_label_offset(mut self, offset: f32) -> Self {
        self.label_offset = offset;
        self
    }

    /// Sets a custom format function for displaying the value
    ///
    /// # Example
    /// ```
    /// # let mut value = 0.5;
    /// Knob::new(&mut value, 0.0, 1.0, KnobStyle::Wiper)
    ///     .with_label_format(|v| format!("{:.1}%", v * 100.0));
    /// ```
    pub fn with_label_format(mut self, format: impl FnMut(f32) -> String + 'static) -> Self {
        self.label_format = Box::new(format);
        self
    }

    /// Sets the step size for value changes.
    ///
    /// When set, the value will snap to discrete steps as the knob is dragged.
    pub fn with_step(mut self, step: f32) -> Self {
        self.step = Some(step);
        self
    }

    /// Sets the neutral value.
    ///
    /// When the knob is double clicked, it will reset to the neutral value.
    pub fn with_neutral(mut self, neutral: f32) -> Self {
        self.neutral = Some(neutral);
        self
    }

    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// Make this a logarithmic knob.
    /// The default is OFF.
    pub fn logarithmic(mut self, logarithmic: bool) -> Self {
        self.spec.logarithmic = logarithmic;
        self
    }

    /// For logarithmic knobs that include zero.
    /// What is the smallest possible value that can be selected
    /// before the value goes to zero.
    /// Value is absolute so works for ranges `0..=x` and `x..=0`.
    pub fn smallest_finite(mut self, smallest_finite: f32) -> Self {
        self.spec.smallest_finite = smallest_finite.abs();
        self
    }

    /// For logarithmic knobs that go to infinity.
    /// What is the largest possible value that can be selected
    /// before the value goes to infinity.
    /// Value is absolute so works for ranges `NEG_INFINITY..=x` and `x..=NEG_INFINITY`.
    pub fn largest_finite(mut self, largest_finite: f32) -> Self {
        self.spec.largest_finite = largest_finite.abs();
        self
    }
}

impl<F: FnMut(f32)> Widget for Knob<F> {
    fn ui(mut self, ui: &mut Ui) -> Response {
        let knob_size = Vec2::splat(self.size);
        let min = *self.range.start();
        let max = *self.range.end();
        let label_size = if let Some(label) = &self.label {
            let font_id = egui::FontId::proportional(self.font_size);
            let max_text = format!("{}: {}", label, (self.label_format)(max));
            ui.painter()
                .layout(max_text, font_id, Color32::WHITE, INFINITY)
                .size()
        } else {
            Vec2::ZERO
        };

        let label_padding = 2.0;
        let vertical_margin = 4.0;

        ui.add_space(vertical_margin);

        let adjusted_size = match self.label_position {
            LabelPosition::Top | LabelPosition::Bottom => Vec2::new(
                knob_size.x.max(label_size.x + label_padding * 2.0),
                knob_size.y + label_size.y + label_padding * 2.0 + self.label_offset,
            ),
            LabelPosition::Left | LabelPosition::Right => Vec2::new(
                knob_size.x + label_size.x + label_padding * 2.0 + self.label_offset,
                knob_size.y.max(label_size.y + label_padding * 2.0),
            ),
        };

        let (rect, mut response) = ui.allocate_exact_size(adjusted_size, Sense::click_and_drag());

        if self.enabled {
            // Double click to return to neutral state.
            if response.double_clicked() {
                if let Some(neutral) = self.neutral {
                    if neutral != self.value {
                        (self.set_value)(neutral);
                        response.mark_changed();
                    }
                }
            } else if response.dragged() {
                let mut delta = response.drag_delta().y;

                // Hold ctrl, alt or shift to move finely.
                ui.input(|input| {
                    if input.modifiers.ctrl || input.modifiers.shift || input.modifiers.alt {
                        delta *= KNOB_FINE_DRAG_RATIO;
                    }
                });

                let step = if let Some(step) = self.step {
                    // Normalise step size.
                    step / (max - min).abs()
                } else {
                    0.005
                };
                let mut new_value =
                    normalised_from_value(self.value, self.range.clone(), &self.spec)
                        - delta * step;
                if self.step.is_some() {
                    let steps = (new_value / step).round();
                    new_value = (steps * step).clamp(0.0, 1.0)
                }

                if new_value != self.value {
                    (self.set_value)(value_from_normalised(
                        new_value,
                        self.range.clone(),
                        &self.spec,
                    ));
                    response.mark_changed();
                }
            }
        }

        let is_dragging = response.dragged() && self.enabled;
        let painter = ui.painter();
        let knob_rect = match self.label_position {
            LabelPosition::Left => {
                Rect::from_min_size(rect.right_top() + Vec2::new(-knob_size.x, 0.0), knob_size)
            }
            LabelPosition::Right => Rect::from_min_size(rect.left_top(), knob_size),
            LabelPosition::Top => Rect::from_min_size(
                rect.left_bottom() + Vec2::new((rect.width() - knob_size.x) / 2.0, -knob_size.y),
                knob_size,
            ),
            LabelPosition::Bottom => Rect::from_min_size(
                rect.left_top() + Vec2::new((rect.width() - knob_size.x) / 2.0, 0.0),
                knob_size,
            ),
        };

        let center = knob_rect.center();
        let radius = if is_dragging {
            knob_size.x * 0.55
        } else {
            knob_size.x * 0.5
        };

        // The range of motion of the knob. 1.0 means a full rotation.
        let range = 0.85;

        // 0.0 points right. 0.25 points down.
        let down = 0.25;

        // The necessary offset from pointing down, in order for motion to be symmetrical.
        let offset = (1.0 - range) * 0.5;

        let start_angle = down + offset;

        let angle =
            TAU * (normalised_from_value(self.value, self.range, &self.spec) * range + start_angle);

        let knob_color = if is_dragging {
            self.knob_dragging_color
        } else {
            self.knob_color
        };
        painter.circle_stroke(center, radius, Stroke::new(self.stroke_width, knob_color));

        match self.style {
            KnobStyle::Wiper => {
                let pointer = center + Vec2::angled(angle) * (radius * 0.7);
                painter.line_segment(
                    [center, pointer],
                    Stroke::new(self.stroke_width * 1.5, self.line_color),
                );
            }
            KnobStyle::Dot => {
                let dot_pos = center + Vec2::angled(angle) * (radius * 0.7);
                painter.circle_filled(dot_pos, self.stroke_width * 1.5, self.line_color);
            }
        }

        if let Some(label) = self.label {
            let value_string = (self.label_format)(self.value);
            let label_text = if label.is_empty() {
                // If the label is empty, format only the value string
                value_string.to_string()
            } else {
                // If the label is not empty, format with the label, colon, and value string
                format!("{}: {}", label, value_string)
            };
            let font_id = egui::FontId::proportional(self.font_size);

            let (label_pos, alignment) = match self.label_position {
                LabelPosition::Top => (
                    Vec2::new(
                        rect.center().x,
                        rect.min.y - self.label_offset + label_padding,
                    ),
                    Align2::CENTER_TOP,
                ),
                LabelPosition::Bottom => (
                    Vec2::new(rect.center().x, rect.max.y + self.label_offset),
                    Align2::CENTER_BOTTOM,
                ),
                LabelPosition::Left => (
                    Vec2::new(rect.min.x - self.label_offset, rect.center().y),
                    // Might be wrong!
                    Align2::LEFT_CENTER,
                ),
                LabelPosition::Right => (
                    Vec2::new(rect.max.x - label_size.x, rect.center().y),
                    // Fixed this - it was right_center before which caused alignment issues.
                    Align2::LEFT_CENTER,
                ),
            };

            ui.painter().text(
                label_pos.to_pos2(),
                alignment,
                label_text,
                font_id,
                self.text_color,
            );
        }

        if cfg!(feature = "extra_debug") {
            // Draw the bounding rect
            painter.rect_stroke(
                rect,
                0.0,
                Stroke::new(1.0, Color32::RED),
                egui::StrokeKind::Inside,
            );
            painter.rect_stroke(
                knob_rect,
                0.0,
                Stroke::new(1.0, Color32::GREEN),
                egui::StrokeKind::Inside,
            );
        }

        ui.add_space(vertical_margin);

        response
    }
}