rust_widgets 2.7.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! AudioVisualizer widget — real-time audio waveform/spectrum visualization.
//!
//! Displays vertical bars representing audio frequency bands or waveform samples.
//! Supports mirror mode (bottom half mirrors top), peak hold indicators, and
//! configurable bar count and spacing.

use crate::core::{Color, Rect};
use crate::event::{Event, EventHandler};
use crate::impl_widget_property_hooks;
use crate::property_names_of;
use crate::render::RenderContext;
use crate::widget::capability::coercion::expect_usize;
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};

/// Audio waveform/spectrum visualization widget.
///
/// Renders vertical bars representing audio samples (normalized -1.0 to 1.0).
/// Supports mirroring, peak hold, and configurable appearance.
pub struct AudioVisualizer {
    base: BaseWidget,
    /// Audio sample data normalized to -1.0 to 1.0.
    samples: Vec<f32>,
    /// Number of vertical bars to display.
    bar_count: usize,
    /// Spacing between bars in pixels.
    bar_spacing: f32,
    /// Color of the bars.
    bar_color: Color,
    /// Background color of the visualization area, when the caller has chosen one.
    ///
    /// `None` means "use the active theme's surface", which is what a visualizer drawn on a themed
    /// page wants. It used to be a **fixed** `rgb(20, 20, 30)` initialised in `new()`, so the
    /// control painted a near-black rectangle on the light appearance as well and the
    /// `style.background_color` that `apply_active_theme` wrote was read by nobody — a declared
    /// value with no consumer. Keeping it `Option` is what lets "the caller set one" and "the
    /// theme supplies one" be told apart, the same distinction `WidgetStyle::theme_derived`
    /// records for the base style.
    background_color: Option<Color>,
    /// Whether to mirror the visualization (bottom half mirrors top).
    mirror: bool,
    /// Whether to show peak hold markers.
    peak_hold: bool,
    /// Duration in ms to hold peak values.
    peak_hold_duration: u64,
    /// Current peak hold values for each bar.
    peak_values: Vec<f32>,
}

impl AudioVisualizer {
    /// Creates a new AudioVisualizer widget with the given geometry.
    pub fn new(geometry: Rect) -> Self {
        let bar_count = 64;
        Self {
            base: BaseWidget::new(WidgetKind::AudioVisualizer, geometry, "AudioVisualizer"),
            samples: Vec::new(),
            bar_count,
            bar_spacing: 2.0,
            bar_color: Color::rgba(0, 150, 255, 255),
            background_color: None,
            mirror: false,
            peak_hold: false,
            peak_hold_duration: 500,
            peak_values: vec![0.0; bar_count],
        }
    }

    /// Sets the audio sample data. Values should be normalized to -1.0 to 1.0.
    pub fn set_samples(&mut self, data: Vec<f32>) {
        self.samples = data;
        self.base.request_redraw();
    }

    /// Adds a single audio sample. Useful for streaming data.
    pub fn add_sample(&mut self, value: f32) {
        self.samples.push(value.clamp(-1.0, 1.0));
        self.base.request_redraw();
    }

    /// Clears all audio samples.
    pub fn clear_samples(&mut self) {
        self.samples.clear();
        self.base.request_redraw();
    }

    /// Returns a reference to the current samples.
    pub fn samples(&self) -> &[f32] {
        &self.samples
    }

    /// Sets the number of vertical bars to display.
    pub fn set_bar_count(&mut self, n: usize) {
        self.bar_count = n.max(1);
        self.peak_values.resize(self.bar_count, 0.0);
        self.base.request_redraw();
    }

    /// Returns the current bar count.
    pub fn bar_count(&self) -> usize {
        self.bar_count
    }

    /// Sets the spacing between bars in pixels.
    pub fn set_bar_spacing(&mut self, spacing: f32) {
        self.bar_spacing = spacing.max(0.0);
        self.base.request_redraw();
    }

    /// Returns the current bar spacing.
    pub fn bar_spacing(&self) -> f32 {
        self.bar_spacing
    }

    /// Sets the color of the bars.
    pub fn set_bar_color(&mut self, color: Color) {
        self.bar_color = color;
        self.base.request_redraw();
    }

    /// Returns the current bar color.
    pub fn bar_color(&self) -> Color {
        self.bar_color
    }

    /// Sets the background color of the visualization area.
    pub fn set_background_color(&mut self, color: Color) {
        self.background_color = Some(color);
        self.base.request_redraw();
    }

    /// Returns the background color the visualizer will paint.
    ///
    /// An explicit [`Self::set_background_color`] wins; otherwise this is the active theme's
    /// surface, so the control sits on the page rather than on a fixed near-black. The final
    /// fallback covers a build with no theme at all.
    pub fn background_color(&self) -> Color {
        self.resolved_background()
    }

    /// The fill the draw path should use: the caller's colour, else the theme's surface.
    fn resolved_background(&self) -> Color {
        if let Some(chosen) = self.background_color {
            return chosen;
        }
        // A visualizer's panel is a **surface one step above the page**, the same role
        // `font_preview` and the popup panels use. The theme guard is released before returning.
        let themed = crate::style::theme_manager()
            .current_theme()
            .map(|active| active.colors.surface_container);
        themed.unwrap_or(Color::rgba(20, 20, 30, 255))
    }

    /// Enables or disables mirror mode. When enabled, the bottom half mirrors the top.
    pub fn set_mirror(&mut self, mirror: bool) {
        self.mirror = mirror;
        self.base.request_redraw();
    }

    /// Returns whether mirror mode is enabled.
    pub fn is_mirror_enabled(&self) -> bool {
        self.mirror
    }

    /// Enables or disables peak hold indicators.
    pub fn set_peak_hold(&mut self, enabled: bool) {
        self.peak_hold = enabled;
        self.base.request_redraw();
    }

    /// Returns whether peak hold is enabled.
    pub fn is_peak_hold_enabled(&self) -> bool {
        self.peak_hold
    }

    /// Sets the peak hold duration in milliseconds.
    pub fn set_peak_hold_duration(&mut self, ms: u64) {
        self.peak_hold_duration = ms;
    }

    /// Returns the peak hold duration in milliseconds.
    pub fn peak_hold_duration(&self) -> u64 {
        self.peak_hold_duration
    }
}

impl Widget for AudioVisualizer {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> crate::core::Size {
        crate::core::Size::new(200, 60)
    }

    /// Reports this widget as the object that paints it.
    ///
    /// `AudioVisualizer` implements `Draw`, so `Some(self)` is total and cannot be wrong.
    fn as_draw_mut(&mut self) -> Option<&mut dyn crate::widget::Draw> {
        Some(self)
    }

    impl_widget_property_hooks!();
}

/// `AudioVisualizer`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_media.in.rs` / `access_write_media.in.rs` dispatch: `bar_count`
/// is published as an unsigned integer and clamped to at least one bar on write.
impl WidgetProperties for AudioVisualizer {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "bar_count" => Ok(CapabilityValue::UInt(self.bar_count() as u64)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "bar_count" => {
                self.set_bar_count(expect_usize(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["bar_count", BASE_PROPERTY_NAMES]
    }
}

impl Draw for AudioVisualizer {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        let w = rect.width as f32;
        let h = rect.height as f32;

        if w <= 0.0 || h <= 0.0 {
            return;
        }

        // Draw background
        context.fill_rect(rect, self.resolved_background());

        // Calculate bar layout
        let total_spacing = self.bar_spacing * (self.bar_count as f32 + 1.0);
        let bar_width = ((w - total_spacing) / self.bar_count as f32).max(1.0);
        let center_y = rect.y as f32 + h / 2.0;
        let half_height = h / 2.0 - 2.0;

        // Prepare sample data: downsample to bar_count
        let bars: Vec<f32> = if self.samples.is_empty() {
            // Generate some test data when no samples are provided
            (0..self.bar_count)
                .map(|i| {
                    let t = i as f32 / self.bar_count as f32;
                    (t * std::f32::consts::PI * 4.0).sin().abs() * 0.6 + 0.1
                })
                .collect()
        } else {
            let step = (self.samples.len() as f32 / self.bar_count as f32).max(1.0);
            (0..self.bar_count)
                .map(|i| {
                    let start = (i as f32 * step) as usize;
                    let end = ((i as f32 + 1.0) * step) as usize;
                    let end = end.min(self.samples.len());
                    if start < end {
                        let chunk = &self.samples[start..end];
                        let sum: f32 = chunk.iter().map(|v| v.abs()).sum();
                        (sum / chunk.len() as f32).min(1.0)
                    } else {
                        0.0
                    }
                })
                .collect()
        };

        for (i, &value) in bars.iter().enumerate() {
            let value = value.min(1.0);
            let bar_height = (value * half_height).max(1.0);
            let x = rect.x as f32 + self.bar_spacing + i as f32 * (bar_width + self.bar_spacing);
            let bar_rect = Rect::new(
                x as i32,
                (center_y - bar_height) as i32,
                bar_width as u32,
                (bar_height * 2.0) as u32,
            );

            // Color gradient based on amplitude
            let intensity = (value * 255.0) as u8;
            let bar_color = if value > 0.7 {
                Color::rgba(255, intensity, intensity, 255)
            } else if value > 0.4 {
                Color::rgba(intensity, 200, 255, 255)
            } else {
                Color::rgba(intensity / 2, intensity / 2, 200, 255)
            };

            if self.mirror {
                // Draw only top half-bar and mirror it
                let top_bar = Rect::new(
                    x as i32,
                    (center_y - bar_height) as i32,
                    bar_width as u32,
                    bar_height as u32,
                );
                let bottom_bar =
                    Rect::new(x as i32, center_y as i32, bar_width as u32, bar_height as u32);
                context.fill_rect(top_bar, bar_color);
                context.fill_rect(bottom_bar, bar_color);
            } else {
                context.fill_rect(bar_rect, bar_color);
            }

            // Peak hold indicator
            if self.peak_hold {
                let peak_value = self.peak_values[i];
                if value > peak_value {
                    self.peak_values[i] = value;
                }
                if self.peak_values[i] > 0.0 {
                    let peak_y = center_y - self.peak_values[i] * half_height;
                    let peak_rect = Rect::new(
                        x as i32,
                        peak_y as i32,
                        bar_width as u32,
                        std::cmp::max(1, (bar_width * 0.5) as u32),
                    );
                    context.fill_rect(peak_rect, Color::rgba(255, 255, 100, 255));
                }
            }
        }
    }
}

impl EventHandler for AudioVisualizer {
    /// Toggles peak-hold on a press that lands on the visualizer.
    ///
    /// The position used to be discarded, so a press on any other control in the same
    /// window flipped this one's peak-hold. The duplicate `MousePress` arm below it —
    /// an empty body for any non-left button — was dead weight and is gone with it.
    fn handle_event(&mut self, event: &Event) {
        if !self.base.is_enabled() {
            return;
        }
        match event {
            Event::MousePress { pos, button }
                if *button == 1 && self.geometry().contains_point(*pos) =>
            {
                self.peak_hold = !self.peak_hold;
                self.base.request_redraw();
            }
            _ => {
                self.base.handle_event(event);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn audio_visualizer_default_state() {
        let av = AudioVisualizer::new(Rect::new(0, 0, 300, 150));
        assert_eq!(av.bar_count(), 64);
        assert!(av.samples().is_empty());
        assert!(!av.is_mirror_enabled());
        assert!(!av.is_peak_hold_enabled());
        assert_eq!(av.kind(), WidgetKind::AudioVisualizer);
    }

    #[test]
    fn audio_visualizer_set_samples() {
        let mut av = AudioVisualizer::new(Rect::new(0, 0, 300, 150));
        let data = vec![0.0, 0.5, 1.0, -0.5, 0.0];
        av.set_samples(data.clone());
        assert_eq!(av.samples(), &data);
    }

    #[test]
    fn audio_visualizer_add_and_clear_samples() {
        let mut av = AudioVisualizer::new(Rect::new(0, 0, 300, 150));
        av.add_sample(0.5);
        av.add_sample(-0.3);
        av.add_sample(0.8);
        assert_eq!(av.samples().len(), 3);
        av.clear_samples();
        assert!(av.samples().is_empty());
    }

    #[test]
    fn audio_visualizer_set_bar_count() {
        let mut av = AudioVisualizer::new(Rect::new(0, 0, 300, 150));
        av.set_bar_count(32);
        assert_eq!(av.bar_count(), 32);
        av.set_bar_count(0); // Should clamp to 1
        assert_eq!(av.bar_count(), 1);
    }

    #[test]
    fn audio_visualizer_toggle_mirror_and_peak_hold() {
        let mut av = AudioVisualizer::new(Rect::new(0, 0, 300, 150));
        assert!(!av.is_mirror_enabled());
        av.set_mirror(true);
        assert!(av.is_mirror_enabled());
        assert!(!av.is_peak_hold_enabled());
        av.set_peak_hold(true);
        assert!(av.is_peak_hold_enabled());
    }

    #[test]
    fn audio_visualizer_bar_spacing() {
        let mut av = AudioVisualizer::new(Rect::new(0, 0, 300, 150));
        assert!((av.bar_spacing() - 2.0).abs() < f32::EPSILON);
        av.set_bar_spacing(5.0);
        assert!((av.bar_spacing() - 5.0).abs() < f32::EPSILON);
    }

    /// The panel colour is the theme's surface unless the caller chose one.
    ///
    /// # The defect this pins
    ///
    /// `new()` initialised `background_color` to a fixed `rgb(20, 20, 30)` and `draw` read that
    /// field directly, so the visualizer painted a near-black rectangle on the light appearance too,
    /// and the `style.background_color` that `apply_active_theme` wrote was read by **nobody** — a
    /// declared value with no consumer. It now resolves to `surface_container` unless
    /// `set_background_color` was called, which is what the `Option` field distinguishes.
    #[test]
    #[cfg(all(device_profile, feature = "desktop"))]
    fn the_background_defaults_to_the_theme_and_still_honours_an_override() {
        let _guard = crate::style::theme_test_guard();
        crate::widget::census::install_preset_appearances();

        let themed = |appearance| -> Color {
            crate::theme::global_theme_manager().set_appearance(appearance);
            AudioVisualizer::new(Rect::new(0, 0, 300, 150)).background_color()
        };

        let dark = themed(crate::theme::AppearanceMode::Dark);
        let light = themed(crate::theme::AppearanceMode::Light);
        assert_ne!(
            dark, light,
            "an un-configured visualizer must take the theme's surface, not a fixed near-black; \
             both were {dark:?}"
        );

        // An explicit choice still wins over the theme, which is what keeps the setter meaningful.
        crate::theme::global_theme_manager().set_appearance(crate::theme::AppearanceMode::Light);
        let mut av = AudioVisualizer::new(Rect::new(0, 0, 300, 150));
        let chosen = Color::rgb(1, 2, 3);
        av.set_background_color(chosen);
        assert_eq!(av.background_color(), chosen, "a caller's colour must survive the theme");
    }
}