iced_audio 0.14.0

An extension to the Iced GUI library with useful widgets for audio applications
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use std::time::{Duration, Instant};

use iced_core::{
    Event, Shell, keyboard, mouse, touch,
    window::{self, RedrawRequest},
};

use super::{Normal, NormalParam};

pub const DEFAULT_SCALAR: f32 = 0.00385;
pub const DEFAULT_WHEEL_SCALAR: f32 = 0.01;
pub const DEFAULT_MODIFIER_SCALAR: f32 = 0.02;
pub const DEFAULT_SCROLL_WHEEL_TIMEOUT_SECS: f32 = 0.25;

/// The configuration of a [`VirtualSlider`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Config {
    /// A scalar which adjusts how fast the [`Normal`] value will change for each logical
    /// pixel the mouse moves.
    ///
    /// The default value is `0.00385`
    pub drag_scalar: f32,

    /// A scalar which adjusts how fast the [`Normal`] value will change for each line
    /// scrolled by the mouse wheel.
    ///
    /// This can be set to `0.0` to disable the scroll wheel from moving the parameter.
    ///
    /// The default value is `0.01`
    pub wheel_scalar: f32,

    /// A scalar applied to the movement speed of the virtual slider when the user drags
    /// the knobs while holding down the fine tune modifier key.
    ///
    /// For example, a scalar of `0.5` will cause the knob to turn half as fast when the
    /// modifier key is down.
    ///
    /// The default value is `0.02`.
    pub fine_tune_scalar: f32,

    /// The modifier key/keys to use for fine-tune dragging.
    ///
    /// The default key is `Ctrl`.
    pub fine_tune_modifiers: keyboard::Modifiers,

    /// How long to wait (in seconds) after a scroll wheel event to consider the gesture to
    /// be finished.
    ///
    /// Set this to `0.0` to disable the timeout (the gesture end message will be sent
    /// immediately).
    ///
    /// The default is "0.25".
    pub scroll_wheel_timeout_seconds: f32,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            drag_scalar: 0.00385,
            wheel_scalar: 0.01,
            fine_tune_scalar: 0.02,
            fine_tune_modifiers: keyboard::Modifiers::CTRL,
            scroll_wheel_timeout_seconds: DEFAULT_SCROLL_WHEEL_TIMEOUT_SECS,
        }
    }
}

/// The current state of the user gesturing this widget.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Gesture {
    /// The gesture has just started. (i.e. the user has just pressed down on this widget
    /// to begin dragging it).
    ///
    /// This will always be sent before [`Gesture::Gesturing`]/`[`Gesture::GestureEnd`].
    GestureStart,
    /// The user is currently gesturing the widget and this is the new normalized value
    /// of the parameter.
    Gesturing(Normal),
    /// The user has finished gesturing the widget. This will always be sent exactly
    /// once after the last [`Gesture::Gesturing`] was sent and before the next
    /// [`Gesture::GestureStart`] is sent.
    GestureEnd,
}

impl Gesture {
    pub fn new_normal(&self) -> Option<Normal> {
        if let Self::Gesturing(value) = self {
            Some(*value)
        } else {
            None
        }
    }
}

/// The [`State`](iced_core::widget::tree::State) of a [`VirtualSlider`].
pub struct State {
    is_dragging: bool,
    prev_drag_pos: f32,
    prev_normal: Normal,
    continuous_normal: f32,
    pressed_modifiers: keyboard::Modifiers,
    last_click: Option<mouse::Click>,
    last_sent_gesture: Gesture,
    last_scroll_wheel_gesture_instant: Option<Instant>,
    hovered: bool,
    enabled: bool,
}

impl State {
    pub fn new(param_normal: Normal, enabled: bool) -> Self {
        Self {
            is_dragging: false,
            prev_drag_pos: 0.0,
            prev_normal: param_normal,
            continuous_normal: param_normal.as_f32(),
            pressed_modifiers: keyboard::Modifiers::NONE,
            last_click: None,
            last_sent_gesture: Gesture::GestureEnd,
            last_scroll_wheel_gesture_instant: None,
            hovered: false,
            enabled,
        }
    }

    pub fn is_gesturing(&self) -> bool {
        self.last_sent_gesture != Gesture::GestureEnd
    }

    pub fn is_dragging(&self) -> bool {
        self.is_dragging
    }

    /// The possible status of a [`VirtualSlider`] widget, used for styling.
    pub fn status(&self) -> Status {
        if !self.enabled {
            Status::Disabled
        } else if self.is_gesturing() {
            Status::Gesturing
        } else if self.hovered {
            Status::Hovered
        } else {
            Status::Idle
        }
    }

    pub fn continuous_normal(&self) -> Normal {
        Normal::new(self.continuous_normal)
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct UpdateStatus {
    pub param_changed: bool,
    pub hover_state_changed: bool,
    pub gesturing_state_changed: bool,
    pub disabled_state_changed: bool,
}

impl UpdateStatus {
    pub fn should_redraw(&self) -> bool {
        self.param_changed
            || self.hover_state_changed
            || self.gesturing_state_changed
            || self.disabled_state_changed
    }
}

/// The possible status of a [`VirtualSlider`] widget, used for styling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Status {
    /// The widget is enabled an idle.
    Idle,
    /// The widget is enabled and is being hovered.
    Hovered,
    /// The widget is enabled and is currently being gestured (dragged).
    Gesturing,
    /// The widget is disabled.
    Disabled,
}

/// The shared input logic for a "virtual slider" widget.
///
/// The input logic for a "virtual slider" works as follows:
/// (TODO)
pub struct VirtualSlider<'a, Message> {
    /// The configuration of this virtual slider.
    pub config: Config,
    on_gesture: Option<Box<dyn 'a + FnMut(Gesture) -> Message>>,

    param: NormalParam,
}

impl<'a, Message> VirtualSlider<'a, Message> {
    pub fn new(normal_param: NormalParam) -> Self {
        Self {
            param: normal_param,
            on_gesture: None,
            config: Config::default(),
        }
    }

    /// Sets the message to emit when the user gestures this widget.
    pub fn set_on_gesture(&mut self, on_gesture: impl 'a + FnMut(Gesture) -> Message) {
        self.on_gesture = Some(Box::new(on_gesture));
    }

    pub fn param(&self) -> &NormalParam {
        &self.param
    }

    /// A method that custom virtual slider widgets can call to implement
    /// virtual slider input logic.
    ///
    /// * `state` - The state of this virtual slider. (Store this in your widget's
    ///   tree state).
    /// * `cursor_is_over` - Whether or not this widget is currently enabled.
    /// * `cursor_is_over` - Whether or not the cursor is currently over the input
    ///   region of this widget. Typically this will be `cursor.is_over(layout.bounds())`,
    ///   but this can be customized to only be a portion of the widget's bounds.
    /// * `drag_horizontally` - If `true`, then the use drags horizontally to modify
    ///   this widget instead of vertically.
    /// * `drag_horizontally` - If `true`, then the speed of dragging/mouse wheel
    ///   scrolling will be halved. This is useful for some widgets such as the modulation
    ///   input range widget.
    /// * `event` - The event passed in to the widget's `update` method.
    /// * `cursor` - The cursor passed in to the widget's `update` method.
    /// * `shell` - The shell passed in to the widget's `update` method.
    #[allow(clippy::too_many_arguments)]
    pub fn update(
        &mut self,
        state: &mut State,
        enabled: bool,
        cursor_is_over: bool,
        drag_horizontally: bool,
        halve_speed: bool,
        event: &Event,
        cursor: mouse::Cursor,
        shell: &mut Shell<'_, Message>,
    ) -> UpdateStatus {
        let mut status = UpdateStatus {
            disabled_state_changed: enabled != state.enabled,
            ..Default::default()
        };

        // Update state if the value was modified outside of the widget.
        if !state.is_dragging && state.prev_normal != self.param.normal {
            status.param_changed = true;
            state.prev_normal = self.param.normal;
            state.continuous_normal = self.param.normal.as_f32();
        }

        state.enabled = enabled;
        if !enabled {
            return status;
        }

        status.hover_state_changed = cursor_is_over != state.hovered;
        state.hovered = cursor_is_over;

        let mut capture_event = false;

        match event {
            Event::Mouse(mouse::Event::CursorMoved { position })
            | Event::Touch(touch::Event::FingerMoved { position, .. }) => {
                if state.is_dragging {
                    let (pos, delta) = if drag_horizontally {
                        (position.x, state.prev_drag_pos - position.x)
                    } else {
                        (position.y, position.y - state.prev_drag_pos)
                    };

                    state.prev_drag_pos = pos;

                    let drag_scalar = if halve_speed {
                        self.config.drag_scalar * 0.5
                    } else {
                        self.config.drag_scalar
                    };

                    self.move_virtual_slider(state, delta * drag_scalar, shell, &mut status);

                    capture_event = true;
                } else if cursor_is_over {
                    capture_event = true;
                }
            }
            Event::Mouse(mouse::Event::WheelScrolled { delta }) => {
                if self.config.wheel_scalar == 0.0 {
                    return status;
                }

                if cursor_is_over {
                    let lines = match delta {
                        mouse::ScrollDelta::Lines { y, .. } => *y,
                        mouse::ScrollDelta::Pixels { y, .. } => {
                            if *y > 0.0 {
                                1.0
                            } else if *y < 0.0 {
                                -1.0
                            } else {
                                0.0
                            }
                        }
                    };

                    if lines != 0.0 {
                        let wheel_scalar = if halve_speed {
                            self.config.wheel_scalar * 0.5
                        } else {
                            self.config.wheel_scalar
                        };

                        let normal_delta = -lines * wheel_scalar;

                        self.move_virtual_slider(state, normal_delta, shell, &mut status);

                        if status.param_changed {
                            if self.config.scroll_wheel_timeout_seconds > 0.0 {
                                let now = Instant::now();
                                let timeout_instant = now
                                    + Duration::from_secs_f32(
                                        self.config.scroll_wheel_timeout_seconds,
                                    );

                                // Wait for the `RedrawRequested` event to send the gesture end message.
                                state.last_scroll_wheel_gesture_instant = Some(timeout_instant);

                                shell.request_redraw_at(RedrawRequest::At(timeout_instant));
                            } else if !state.is_dragging {
                                self.end_gesture(state, shell, &mut status);
                            }
                        }
                    }

                    capture_event = true;
                }
            }
            Event::Window(window::Event::RedrawRequested(now)) => {
                if let Some(timeout_instant) = state.last_scroll_wheel_gesture_instant {
                    if *now >= timeout_instant {
                        self.end_gesture(state, shell, &mut status);
                    } else {
                        shell.request_redraw_at(timeout_instant);
                    }
                }
            }
            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
            | Event::Touch(touch::Event::FingerPressed { .. }) => {
                if cursor_is_over && let Some(cursor_position) = cursor.position() {
                    let click =
                        mouse::Click::new(cursor_position, mouse::Button::Left, state.last_click);

                    match click.kind() {
                        mouse::click::Kind::Single => {
                            state.is_dragging = true;
                            state.prev_drag_pos = if drag_horizontally {
                                cursor_position.x
                            } else {
                                cursor_position.y
                            };

                            if let Gesture::GestureEnd = &state.last_sent_gesture {
                                if let Some(on_gesture) = &mut self.on_gesture {
                                    shell.publish((on_gesture)(Gesture::GestureStart));
                                }
                                state.last_sent_gesture = Gesture::GestureStart;
                            }
                        }
                        _ => {
                            self.set_param_value(
                                self.param.default.as_f32(),
                                state,
                                shell,
                                &mut status,
                            );
                            self.end_gesture(state, shell, &mut status);
                        }
                    }

                    state.last_click = Some(click);

                    capture_event = true;
                }
            }
            Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left))
            | Event::Touch(touch::Event::FingerLifted { .. })
            | Event::Touch(touch::Event::FingerLost { .. }) => {
                self.end_gesture(state, shell, &mut status);
                capture_event = true;
            }
            Event::Window(window::Event::Unfocused) => {
                self.end_gesture(state, shell, &mut status);
            }
            Event::Keyboard(keyboard_event) => match keyboard_event {
                keyboard::Event::KeyPressed { modifiers, .. } => {
                    state.pressed_modifiers = *modifiers;
                    capture_event = true;
                }
                keyboard::Event::KeyReleased { modifiers, .. } => {
                    state.pressed_modifiers = *modifiers;
                    capture_event = true;
                }
                keyboard::Event::ModifiersChanged(modifiers) => {
                    state.pressed_modifiers = *modifiers;
                    capture_event = true;
                }
            },
            _ => {}
        }

        if capture_event {
            shell.capture_event();
        }

        status
    }

    fn move_virtual_slider(
        &mut self,
        state: &mut State,
        mut normal_delta: f32,
        shell: &mut Shell<'_, Message>,
        status: &mut UpdateStatus,
    ) {
        if state
            .pressed_modifiers
            .contains(self.config.fine_tune_modifiers)
        {
            normal_delta *= self.config.fine_tune_scalar;
        }

        self.set_param_value(state.continuous_normal - normal_delta, state, shell, status)
    }

    fn set_param_value(
        &mut self,
        value: f32,
        state: &mut State,
        shell: &mut Shell<'_, Message>,
        status: &mut UpdateStatus,
    ) {
        let prev_value = self.param.normal;
        self.param.normal.set(value);
        state.continuous_normal = self.param.normal.as_f32();

        if (self.param.normal.as_f32() - prev_value.as_f32()).abs() <= f32::EPSILON {
            return;
        }
        status.param_changed = true;

        if let Gesture::GestureEnd = &state.last_sent_gesture {
            // Send a GestureStart message first.
            if let Some(on_gesture) = &mut self.on_gesture {
                shell.publish((on_gesture)(Gesture::GestureStart));
            }
            state.last_sent_gesture = Gesture::GestureStart;
            status.gesturing_state_changed = true;
        }

        if let Some(on_gesture) = &mut self.on_gesture {
            shell.publish((on_gesture)(Gesture::Gesturing(self.param.normal)));
        }
        state.last_sent_gesture = Gesture::Gesturing(self.param.normal);
    }

    fn end_gesture(
        &mut self,
        state: &mut State,
        shell: &mut Shell<'_, Message>,
        status: &mut UpdateStatus,
    ) {
        state.is_dragging = false;
        state.last_scroll_wheel_gesture_instant = None;

        if state.last_sent_gesture == Gesture::GestureEnd {
            return;
        }
        status.gesturing_state_changed = true;

        if let Some(on_gesture) = &mut self.on_gesture {
            shell.publish((on_gesture)(Gesture::GestureEnd));
        }
        state.last_sent_gesture = Gesture::GestureEnd;
    }
}