ruviz 0.7.0

High-performance 2D plotting library for Rust
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! Style resolution utilities for theme-aware plot styling
//!
//! This module provides [`StyleResolver`], a central utility for resolving
//! styling values with theme fallbacks. It ensures consistent styling across
//! all plot types by providing a single source of truth for style resolution.
//!
//! # Design Philosophy
//!
//! Plot configurations use `Option<T>` for theme-derivable fields where
//! `None` means "use theme default". StyleResolver handles this resolution
//! consistently across all plot types.
//!
//! # Example
//!
//! ```rust,ignore
//! use ruviz::core::style_utils::StyleResolver;
//! use ruviz::render::Theme;
//!
//! let theme = Theme::seaborn();
//! let resolver = StyleResolver::new(&theme);
//!
//! // Use config value if present, otherwise theme default
//! let line_width = resolver.line_width(config.line_width);
//!
//! // Generate edge color from fill color
//! let edge = resolver.edge_color(fill_color, config.edge_color);
//! ```

use crate::core::units::pt_to_px;
use crate::render::{Color, Theme};

/// Central utility for resolving styling values with theme fallbacks
///
/// All methods are `#[inline]` for performance - overhead is negligible (<1μs per call).
#[derive(Debug, Clone, Copy)]
pub struct StyleResolver<'a> {
    theme: &'a Theme,
}

impl<'a> StyleResolver<'a> {
    /// Create a new StyleResolver with the given theme
    pub fn new(theme: &'a Theme) -> Self {
        Self { theme }
    }

    /// Get the underlying theme reference
    #[inline]
    pub fn theme(&self) -> &'a Theme {
        self.theme
    }

    /// Resolve line width, using config override or theme default
    ///
    /// # Arguments
    /// * `config_override` - Explicit line width from config, or None to use theme
    ///
    /// # Returns
    /// The resolved line width in points
    #[inline]
    pub fn line_width(&self, config_override: Option<f32>) -> f32 {
        config_override.unwrap_or(self.theme.line_width)
    }

    /// Resolve fill alpha value
    ///
    /// # Arguments
    /// * `config_override` - Explicit alpha from config, or None to use default
    /// * `default` - Default alpha value when config is None
    ///
    /// # Returns
    /// The resolved alpha value (0.0-1.0)
    #[inline]
    pub fn fill_alpha(&self, config_override: Option<f32>, default: f32) -> f32 {
        config_override.unwrap_or(default).clamp(0.0, 1.0)
    }

    /// Scale font size relative to theme base size
    ///
    /// # Arguments
    /// * `scale` - Scale factor (1.0 = theme.font_size)
    ///
    /// # Returns
    /// The scaled font size in points
    #[inline]
    pub fn font_size(&self, scale: f32) -> f32 {
        self.theme.font_size * scale
    }

    /// Resolve edge color, using explicit value or auto-darkening fill color
    ///
    /// This is the standard method for generating edge colors from fill colors.
    /// When no explicit edge color is provided, generates a 30% darker version
    /// of the fill color (matching matplotlib/seaborn behavior).
    ///
    /// # Arguments
    /// * `fill` - The fill color (used to derive edge if explicit is None)
    /// * `explicit` - Explicit edge color, or None to auto-derive
    ///
    /// # Returns
    /// The resolved edge color
    #[inline]
    pub fn edge_color(&self, fill: Color, explicit: Option<Color>) -> Color {
        explicit.unwrap_or_else(|| fill.darken(0.3))
    }

    /// Resolve a filled patch's edge into the `(colour, width_in_points)` pair
    /// the backends stroke with.
    ///
    /// This is the single place both halves of the edge rule live:
    /// - an `explicit` colour of `None` means "derive from the fill" (see
    ///   [`Self::edge_color`]);
    /// - a non-positive `width` means there is no edge at all, rather than a
    ///   hairline floored to some minimum.
    ///
    /// Bars, histograms, box plots and marker rims all funnel through it, so
    /// the raster, parallel and SVG backends cannot drift apart. The width
    /// stays in **points**; each renderer converts it to device pixels, which
    /// is what makes a patch edge the same physical thickness at every DPI.
    #[inline]
    pub fn patch_edge(
        &self,
        fill: Color,
        explicit: Option<Color>,
        width: f32,
    ) -> Option<(Color, f32)> {
        (width > 0.0).then(|| (self.edge_color(fill, explicit), width))
    }

    /// Resolve edge color with custom darkening factor
    ///
    /// # Arguments
    /// * `fill` - The fill color
    /// * `explicit` - Explicit edge color, or None to auto-derive
    /// * `darken_factor` - How much to darken (0.0-1.0)
    #[inline]
    pub fn edge_color_with_factor(
        &self,
        fill: Color,
        explicit: Option<Color>,
        darken_factor: f32,
    ) -> Color {
        explicit.unwrap_or_else(|| fill.darken(darken_factor))
    }

    /// Get grid line width in points (typically thinner than data lines)
    ///
    /// Returns theme.line_width * 0.5 by default.
    #[inline]
    pub fn grid_line_width(&self) -> f32 {
        self.theme.line_width * 0.5
    }

    /// Get grid line width in device pixels at the given DPI
    ///
    /// Scales [`Self::grid_line_width`] by DPI and then applies a floor of
    /// [`defaults::MIN_GRID_LINE_WIDTH_PX`]. Without the floor, a sub-pixel
    /// stroke at low DPI is spread by the antialiaser across two pixel rows,
    /// halving its effective contrast and making the grid disappear. The floor
    /// is a minimum only - at high DPI the DPI-scaled value wins unchanged.
    #[inline]
    pub fn grid_line_width_px(&self, dpi: f32) -> f32 {
        pt_to_px(self.grid_line_width(), dpi).max(defaults::MIN_GRID_LINE_WIDTH_PX)
    }

    /// Get axis line width
    ///
    /// Returns theme.line_width * 0.5 by default.
    #[inline]
    pub fn axis_line_width(&self) -> f32 {
        self.theme.line_width * 0.5
    }

    /// Get tick line width
    ///
    /// Returns theme.line_width * 0.4 by default.
    #[inline]
    pub fn tick_line_width(&self) -> f32 {
        self.theme.line_width * 0.4
    }

    /// Get edge width for filled shapes (patch.linewidth equivalent)
    ///
    /// Returns 0.8 by default (matplotlib's patch.linewidth).
    #[inline]
    pub fn patch_line_width(&self, config_override: Option<f32>) -> f32 {
        config_override.unwrap_or(0.8)
    }

    /// Resolve a color from the theme palette
    ///
    /// # Arguments
    /// * `explicit` - Explicit color, or None to get from palette
    /// * `series_index` - Index for palette cycling
    #[inline]
    pub fn series_color(&self, explicit: Option<Color>, series_index: usize) -> Color {
        explicit.unwrap_or_else(|| self.theme.get_color(series_index))
    }

    /// Get marker size
    ///
    /// # Arguments
    /// * `config_override` - Explicit marker size, or None for default
    ///
    /// # Returns
    /// Marker size in points (default: 6.0, matching matplotlib)
    #[inline]
    pub fn marker_size(&self, config_override: Option<f32>) -> f32 {
        config_override.unwrap_or(6.0)
    }

    /// Get tick label font size from theme
    #[inline]
    pub fn tick_label_font_size(&self) -> f32 {
        self.theme.tick_label_font_size
    }

    /// Get axis label font size from theme
    #[inline]
    pub fn axis_label_font_size(&self) -> f32 {
        self.theme.axis_label_font_size
    }

    /// Get foreground color from theme (for text, axes, etc.)
    #[inline]
    pub fn foreground(&self) -> Color {
        self.theme.foreground
    }

    /// Get background color from theme
    #[inline]
    pub fn background(&self) -> Color {
        self.theme.background
    }

    /// Get grid color from theme
    #[inline]
    pub fn grid_color(&self) -> Color {
        self.theme.grid_color
    }
}

/// Default fill alpha values matching matplotlib/seaborn
pub mod defaults {
    /// Default fill alpha for violin plots (seaborn: 0.6)
    pub const VIOLIN_FILL_ALPHA: f32 = 0.6;

    /// Default fill alpha for box plots (matplotlib: 0.7)
    pub const BOXPLOT_FILL_ALPHA: f32 = 0.7;

    /// Default fill alpha for histograms (matplotlib: 1.0)
    pub const HISTOGRAM_FILL_ALPHA: f32 = 1.0;

    /// Default fill alpha for KDE fill (seaborn: 0.3)
    pub const KDE_FILL_ALPHA: f32 = 0.3;

    /// Default fill alpha for bar charts (matplotlib: 1.0)
    pub const BAR_FILL_ALPHA: f32 = 1.0;

    /// Default edge width (patch.linewidth in matplotlib: 0.8)
    pub const PATCH_LINE_WIDTH: f32 = 0.8;

    /// Default bar width for histograms (0-1 range)
    pub const HISTOGRAM_BAR_WIDTH: f32 = 0.9;

    /// Default box width ratio for box plots
    pub const BOXPLOT_WIDTH_RATIO: f32 = 0.5;

    /// Default cap width as fraction of box width
    pub const BOXPLOT_CAP_WIDTH: f32 = 0.5;

    /// Default flier (outlier) marker size
    pub const FLIER_SIZE: f32 = 6.0;

    /// Default rug height as fraction of plot height
    pub const RUG_HEIGHT: f32 = 0.05;

    /// Default rug alpha
    pub const RUG_ALPHA: f32 = 0.5;

    /// Minimum grid stroke width in device pixels
    ///
    /// A grid line narrower than one device pixel gets antialiased into a
    /// washed-out grey band, which is what made the default grid unreadable.
    pub const MIN_GRID_LINE_WIDTH_PX: f32 = 1.0;
}

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

    #[test]
    fn test_style_resolver_creation() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);
        assert_eq!(resolver.theme().line_width, theme.line_width);
    }

    #[test]
    fn test_line_width_override() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);

        // With override
        assert_eq!(resolver.line_width(Some(2.5)), 2.5);

        // Without override (use theme default)
        assert_eq!(resolver.line_width(None), theme.line_width);
    }

    #[test]
    fn test_fill_alpha() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);

        // With override
        assert_eq!(resolver.fill_alpha(Some(0.5), 1.0), 0.5);

        // Without override
        assert_eq!(resolver.fill_alpha(None, 0.7), 0.7);

        // Clamping
        assert_eq!(resolver.fill_alpha(Some(1.5), 1.0), 1.0);
        assert_eq!(resolver.fill_alpha(Some(-0.5), 1.0), 0.0);
    }

    #[test]
    fn test_font_size_scaling() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);

        assert_eq!(resolver.font_size(1.0), theme.font_size);
        assert_eq!(resolver.font_size(1.4), theme.font_size * 1.4);
        assert_eq!(resolver.font_size(0.8), theme.font_size * 0.8);
    }

    #[test]
    fn test_edge_color_explicit() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);

        let fill = Color::BLUE;
        let explicit = Color::RED;

        // With explicit color
        assert_eq!(resolver.edge_color(fill, Some(explicit)), explicit);
    }

    #[test]
    fn test_edge_color_auto_darken() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);

        let fill = Color::from_rgb(100, 150, 200);

        // Auto-derived (30% darker)
        let edge = resolver.edge_color(fill, None);
        assert_eq!(edge.r, 70); // 100 * 0.7
        assert_eq!(edge.g, 105); // 150 * 0.7
        assert_eq!(edge.b, 140); // 200 * 0.7
    }

    #[test]
    fn test_edge_color_custom_factor() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);

        let fill = Color::from_rgb(100, 150, 200);

        // 50% darker
        let edge = resolver.edge_color_with_factor(fill, None, 0.5);
        assert_eq!(edge.r, 50); // 100 * 0.5
        assert_eq!(edge.g, 75); // 150 * 0.5
        assert_eq!(edge.b, 100); // 200 * 0.5
    }

    #[test]
    fn test_grid_and_axis_widths() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);

        assert_eq!(resolver.grid_line_width(), theme.line_width * 0.5);
        assert_eq!(resolver.axis_line_width(), theme.line_width * 0.5);
        assert_eq!(resolver.tick_line_width(), theme.line_width * 0.4);
    }

    #[test]
    fn test_grid_line_width_px_floors_at_one_device_pixel() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);

        // 1.5pt theme line width -> 0.75pt grid, which is sub-pixel below 96 DPI
        assert!(pt_to_px(resolver.grid_line_width(), 72.0) < 1.0);
        assert_eq!(
            resolver.grid_line_width_px(72.0),
            defaults::MIN_GRID_LINE_WIDTH_PX
        );
    }

    #[test]
    fn test_grid_line_width_px_still_scales_with_dpi() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);

        // Above the floor the DPI-scaled value is used verbatim
        for dpi in [100.0_f32, 150.0, 300.0] {
            let expected = pt_to_px(resolver.grid_line_width(), dpi);
            assert!(expected > defaults::MIN_GRID_LINE_WIDTH_PX);
            assert!((resolver.grid_line_width_px(dpi) - expected).abs() < 1e-6);
        }

        // And it is monotonic in DPI
        assert!(resolver.grid_line_width_px(300.0) > resolver.grid_line_width_px(100.0));
    }

    #[test]
    fn test_patch_line_width() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);

        // Default is 0.8 (matplotlib patch.linewidth)
        assert_eq!(resolver.patch_line_width(None), 0.8);

        // With override
        assert_eq!(resolver.patch_line_width(Some(1.5)), 1.5);
    }

    #[test]
    fn test_series_color() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);

        // With explicit color
        assert_eq!(resolver.series_color(Some(Color::RED), 0), Color::RED);

        // From palette
        assert_eq!(resolver.series_color(None, 0), theme.get_color(0));
        assert_eq!(resolver.series_color(None, 1), theme.get_color(1));
    }

    #[test]
    fn test_marker_size() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);

        // Default is 6.0 (matplotlib default)
        assert_eq!(resolver.marker_size(None), 6.0);

        // With override
        assert_eq!(resolver.marker_size(Some(10.0)), 10.0);
    }

    #[test]
    fn test_theme_colors() {
        let theme = Theme::dark();
        let resolver = StyleResolver::new(&theme);

        assert_eq!(resolver.foreground(), theme.foreground);
        assert_eq!(resolver.background(), theme.background);
        assert_eq!(resolver.grid_color(), theme.grid_color);
    }

    #[test]
    fn test_different_themes() {
        // Light theme
        let light = Theme::light();
        let light_resolver = StyleResolver::new(&light);

        // Dark theme
        let dark = Theme::dark();
        let dark_resolver = StyleResolver::new(&dark);

        // Presentation theme (larger line widths)
        let presentation = Theme::presentation();
        let presentation_resolver = StyleResolver::new(&presentation);

        // Line widths should differ
        assert!(presentation_resolver.line_width(None) > light_resolver.line_width(None));

        // Colors should differ
        assert_ne!(light_resolver.background(), dark_resolver.background());
    }

    #[test]
    fn test_patch_edge_derives_its_colour_from_the_fill() {
        let theme = Theme::light();
        assert_eq!(
            StyleResolver::new(&theme).patch_edge(Color::BLUE, None, 0.8),
            Some((Color::BLUE.darken(0.3), 0.8)),
            "an unset edge colour must darken the fill"
        );
    }

    #[test]
    fn test_patch_edge_keeps_an_explicit_colour() {
        let theme = Theme::light();
        assert_eq!(
            StyleResolver::new(&theme).patch_edge(Color::BLUE, Some(Color::RED), 1.5),
            Some((Color::RED, 1.5)),
            "an explicit edge colour must survive untouched"
        );
    }

    #[test]
    fn test_patch_edge_of_non_positive_width_is_no_edge() {
        let theme = Theme::light();
        let resolver = StyleResolver::new(&theme);
        assert_eq!(
            resolver.patch_edge(Color::BLUE, Some(Color::RED), 0.0),
            None,
            "a zero width must switch the edge off, not floor it to a hairline"
        );
        assert_eq!(resolver.patch_edge(Color::BLUE, None, -1.0), None);
    }
}