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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! Pie chart implementation
//!
//! Provides pie and donut chart functionality with labels, percentages, and explode.
//!
//! # Trait-Based API
//!
//! Pie charts implement the core plot traits:
//! - [`PlotConfig`] for `PieConfig`
//! - [`PlotCompute`] for `Pie` marker struct
//! - [`PlotData`] for `PieData`
//! - [`PlotRender`] for `PieData`

use crate::core::Result;
use crate::plots::traits::{PlotArea, PlotCompute, PlotConfig, PlotData, PlotRender};
use crate::render::primitives::{Wedge, pie_wedges};
use crate::render::{Color, SkiaRenderer, Theme};
use std::f64::consts::PI;

/// Inner radius, as a fraction of the outer radius, that makes a pie a donut.
///
/// The one number `Plot::donut` means by "a donut": a hole wide enough to read
/// as one, narrow enough to leave the wedges comparable by angle. Callers who
/// want a different hole say so with [`PieConfig::donut`].
pub const DEFAULT_DONUT_INNER_RADIUS: f64 = 0.4;

/// Configuration for pie chart
#[derive(Debug, Clone)]
pub struct PieConfig {
    /// Labels for each wedge
    pub labels: Vec<String>,
    /// Colors for each wedge (None for auto-colors from palette)
    pub colors: Option<Vec<Color>>,
    /// Explode offset for each wedge (0.0 = no explode)
    pub explode: Vec<f64>,
    /// Show percentage labels
    pub show_percentages: bool,
    /// Show value labels
    pub show_values: bool,
    /// Show labels (category names)
    pub show_labels: bool,
    /// Inner radius for donut chart (0.0 = full pie)
    pub inner_radius: f64,
    /// Start angle in degrees, measured counter-clockwise from 3 o'clock
    /// (0 = 3 o'clock, 90 = 12 o'clock), as in matplotlib
    pub start_angle: f64,
    /// Whether wedges advance counter-clockwise from `start_angle` (matplotlib's default)
    pub counter_clockwise: bool,
    /// Text color for labels
    pub text_color: Color,
    /// Font size for labels
    pub label_font_size: f32,
    /// Distance from center for labels (as fraction of radius)
    pub label_distance: f64,
    /// Shadow offset (0 = no shadow)
    pub shadow: f64,
    /// Edge color for wedges (None for no edge)
    pub edge_color: Option<Color>,
    /// Edge width
    pub edge_width: f32,
}

impl Default for PieConfig {
    fn default() -> Self {
        Self {
            labels: vec![],
            colors: None,
            explode: vec![],
            show_percentages: true,
            show_values: false,
            show_labels: true,
            inner_radius: 0.0,
            start_angle: 90.0, // Start at top (12 o'clock)
            counter_clockwise: true,
            text_color: Color::from_rgb(0, 0, 0),
            label_font_size: 10.0,
            label_distance: 0.6,
            shadow: 0.0,
            edge_color: Some(Color::from_rgb(255, 255, 255)),
            edge_width: 1.0,
        }
    }
}

impl PieConfig {
    /// Create a new pie config with labels
    pub fn new(labels: Vec<String>) -> Self {
        Self {
            labels,
            ..Default::default()
        }
    }

    /// Set colors for wedges
    pub fn colors(mut self, colors: Vec<Color>) -> Self {
        self.colors = Some(colors);
        self
    }

    /// Set explode offsets for wedges
    pub fn explode(mut self, explode: Vec<f64>) -> Self {
        self.explode = explode;
        self
    }

    /// Create a donut chart with inner radius
    ///
    /// See [`DEFAULT_DONUT_INNER_RADIUS`] for the ratio `Plot::donut` uses.
    pub fn donut(mut self, inner_radius: f64) -> Self {
        self.inner_radius = inner_radius.clamp(0.0, 0.95);
        self
    }

    /// Set start angle in degrees
    pub fn start_angle(mut self, angle: f64) -> Self {
        self.start_angle = angle;
        self
    }

    /// Go clockwise instead of counter-clockwise
    pub fn clockwise(mut self) -> Self {
        self.counter_clockwise = false;
        self
    }

    /// Show/hide percentage labels
    pub fn percentages(mut self, show: bool) -> Self {
        self.show_percentages = show;
        self
    }

    /// Show/hide value labels
    pub fn values(mut self, show: bool) -> Self {
        self.show_values = show;
        self
    }

    /// Show/hide category labels
    pub fn labels(mut self, show: bool) -> Self {
        self.show_labels = show;
        self
    }

    /// Set label font size
    pub fn font_size(mut self, size: f32) -> Self {
        self.label_font_size = size;
        self
    }

    /// Set label distance from center
    pub fn label_distance(mut self, distance: f64) -> Self {
        self.label_distance = distance;
        self
    }

    /// Set edge color
    pub fn edge_color(mut self, color: Color) -> Self {
        self.edge_color = Some(color);
        self
    }

    /// Remove edge
    pub fn no_edge(mut self) -> Self {
        self.edge_color = None;
        self
    }
}

// Implement PlotConfig marker trait
impl PlotConfig for PieConfig {}

/// Marker struct for Pie plot type
pub struct Pie;

/// Pie chart data and computed wedges
#[derive(Debug, Clone)]
pub struct PieData {
    /// Original values
    pub values: Vec<f64>,
    /// Computed wedges
    pub wedges: Vec<Wedge>,
    /// Total sum of values
    pub total: f64,
    /// Percentages for each wedge
    pub percentages: Vec<f64>,
    /// Start angles for each wedge (radians)
    pub start_angles: Vec<f64>,
    /// End angles for each wedge (radians)
    pub end_angles: Vec<f64>,
    /// Configuration used
    pub(crate) config: PieConfig,
}

impl PieData {
    /// Create pie data from values
    pub fn from_values(values: &[f64], cx: f64, cy: f64, radius: f64, config: &PieConfig) -> Self {
        let kept: Vec<usize> = values
            .iter()
            .enumerate()
            .filter(|&(_, &v)| v > 0.0)
            .map(|(index, _)| index)
            .collect();
        let positive_values: Vec<f64> = kept.iter().map(|&index| values[index]).collect();
        let total: f64 = positive_values.iter().sum();

        // Per-value vectors the caller supplied are indexed by wedge, so they have
        // to be filtered alongside the values: otherwise every entry after a
        // dropped value binds to the wrong wedge.
        let config = filter_per_value_config(config, &kept, values.len());

        let percentages: Vec<f64> = if total > 0.0 {
            positive_values.iter().map(|v| v / total * 100.0).collect()
        } else {
            vec![0.0; positive_values.len()]
        };

        // Wedge angles live in screen space, where +y points down, so a positive
        // sweep advances clockwise. `start_angle` is measured counter-clockwise
        // from 3 o'clock (matplotlib's convention), hence the negation: the
        // default of 90° starts at 12 o'clock.
        let start_angle_rad = -config.start_angle.to_radians();

        let mut wedges = pie_wedges(&positive_values, cx, cy, radius, Some(start_angle_rad));

        // `pie_wedges` always sweeps clockwise on screen. Mirroring each wedge
        // about the start angle keeps the wedge order but sweeps the other way.
        if config.counter_clockwise {
            for wedge in &mut wedges {
                let (start, end) = (wedge.start_angle, wedge.end_angle);
                wedge.start_angle = 2.0 * start_angle_rad - end;
                wedge.end_angle = 2.0 * start_angle_rad - start;
            }
        }

        // Compute normalized angles
        let mut start_angles = Vec::with_capacity(wedges.len());
        let mut end_angles = Vec::with_capacity(wedges.len());

        // Apply configuration to wedges
        for (i, wedge) in wedges.iter_mut().enumerate() {
            start_angles.push(wedge.start_angle);
            end_angles.push(wedge.end_angle);

            // Apply inner radius for donut
            if config.inner_radius > 0.0 {
                *wedge = wedge.inner_radius(radius * config.inner_radius);
            }

            // Apply explode
            if i < config.explode.len() && config.explode[i] > 0.0 {
                *wedge = wedge.explode(config.explode[i] * radius * 0.1);
            }
        }

        Self {
            values: positive_values,
            wedges,
            total,
            percentages,
            start_angles,
            end_angles,
            config,
        }
    }

    /// Create normalized pie data (without specific coordinates)
    /// Used by PlotCompute trait
    pub fn compute(values: &[f64], config: &PieConfig) -> Self {
        // Use unit circle coordinates for normalized computation
        Self::from_values(values, 0.5, 0.5, 0.5, config)
    }
}

/// Drop the entries of the per-value config vectors whose value was filtered out.
///
/// `kept` holds the indices of the values that became wedges. Labels and explode
/// offsets are read with a bounds check, so a short vector filters cleanly; colors
/// wrap modulo their length, so they are only realigned when the caller supplied
/// exactly one per value.
fn filter_per_value_config(config: &PieConfig, kept: &[usize], value_count: usize) -> PieConfig {
    let mut filtered = config.clone();
    if kept.len() == value_count {
        return filtered;
    }

    filtered.labels = kept
        .iter()
        .filter_map(|&index| config.labels.get(index).cloned())
        .collect();
    filtered.explode = kept
        .iter()
        .filter_map(|&index| config.explode.get(index).copied())
        .collect();
    if let Some(colors) = config.colors.as_ref().filter(|c| c.len() == value_count) {
        filtered.colors = Some(kept.iter().map(|&index| colors[index]).collect());
    }

    filtered
}

/// Render a pie chart
///
/// # Arguments
/// * `renderer` - The Skia renderer
/// * `values` - Numeric values for each wedge
/// * `cx` - Center X coordinate
/// * `cy` - Center Y coordinate
/// * `radius` - Outer radius
/// * `config` - Pie chart configuration
/// * `theme` - Color theme
///
/// # Returns
/// Result with PieData containing computed wedges
pub fn render_pie(
    renderer: &mut SkiaRenderer,
    values: &[f64],
    cx: f64,
    cy: f64,
    radius: f64,
    config: &PieConfig,
    theme: &Theme,
) -> crate::core::Result<PieData> {
    let pie_data = PieData::from_values(values, cx, cy, radius, config);

    if pie_data.wedges.is_empty() {
        return Ok(pie_data);
    }

    // Use the resolved config: its per-wedge vectors are aligned with the wedges,
    // which the caller's are not once a non-positive value has been dropped.
    let config = &pie_data.config;

    // Get colors from config or theme palette
    let colors = if let Some(ref colors) = config.colors {
        colors.clone()
    } else {
        let palette = theme.color_palette.clone();
        (0..pie_data.wedges.len())
            .map(|i| palette[i % palette.len()])
            .collect()
    };

    // Number of segments per arc for smooth curves
    let segments = 64;

    let render_scale = renderer.render_scale();
    let edge_width_px = render_scale.points_to_pixels(config.edge_width);
    let label_font_size_px = render_scale.points_to_pixels(config.label_font_size);
    let shadow_offset_px = render_scale.points_to_pixels(config.shadow as f32) as f64;

    // Draw shadow if configured
    if config.shadow > 0.0 {
        let shadow_color = Color::from_rgb(100, 100, 100).with_alpha(0.3);
        for wedge in &pie_data.wedges {
            let mut shadow_wedge = *wedge;
            // Offset shadow
            let polygon = shadow_wedge.as_polygon(segments);
            let shadow_polygon: Vec<(f32, f32)> = polygon
                .iter()
                .map(|(x, y)| {
                    (
                        (*x + shadow_offset_px) as f32,
                        (*y + shadow_offset_px) as f32,
                    )
                })
                .collect();
            renderer.draw_filled_polygon(&shadow_polygon, shadow_color)?;
        }
    }

    // Draw wedges
    for (i, wedge) in pie_data.wedges.iter().enumerate() {
        let color = colors[i % colors.len()];
        let polygon = wedge.as_polygon(segments);
        let polygon_f32: Vec<(f32, f32)> = polygon
            .iter()
            .map(|(x, y)| (*x as f32, *y as f32))
            .collect();

        // Draw filled wedge
        renderer.draw_filled_polygon(&polygon_f32, color)?;

        // Draw edge if configured
        if let Some(edge_color) = config.edge_color {
            renderer.draw_polygon_outline(&polygon_f32, edge_color, edge_width_px)?;
        }
    }

    // Draw labels
    if config.show_labels || config.show_percentages || config.show_values {
        for (i, wedge) in pie_data.wedges.iter().enumerate() {
            let label_parts: Vec<String> = [
                if config.show_labels && i < config.labels.len() {
                    Some(config.labels[i].clone())
                } else {
                    None
                },
                if config.show_percentages {
                    Some(format!("{:.1}%", pie_data.percentages[i]))
                } else {
                    None
                },
                if config.show_values {
                    Some(format!("{:.1}", pie_data.values[i]))
                } else {
                    None
                },
            ]
            .into_iter()
            .flatten()
            .collect();

            if !label_parts.is_empty() {
                let label = label_parts.join("\n");

                // Calculate label position
                let label_r = if config.inner_radius > 0.0 {
                    radius * (1.0 + config.inner_radius) / 2.0 * config.label_distance
                } else {
                    radius * config.label_distance
                };

                let (lx, ly) = wedge.centroid();
                let mid_angle = (wedge.start_angle + wedge.end_angle) / 2.0;
                let label_x = cx + label_r * mid_angle.cos();
                let label_y = cy + label_r * mid_angle.sin();

                renderer.draw_text_centered(
                    &label,
                    label_x as f32,
                    label_y as f32,
                    label_font_size_px,
                    config.text_color,
                )?;
            }
        }
    }

    Ok(pie_data)
}

// ============================================================================
// Trait Implementations
// ============================================================================

impl PlotCompute for Pie {
    type Input<'a> = &'a [f64];
    type Config = PieConfig;
    type Output = PieData;

    fn compute(input: Self::Input<'_>, config: &Self::Config) -> Result<Self::Output> {
        let positive_count = input.iter().filter(|&&v| v > 0.0).count();
        if positive_count == 0 {
            return Err(crate::core::PlottingError::EmptyDataSet);
        }

        Ok(PieData::compute(input, config))
    }
}

impl PlotData for PieData {
    fn data_bounds(&self) -> ((f64, f64), (f64, f64)) {
        // Pie charts use a normalized 0-1 coordinate space
        ((0.0, 1.0), (0.0, 1.0))
    }

    fn is_empty(&self) -> bool {
        self.values.is_empty()
    }
}

impl PlotRender for PieData {
    fn render(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        theme: &Theme,
        color: Color,
    ) -> Result<()> {
        self.render_styled(renderer, area, theme, color, 1.0, None)
    }

    /// # The `color` argument is deliberately ignored
    ///
    /// A pie needs one colour *per wedge*, so a single series colour cannot
    /// describe it: honouring it would paint every wedge the same and erase the
    /// chart. Wedge colours come from [`PieConfig::colors`], falling back to the
    /// theme palette. This means a generic `.color(..)` on the pie builder is a
    /// no-op — use `PieConfig::colors` instead.
    fn render_styled(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        theme: &Theme,
        _color: Color,
        alpha: f32,
        line_width: Option<f32>,
    ) -> Result<()> {
        if self.wedges.is_empty() {
            return Ok(());
        }

        let config = &self.config;

        // Calculate center and radius from plot area
        let (cx, cy) = area.data_to_screen(0.5, 0.5);
        let (edge_x, _) = area.data_to_screen(1.0, 0.5);
        let (_, edge_y) = area.data_to_screen(0.5, 1.0);
        let radius = ((edge_x - cx).abs().min((edge_y - cy).abs())) * 0.9;

        // Recompute wedges with screen coordinates
        let screen_data =
            PieData::from_values(&self.values, cx as f64, cy as f64, radius as f64, config);

        // Get colors from config or theme palette
        let colors = if let Some(ref colors) = config.colors {
            colors.clone()
        } else {
            let palette = theme.color_palette.clone();
            (0..screen_data.wedges.len())
                .map(|i| palette[i % palette.len()])
                .collect()
        }
        .into_iter()
        .map(|color| color.with_alpha((f32::from(color.a) / 255.0) * alpha.clamp(0.0, 1.0)))
        .collect::<Vec<_>>();

        // Number of segments per arc for smooth curves
        let segments = 64;
        let render_scale = renderer.render_scale();
        let edge_width_px = render_scale.points_to_pixels(line_width.unwrap_or(config.edge_width));
        let label_font_size_px = render_scale.points_to_pixels(config.label_font_size);
        let shadow_offset_px = render_scale.points_to_pixels(config.shadow as f32) as f64;

        // Draw shadow if configured
        if config.shadow > 0.0 {
            let shadow_color = Color::from_rgb(100, 100, 100).with_alpha(0.3 * alpha);
            for wedge in &screen_data.wedges {
                let polygon = wedge.as_polygon(segments);
                let shadow_polygon: Vec<(f32, f32)> = polygon
                    .iter()
                    .map(|(x, y)| {
                        (
                            (*x + shadow_offset_px) as f32,
                            (*y + shadow_offset_px) as f32,
                        )
                    })
                    .collect();
                renderer.draw_filled_polygon(&shadow_polygon, shadow_color)?;
            }
        }

        // Draw wedges
        for (i, wedge) in screen_data.wedges.iter().enumerate() {
            let color = colors[i % colors.len()];
            let polygon = wedge.as_polygon(segments);
            let polygon_f32: Vec<(f32, f32)> = polygon
                .iter()
                .map(|(x, y)| (*x as f32, *y as f32))
                .collect();

            // Draw filled wedge
            renderer.draw_filled_polygon(&polygon_f32, color)?;

            // Draw edge if configured
            if let Some(edge_color) = config.edge_color {
                let edge_color = edge_color
                    .with_alpha((f32::from(edge_color.a) / 255.0) * alpha.clamp(0.0, 1.0));
                renderer.draw_polygon_outline(&polygon_f32, edge_color, edge_width_px)?;
            }
        }

        // Draw labels
        if config.show_labels || config.show_percentages || config.show_values {
            for (i, wedge) in screen_data.wedges.iter().enumerate() {
                let label_parts: Vec<String> = [
                    if config.show_labels && i < config.labels.len() {
                        Some(config.labels[i].clone())
                    } else {
                        None
                    },
                    if config.show_percentages {
                        Some(format!("{:.1}%", screen_data.percentages[i]))
                    } else {
                        None
                    },
                    if config.show_values {
                        Some(format!("{:.1}", screen_data.values[i]))
                    } else {
                        None
                    },
                ]
                .into_iter()
                .flatten()
                .collect();

                if !label_parts.is_empty() {
                    let label = label_parts.join("\n");

                    // Calculate label position
                    let label_r = if config.inner_radius > 0.0 {
                        radius as f64 * (1.0 + config.inner_radius) / 2.0 * config.label_distance
                    } else {
                        radius as f64 * config.label_distance
                    };

                    let mid_angle = (wedge.start_angle + wedge.end_angle) / 2.0;
                    let label_x = cx as f64 + label_r * mid_angle.cos();
                    let label_y = cy as f64 + label_r * mid_angle.sin();

                    renderer.draw_text_centered(
                        &label,
                        label_x as f32,
                        label_y as f32,
                        label_font_size_px,
                        config.text_color,
                    )?;
                }
            }
        }

        Ok(())
    }
}

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

    #[test]
    fn test_pie_data_basic() {
        let values = vec![30.0, 20.0, 50.0];
        let config = PieConfig::default();
        let data = PieData::from_values(&values, 100.0, 100.0, 50.0, &config);

        assert_eq!(data.wedges.len(), 3);
        assert!((data.total - 100.0).abs() < 1e-10);
        assert!((data.percentages[0] - 30.0).abs() < 1e-10);
        assert!((data.percentages[1] - 20.0).abs() < 1e-10);
        assert!((data.percentages[2] - 50.0).abs() < 1e-10);
    }

    #[test]
    fn test_pie_config_donut() {
        let config = PieConfig::default().donut(0.5);
        assert!((config.inner_radius - 0.5).abs() < 1e-10);
    }

    #[test]
    fn test_pie_data_with_explode() {
        let values = vec![25.0, 25.0, 50.0];
        let config = PieConfig::default().explode(vec![0.1, 0.0, 0.0]);
        let data = PieData::from_values(&values, 100.0, 100.0, 50.0, &config);

        assert_eq!(data.wedges.len(), 3);
        // First wedge should be exploded
        assert!(data.wedges[0].explode > 0.0);
        assert!((data.wedges[1].explode - 0.0).abs() < 1e-10);
    }

    #[test]
    fn test_pie_ignores_negative() {
        let values = vec![30.0, -10.0, 20.0];
        let config = PieConfig::default();
        let data = PieData::from_values(&values, 100.0, 100.0, 50.0, &config);

        // Should only have 2 wedges (negative value filtered)
        assert_eq!(data.wedges.len(), 2);
    }

    #[test]
    fn test_pie_per_value_config_tracks_filtered_values() {
        let red = Color::from_rgb(255, 0, 0);
        let green = Color::from_rgb(0, 255, 0);
        let blue = Color::from_rgb(0, 0, 255);
        let values = vec![30.0, -10.0, 20.0];
        let config = PieConfig::new(vec!["a".to_string(), "b".to_string(), "c".to_string()])
            .explode(vec![0.0, 0.5, 0.0])
            .colors(vec![red, green, blue]);
        let data = PieData::from_values(&values, 100.0, 100.0, 50.0, &config);

        assert_eq!(data.values, vec![30.0, 20.0]);
        // The dropped value must take its label, explode offset and color with it.
        assert_eq!(data.config.labels, vec!["a".to_string(), "c".to_string()]);
        assert_eq!(data.config.explode, vec![0.0, 0.0]);
        assert_eq!(data.config.colors, Some(vec![red, blue]));
        assert!(data.wedges.iter().all(|wedge| wedge.explode.abs() < 1e-10));

        // Recomputing from already-filtered data is idempotent.
        let again = PieData::from_values(&data.values, 0.0, 0.0, 1.0, &data.config);
        assert_eq!(again.config.labels, data.config.labels);
        assert_eq!(again.config.colors, data.config.colors);
    }

    #[test]
    fn test_pie_all_values_positive_keeps_config_untouched() {
        let values = vec![30.0, 20.0, 50.0];
        let config = PieConfig::new(vec!["a".to_string(), "b".to_string(), "c".to_string()]);
        let data = PieData::from_values(&values, 100.0, 100.0, 50.0, &config);

        assert_eq!(data.config.labels, config.labels);
    }

    #[test]
    fn test_pie_starts_at_twelve_oclock_counter_clockwise() {
        let values = vec![30.0, 20.0, 50.0];
        let config = PieConfig::default();
        let (cx, cy) = (100.0, 100.0);
        let data = PieData::from_values(&values, cx, cy, 50.0, &config);

        // Default start_angle of 90° is 12 o'clock: one boundary ray points up.
        // Screen space has +y down, so "up" is -PI/2.
        let boundary = data.wedges[0].end_angle;
        assert!((boundary + PI / 2.0).abs() < 1e-9, "boundary: {boundary}");

        // Counter-clockwise from the top puts the first wedge's midpoint in the
        // upper-left quadrant (matplotlib's default direction).
        let (mx, my) = data.wedges[0].centroid();
        assert!(mx < cx, "midpoint x {mx} should be left of {cx}");
        assert!(my < cy, "midpoint y {my} should be above {cy}");

        // Wedges stay adjacent and cover the full turn.
        for pair in data.wedges.windows(2) {
            assert!((pair[0].start_angle - pair[1].end_angle).abs() < 1e-9);
        }
        let swept: f64 = data
            .wedges
            .iter()
            .map(|wedge| (wedge.end_angle - wedge.start_angle).abs())
            .sum();
        assert!((swept - 2.0 * PI).abs() < 1e-9);
    }

    #[test]
    fn test_pie_clockwise_reverses_direction() {
        let values = vec![30.0, 20.0, 50.0];
        let config = PieConfig::default().clockwise();
        let (cx, cy) = (100.0, 100.0);
        let data = PieData::from_values(&values, cx, cy, 50.0, &config);

        // Still starts at 12 o'clock, but sweeps toward the upper-right.
        assert!((data.wedges[0].start_angle + PI / 2.0).abs() < 1e-9);
        let (mx, my) = data.wedges[0].centroid();
        assert!(mx > cx, "midpoint x {mx} should be right of {cx}");
        assert!(my < cy, "midpoint y {my} should be above {cy}");
    }

    #[test]
    fn test_pie_start_angle_zero_is_three_oclock() {
        let values = vec![25.0, 75.0];
        let config = PieConfig::default().start_angle(0.0);
        let (cx, cy) = (0.0, 0.0);
        let data = PieData::from_values(&values, cx, cy, 1.0, &config);

        // start_angle 0 is the +x axis; the first wedge sweeps counter-clockwise
        // into the upper-right quadrant.
        assert!(data.wedges[0].end_angle.abs() < 1e-9);
        let (mx, my) = data.wedges[0].centroid();
        assert!(mx > 0.0 && my < 0.0, "midpoint ({mx}, {my})");
    }

    #[test]
    fn test_pie_config_implements_plot_config() {
        fn assert_plot_config<T: PlotConfig>() {}
        assert_plot_config::<PieConfig>();
    }

    /// `PieConfig::clockwise` was reported as an inert setter (plan item 2.4).
    /// It is not: `PieData::from_values` reads `counter_clockwise`, and
    /// `render_styled` re-derives the wedges from the stored config, so the
    /// direction reaches the pixels. This test guards the render path that
    /// `test_pie_clockwise_reverses_direction` does not cover.
    #[test]
    fn test_clockwise_changes_the_rendered_image() {
        fn render(config: PieConfig) -> Vec<u8> {
            let values = vec![10.0, 20.0, 70.0];
            let data = PieData::compute(&values, &config);
            let mut renderer = SkiaRenderer::new(160, 160, Theme::default()).unwrap();
            let area = PlotArea::new(0.0, 0.0, 160.0, 160.0, 0.0, 1.0, 0.0, 1.0);
            data.render(
                &mut renderer,
                &area,
                &Theme::default(),
                Color::from_rgb(0, 0, 0),
            )
            .unwrap();
            renderer.into_image().pixels
        }

        let ccw = render(PieConfig::default().labels(false).percentages(false));
        let cw = render(
            PieConfig::default()
                .labels(false)
                .percentages(false)
                .clockwise(),
        );

        assert_ne!(
            ccw, cw,
            "PieConfig::clockwise produced a byte-identical image"
        );
    }

    #[test]
    fn test_pie_plot_compute_trait() {
        use crate::plots::traits::PlotCompute;

        let values = vec![30.0, 20.0, 50.0];
        let config = PieConfig::default();
        let result = Pie::compute(&values, &config);

        assert!(result.is_ok());
        let pie_data = result.unwrap();
        assert_eq!(pie_data.wedges.len(), 3);
        assert!((pie_data.total - 100.0).abs() < 1e-10);
    }

    #[test]
    fn test_pie_plot_compute_empty() {
        use crate::plots::traits::PlotCompute;

        let values: Vec<f64> = vec![];
        let config = PieConfig::default();
        let result = Pie::compute(&values, &config);

        assert!(result.is_err());
    }

    #[test]
    fn test_pie_plot_compute_all_negative() {
        use crate::plots::traits::PlotCompute;

        let values = vec![-10.0, -20.0];
        let config = PieConfig::default();
        let result = Pie::compute(&values, &config);

        assert!(result.is_err());
    }

    #[test]
    fn test_pie_plot_data_trait() {
        use crate::plots::traits::{PlotCompute, PlotData};

        let values = vec![30.0, 20.0, 50.0];
        let config = PieConfig::default();
        let pie_data = Pie::compute(&values, &config).unwrap();

        // Test data_bounds (pie uses normalized 0-1 space)
        let ((x_min, x_max), (y_min, y_max)) = pie_data.data_bounds();
        assert!((x_min - 0.0).abs() < 1e-10);
        assert!((x_max - 1.0).abs() < 1e-10);
        assert!((y_min - 0.0).abs() < 1e-10);
        assert!((y_max - 1.0).abs() < 1e-10);

        // Test is_empty
        assert!(!pie_data.is_empty());
    }
}