Skip to main content

tui_piechart/
lib.rs

1//! # tui-piechart
2//!
3//! A customizable pie chart widget for [Ratatui](https://github.com/ratatui/ratatui) TUI applications.
4//!
5//! ## Features
6//!
7//! - 🥧 Simple pie chart with customizable slices
8//! - 🎨 Customizable colors for each slice
9//! - 🔤 Labels and percentages
10//! - 📊 Legend support
11//! - 📦 Optional block wrapper
12//! - ✨ Custom symbols for pie chart and legend
13//! - 🔭 More chart types (gauges, radial bars, radar, treemap, funnel, waterfall, instruments)
14//!   live in [`tui-chart`](https://crates.io/crates/tui-chart)
15//! - 🍩 Donut / segmented / HUD / rose pies via [`PieStyle`]
16//! - ⚡ Zero-cost abstractions
17//!
18//! ## Examples
19//!
20//! Basic usage:
21//!
22//! ```no_run
23//! use ratatui::style::Color;
24//! use tui_piechart::{PieChart, PieSlice};
25//!
26//! let slices = vec![
27//!     PieSlice::new("Rust", 45.0, Color::Red),
28//!     PieSlice::new("Go", 30.0, Color::Blue),
29//!     PieSlice::new("Python", 25.0, Color::Green),
30//! ];
31//! let piechart = PieChart::new(slices);
32//! ```
33//!
34//! With custom styling:
35//!
36//! ```no_run
37//! use ratatui::style::{Color, Style};
38//! use tui_piechart::{PieChart, PieSlice};
39//!
40//! let slices = vec![
41//!     PieSlice::new("Rust", 45.0, Color::Red),
42//!     PieSlice::new("Go", 30.0, Color::Blue),
43//! ];
44//! let piechart = PieChart::new(slices)
45//!     .style(Style::default())
46//!     .show_legend(true)
47//!     .show_percentages(true);
48//! ```
49//!
50//! With custom symbols:
51//!
52//! ```no_run
53//! use ratatui::style::Color;
54//! use tui_piechart::{PieChart, PieSlice, symbols};
55//!
56//! let slices = vec![
57//!     PieSlice::new("Rust", 45.0, Color::Red),
58//!     PieSlice::new("Go", 30.0, Color::Blue),
59//! ];
60//!
61//! // Use predefined symbols
62//! let piechart = PieChart::new(slices.clone())
63//!     .pie_char(symbols::PIE_CHAR_BLOCK)
64//!     .legend_marker(symbols::LEGEND_MARKER_CIRCLE);
65//!
66//! // Or use any custom characters
67//! let piechart = PieChart::new(slices)
68//!     .pie_char('█')
69//!     .legend_marker("→");
70//! ```
71//!
72//! With custom border styles:
73//!
74//! ```no_run
75//! use ratatui::style::Color;
76//! use tui_piechart::{PieChart, PieSlice, border_style::BorderStyle};
77//! // Or use backwards-compatible path: use tui_piechart::symbols::BorderStyle;
78//!
79//! let slices = vec![
80//!     PieSlice::new("Rust", 45.0, Color::Red),
81//!     PieSlice::new("Go", 30.0, Color::Blue),
82//! ];
83//!
84//! // Use predefined border styles
85//! let piechart = PieChart::new(slices)
86//!     .block(BorderStyle::Rounded.block().title("My Chart"));
87//! ```
88
89#![warn(missing_docs)]
90#![warn(clippy::pedantic)]
91#![allow(clippy::module_name_repetitions)]
92
93use std::f64::consts::PI;
94
95use ratatui::buffer::Buffer;
96use ratatui::layout::Rect;
97use ratatui::style::{Color, Style, Styled};
98use ratatui::text::{Line, Span};
99use ratatui::widgets::{Block, Widget};
100
101pub mod border_style;
102mod braille;
103pub mod legend;
104pub mod pie_style;
105#[macro_use]
106pub mod macros;
107pub mod symbols;
108pub mod title;
109
110// Re-export commonly used types from submodules for convenience
111pub use legend::{LegendAlignment, LegendLayout, LegendPosition};
112pub use pie_style::PieStyle;
113pub use title::{BlockExt, TitleAlignment, TitlePosition, TitleStyle};
114#[cfg(feature = "theme")]
115pub use tui_nuances::{Theme, ThemeProvider, ThemeSwitcher, Themed};
116
117/// Rendering resolution mode for pie charts.
118///
119/// Different resolution modes provide varying levels of detail by using
120/// different Unicode block drawing characters with different dot densities.
121///
122/// # Examples
123///
124/// ```
125/// use tui_piechart::{PieChart, PieSlice, Resolution};
126/// use ratatui::style::Color;
127///
128/// let slices = vec![PieSlice::new("Rust", 45.0, Color::Red)];
129///
130/// // Standard resolution (1 dot per character)
131/// let standard = PieChart::new(slices.clone())
132///     .resolution(Resolution::Standard);
133///
134/// // High resolution with braille patterns (8 dots per character)
135/// let braille = PieChart::new(slices)
136///     .resolution(Resolution::Braille);
137/// ```
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
139pub enum Resolution {
140    /// Standard resolution using full characters (1 dot per cell).
141    ///
142    /// Uses regular Unicode characters like `●`. This is the default mode.
143    #[default]
144    Standard,
145
146    /// Braille resolution using 2×4 dot patterns (8 dots per cell).
147    ///
148    /// Uses Unicode braille patterns (U+2800-U+28FF) providing 8x resolution.
149    /// This provides the highest resolution available for terminal rendering.
150    Braille,
151}
152
153/// A slice of the pie chart representing a portion of data.
154///
155/// Each slice has a label, a value, and a color.
156///
157/// # Examples
158///
159/// ```
160/// use ratatui::style::Color;
161/// use tui_piechart::PieSlice;
162///
163/// let slice = PieSlice::new("Rust", 45.0, Color::Red);
164/// ```
165#[derive(Debug, Clone, PartialEq)]
166pub struct PieSlice<'a> {
167    /// The label for this slice
168    label: &'a str,
169    /// The value of this slice (will be converted to percentage)
170    value: f64,
171    /// The color of this slice
172    color: Color,
173}
174
175impl<'a> PieSlice<'a> {
176    /// Creates a new pie slice with the given label, value, and color.
177    ///
178    /// # Examples
179    ///
180    /// ```
181    /// use ratatui::style::Color;
182    /// use tui_piechart::PieSlice;
183    ///
184    /// let slice = PieSlice::new("Rust", 45.0, Color::Red);
185    /// ```
186    #[must_use]
187    pub const fn new(label: &'a str, value: f64, color: Color) -> Self {
188        Self {
189            label,
190            value,
191            color,
192        }
193    }
194
195    /// Creates a slice colored from the theme palette (`theme.color(index)`).
196    ///
197    /// ```
198    /// use tui_piechart::{PieSlice, Theme};
199    /// let s = PieSlice::themed("Rust", 45.0, &Theme::nord(), 0);
200    /// assert_eq!(s.color(), Theme::nord().color(0));
201    /// ```
202    #[cfg(feature = "theme")]
203    #[must_use]
204    pub fn themed(label: &'a str, value: f64, theme: &Theme, index: usize) -> Self {
205        Self::new(label, value, theme.color(index))
206    }
207
208    /// Returns the label of this slice.
209    #[must_use]
210    pub const fn label(&self) -> &'a str {
211        self.label
212    }
213
214    /// Returns the value of this slice.
215    #[must_use]
216    pub const fn value(&self) -> f64 {
217        self.value
218    }
219
220    /// Returns the color of this slice.
221    #[must_use]
222    pub const fn color(&self) -> Color {
223        self.color
224    }
225}
226
227#[cfg(feature = "theme")]
228impl Themed for PieChart<'_> {
229    fn apply_theme(self, theme: &Theme) -> Self {
230        self.theme(theme)
231    }
232}
233
234/// A widget that displays a pie chart.
235///
236/// A `PieChart` displays data as slices of a circle, where each slice represents
237/// a proportion of the total.
238///
239/// # Examples
240///
241/// ```
242/// use ratatui::style::Color;
243/// use tui_piechart::{PieChart, PieSlice};
244///
245/// let slices = vec![
246///     PieSlice::new("Rust", 45.0, Color::Red),
247///     PieSlice::new("Go", 30.0, Color::Blue),
248///     PieSlice::new("Python", 25.0, Color::Green),
249/// ];
250/// let piechart = PieChart::new(slices);
251/// ```
252#[derive(Debug, Clone, PartialEq)]
253pub struct PieChart<'a> {
254    /// The slices of the pie chart
255    slices: Vec<PieSlice<'a>>,
256    /// Optional block to wrap the pie chart
257    block: Option<Block<'a>>,
258    /// Base style for the entire widget
259    style: Style,
260    /// Theme-derived base style; lower precedence than `style`
261    theme_style: Style,
262    /// Whether to show the legend
263    show_legend: bool,
264    /// Whether to show percentages on slices
265    show_percentages: bool,
266    /// The character to use for drawing the pie chart
267    pie_char: char,
268    /// The marker to use for legend items
269    legend_marker: &'a str,
270    /// Resolution mode for rendering
271    resolution: Resolution,
272    /// Position of the legend
273    legend_position: LegendPosition,
274    /// Layout of the legend
275    legend_layout: LegendLayout,
276    /// Alignment of legend items
277    legend_alignment: LegendAlignment,
278    /// Look of the pie (solid, segmented ring, HUD, rose)
279    pie_style: PieStyle,
280    /// Hole radius as a fraction of the radius (`0` = pie, `>0` = donut)
281    hole: f64,
282    /// Start angle in turns (`0` = 12 o'clock, clockwise)
283    start: f64,
284    /// Gap between slices in braille dots (canvas styles only)
285    gap: f64,
286    /// Outward shift of every slice in braille dots (canvas styles only)
287    explode: f64,
288    /// Text shown in the donut hole
289    center: Option<&'a str>,
290}
291
292impl Default for PieChart<'_> {
293    /// Returns a default `PieChart` widget.
294    ///
295    /// The default widget has:
296    /// - No slices
297    /// - No block
298    /// - Default style
299    /// - Legend shown
300    /// - Percentages shown
301    /// - Default pie character (●)
302    /// - Default legend marker (■)
303    fn default() -> Self {
304        Self {
305            slices: Vec::new(),
306            block: None,
307            style: Style::default(),
308            theme_style: Style::default(),
309            show_legend: true,
310            show_percentages: true,
311            pie_char: symbols::PIE_CHAR,
312            legend_marker: symbols::LEGEND_MARKER,
313            resolution: Resolution::default(),
314            legend_position: LegendPosition::default(),
315            legend_layout: LegendLayout::default(),
316            legend_alignment: LegendAlignment::default(),
317            pie_style: PieStyle::default(),
318            hole: 0.0,
319            start: 0.0,
320            gap: 0.0,
321            explode: 0.0,
322            center: None,
323        }
324    }
325}
326
327impl<'a> PieChart<'a> {
328    /// Creates a new `PieChart` with the given slices.
329    ///
330    /// # Examples
331    ///
332    /// ```
333    /// use ratatui::style::Color;
334    /// use tui_piechart::{PieChart, PieSlice};
335    ///
336    /// let slices = vec![
337    ///     PieSlice::new("Rust", 45.0, Color::Red),
338    ///     PieSlice::new("Go", 30.0, Color::Blue),
339    /// ];
340    /// let piechart = PieChart::new(slices);
341    /// ```
342    #[must_use]
343    pub fn new(slices: Vec<PieSlice<'a>>) -> Self {
344        Self {
345            slices,
346            ..Default::default()
347        }
348    }
349
350    /// The slices, in drawing order.
351    ///
352    /// Together with [`areas`](Self::areas) this lets other crates build hit
353    /// testing (hover / click) on top of a rendered chart.
354    #[must_use]
355    pub fn slice_list(&self) -> &[PieSlice<'a>] {
356        &self.slices
357    }
358
359    /// Sets the slices of the pie chart.
360    ///
361    /// # Examples
362    ///
363    /// ```
364    /// use ratatui::style::Color;
365    /// use tui_piechart::{PieChart, PieSlice};
366    ///
367    /// let slices = vec![
368    ///     PieSlice::new("Rust", 45.0, Color::Red),
369    /// ];
370    /// let piechart = PieChart::default().slices(slices);
371    /// ```
372    #[must_use]
373    pub fn slices(mut self, slices: Vec<PieSlice<'a>>) -> Self {
374        self.slices = slices;
375        self
376    }
377
378    /// Wraps the pie chart with the given block.
379    ///
380    /// # Examples
381    ///
382    /// ```
383    /// use ratatui::style::Color;
384    /// use ratatui::widgets::Block;
385    /// use tui_piechart::{PieChart, PieSlice};
386    ///
387    /// let slices = vec![PieSlice::new("Rust", 45.0, Color::Red)];
388    /// let piechart = PieChart::new(slices)
389    ///     .block(Block::bordered().title("Statistics"));
390    /// ```
391    #[must_use]
392    pub fn block(mut self, block: Block<'a>) -> Self {
393        self.block = Some(block);
394        self
395    }
396
397    /// Sets the base style of the widget.
398    ///
399    /// # Examples
400    ///
401    /// ```
402    /// use ratatui::style::{Color, Style};
403    /// use tui_piechart::PieChart;
404    ///
405    /// let piechart = PieChart::default()
406    ///     .style(Style::default().fg(Color::White));
407    /// ```
408    #[must_use]
409    pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
410        self.style = style.into();
411        self
412    }
413
414    /// Applies a shared [`Theme`] (foreground/background of the widget).
415    ///
416    /// Precedence: fields set explicitly with [`style`](Self::style) always win
417    /// over the theme, regardless of call order. Without a theme the look is unchanged.
418    ///
419    /// ```
420    /// use tui_piechart::{PieChart, Theme};
421    /// let chart = PieChart::default().theme(&Theme::nord());
422    /// ```
423    #[cfg(feature = "theme")]
424    #[must_use]
425    pub fn theme(mut self, theme: &Theme) -> Self {
426        self.theme_style = theme.style();
427        self
428    }
429
430    /// Sets whether to show the legend.
431    ///
432    /// # Examples
433    ///
434    /// ```
435    /// use tui_piechart::PieChart;
436    ///
437    /// let piechart = PieChart::default().show_legend(true);
438    /// ```
439    #[must_use]
440    pub const fn show_legend(mut self, show: bool) -> Self {
441        self.show_legend = show;
442        self
443    }
444
445    /// Sets whether to show percentages on slices.
446    ///
447    /// # Examples
448    ///
449    /// ```
450    /// use tui_piechart::PieChart;
451    ///
452    /// let piechart = PieChart::default().show_percentages(true);
453    /// ```
454    #[must_use]
455    pub const fn show_percentages(mut self, show: bool) -> Self {
456        self.show_percentages = show;
457        self
458    }
459
460    /// Sets the character used to draw the pie chart.
461    ///
462    /// You can use any Unicode character for custom visualization.
463    ///
464    /// # Examples
465    ///
466    /// Using a predefined symbol:
467    ///
468    /// ```
469    /// use tui_piechart::{PieChart, symbols};
470    ///
471    /// let piechart = PieChart::default()
472    ///     .pie_char(symbols::PIE_CHAR_BLOCK);
473    /// ```
474    ///
475    /// Using a custom character:
476    ///
477    /// ```
478    /// use tui_piechart::PieChart;
479    ///
480    /// let piechart = PieChart::default().pie_char('█');
481    /// ```
482    #[must_use]
483    pub const fn pie_char(mut self, c: char) -> Self {
484        self.pie_char = c;
485        self
486    }
487
488    /// Sets the marker used for legend items.
489    ///
490    /// You can use any string (including Unicode characters) for custom markers.
491    ///
492    /// # Examples
493    ///
494    /// Using a predefined symbol:
495    ///
496    /// ```
497    /// use tui_piechart::{PieChart, symbols};
498    ///
499    /// let piechart = PieChart::default()
500    ///     .legend_marker(symbols::LEGEND_MARKER_CIRCLE);
501    /// ```
502    ///
503    /// Using custom markers:
504    ///
505    /// ```
506    /// use tui_piechart::PieChart;
507    ///
508    /// // Simple arrow
509    /// let piechart = PieChart::default().legend_marker("→");
510    ///
511    /// // Or any Unicode character
512    /// let piechart = PieChart::default().legend_marker("★");
513    ///
514    /// // Or even multi-character strings
515    /// let piechart = PieChart::default().legend_marker("-->");
516    /// ```
517    #[must_use]
518    pub const fn legend_marker(mut self, marker: &'a str) -> Self {
519        self.legend_marker = marker;
520        self
521    }
522
523    /// Sets the rendering resolution mode.
524    ///
525    /// Different resolution modes provide varying levels of detail:
526    /// - `Standard`: Regular characters (1 dot per cell)
527    /// - `Braille`: 2×4 patterns (8 dots per cell, 8x resolution)
528    ///
529    /// # Examples
530    ///
531    /// ```
532    /// use tui_piechart::{PieChart, Resolution};
533    ///
534    /// let standard = PieChart::default().resolution(Resolution::Standard);
535    /// let braille = PieChart::default().resolution(Resolution::Braille);
536    /// ```
537    #[must_use]
538    pub const fn resolution(mut self, resolution: Resolution) -> Self {
539        self.resolution = resolution;
540        self
541    }
542
543    /// Sets whether to use high resolution rendering with braille patterns.
544    ///
545    /// This is a convenience method that sets the resolution to `Braille` when enabled,
546    /// or `Standard` when disabled. For more control, use [`resolution`](Self::resolution).
547    ///
548    /// # Examples
549    ///
550    /// ```
551    /// use tui_piechart::PieChart;
552    ///
553    /// let piechart = PieChart::default().high_resolution(true);
554    /// ```
555    #[must_use]
556    pub const fn high_resolution(mut self, enabled: bool) -> Self {
557        self.resolution = if enabled {
558            Resolution::Braille
559        } else {
560            Resolution::Standard
561        };
562        self
563    }
564
565    /// Sets the position of the legend relative to the pie chart.
566    ///
567    /// # Examples
568    ///
569    /// ```
570    /// use tui_piechart::{PieChart, LegendPosition};
571    ///
572    /// let piechart = PieChart::default()
573    ///     .legend_position(LegendPosition::Right);
574    /// ```
575    #[must_use]
576    pub const fn legend_position(mut self, position: LegendPosition) -> Self {
577        self.legend_position = position;
578        self
579    }
580
581    /// Sets the layout mode for the legend.
582    ///
583    /// # Examples
584    ///
585    /// ```
586    /// use tui_piechart::{PieChart, LegendLayout};
587    ///
588    /// // Single horizontal row
589    /// let piechart = PieChart::default()
590    ///     .legend_layout(LegendLayout::Horizontal);
591    ///
592    /// // Vertical stacking (default)
593    /// let piechart = PieChart::default()
594    ///     .legend_layout(LegendLayout::Vertical);
595    /// ```
596    #[must_use]
597    pub const fn legend_layout(mut self, layout: LegendLayout) -> Self {
598        self.legend_layout = layout;
599        self
600    }
601
602    /// Sets the alignment of legend items within the legend area.
603    ///
604    /// # Examples
605    ///
606    /// ```
607    /// use tui_piechart::{PieChart, LegendAlignment};
608    ///
609    /// // Center-align legend items
610    /// let piechart = PieChart::default()
611    ///     .legend_alignment(LegendAlignment::Center);
612    ///
613    /// // Right-align legend items
614    /// let piechart = PieChart::default()
615    ///     .legend_alignment(LegendAlignment::Right);
616    /// ```
617    #[must_use]
618    pub const fn legend_alignment(mut self, alignment: LegendAlignment) -> Self {
619        self.legend_alignment = alignment;
620        self
621    }
622
623    /// Draws a donut: the inner `hole` fraction (`0.0..=0.95`) of the radius stays empty.
624    ///
625    /// # Examples
626    ///
627    /// ```
628    /// use tui_piechart::PieChart;
629    ///
630    /// let donut = PieChart::default().hole(0.55).center("42 items");
631    /// ```
632    #[must_use]
633    pub fn hole(mut self, hole: f64) -> Self {
634        self.hole = if hole.is_finite() {
635            hole.clamp(0.0, 0.95)
636        } else {
637            0.0
638        };
639        self
640    }
641
642    /// Sets where the first slice starts, in degrees clockwise from 12 o'clock.
643    ///
644    /// # Examples
645    ///
646    /// ```
647    /// use tui_piechart::PieChart;
648    ///
649    /// let chart = PieChart::default().start_angle(90.0);
650    /// ```
651    #[must_use]
652    pub fn start_angle(mut self, degrees: f64) -> Self {
653        self.start = if degrees.is_finite() {
654            (degrees / 360.0).rem_euclid(1.0)
655        } else {
656            0.0
657        };
658        self
659    }
660
661    /// Leaves a gap of `dots` braille dots between slices (`0` = flush).
662    ///
663    /// Gaps, [`Self::explode`] and the non-solid [`PieStyle`]s are drawn with
664    /// braille dots, whatever the [`Resolution`].
665    #[must_use]
666    pub fn gap(mut self, dots: f64) -> Self {
667        self.gap = if dots.is_finite() {
668            dots.clamp(0.0, 8.0)
669        } else {
670            0.0
671        };
672        self
673    }
674
675    /// Pushes every slice outward by `dots` braille dots (an exploded pie).
676    #[must_use]
677    pub fn explode(mut self, dots: f64) -> Self {
678        self.explode = if dots.is_finite() {
679            dots.clamp(0.0, 8.0)
680        } else {
681            0.0
682        };
683        self
684    }
685
686    /// Chooses how slices are drawn: solid, segmented ring, HUD band or rose.
687    #[must_use]
688    pub const fn pie_style(mut self, style: PieStyle) -> Self {
689        self.pie_style = style;
690        self
691    }
692
693    /// Text shown in the middle of a donut (needs a [`Self::hole`]).
694    #[must_use]
695    pub const fn center(mut self, text: &'a str) -> Self {
696        self.center = Some(text);
697        self
698    }
699
700    fn total_value(&self) -> f64 {
701        self.slices.iter().map(|s| s.value).sum()
702    }
703
704    /// Computes the percentage a value represents of a total.
705    ///
706    /// Returns `0.0` when `total` is not strictly positive, which keeps the
707    /// arithmetic safe for empty charts and all-zero data sets.
708    fn value_percent(value: f64, total: f64) -> f64 {
709        if total > 0.0 {
710            (value / total) * 100.0
711        } else {
712            0.0
713        }
714    }
715
716    /// Calculates the percentage for a given slice.
717    fn percentage(&self, slice: &PieSlice) -> f64 {
718        Self::value_percent(slice.value, self.total_value())
719    }
720}
721
722impl Styled for PieChart<'_> {
723    type Item = Self;
724
725    fn style(&self) -> Style {
726        self.style
727    }
728
729    fn set_style<S: Into<Style>>(mut self, style: S) -> Self::Item {
730        self.style = style.into();
731        self
732    }
733}
734
735impl Widget for PieChart<'_> {
736    fn render(self, area: Rect, buf: &mut Buffer) {
737        Widget::render(&self, area, buf);
738    }
739}
740
741impl Widget for &PieChart<'_> {
742    fn render(self, area: Rect, buf: &mut Buffer) {
743        buf.set_style(area, self.theme_style.patch(self.style));
744        let inner = if let Some(ref block) = self.block {
745            let inner_area = block.inner(area);
746            block.render(area, buf);
747            inner_area
748        } else {
749            area
750        };
751        self.render_piechart(inner, buf);
752    }
753}
754
755impl PieChart<'_> {
756    /// Maximum ratio for vertical legend width (1/3 of available width).
757    const LEGEND_VERTICAL_MAX_RATIO: u16 = 3;
758
759    /// Minimum width for vertical legend to ensure readability.
760    const LEGEND_VERTICAL_MIN_WIDTH: u16 = 20;
761
762    /// Maximum ratio for horizontal legend width (2/5 = 40% of available width).
763    /// This keeps the pie chart proportional and prevents legend from dominating.
764    const LEGEND_HORIZONTAL_MAX_RATIO: u16 = 5;
765
766    /// Absolute maximum width for horizontal legends to prevent excessive space usage.
767    const LEGEND_HORIZONTAL_MAX_WIDTH: u16 = 60;
768
769    /// Absolute maximum height for vertical legends to prevent pie chart from being too small.
770    /// This allows 4 items with spacing (4 items * 2 lines = 8 lines, +1 for padding = 9).
771    const LEGEND_VERTICAL_MAX_HEIGHT: u16 = 9;
772
773    /// Height required for horizontal legend layout (single row with padding).
774    const LEGEND_HORIZONTAL_HEIGHT: u16 = 3;
775
776    /// Space between pie chart and legend areas.
777    const LEGEND_SPACING: u16 = 1;
778
779    /// Inner padding for legend area.
780    const LEGEND_PADDING: u16 = 1;
781
782    fn render_piechart(&self, area: Rect, buf: &mut Buffer) {
783        if area.is_empty() || self.slices.is_empty() {
784            return;
785        }
786
787        let total = self.total_value();
788        if total <= 0.0 {
789            return;
790        }
791
792        if self.needs_canvas() {
793            self.render_piechart_canvas(area, buf);
794            return;
795        }
796
797        match self.resolution {
798            Resolution::Standard => {
799                // Continue with standard rendering below
800            }
801            Resolution::Braille => {
802                self.render_piechart_braille(area, buf);
803                return;
804            }
805        }
806
807        // Calculate layout with legend positioning
808        let (pie_area, legend_area_opt) = self.calculate_layout(area);
809
810        // Calculate the center and radius of the pie chart
811        // Account for terminal character aspect ratio (typically 1:2, chars are twice as tall as wide)
812        let center_x = pie_area.width / 2;
813        let center_y = pie_area.height / 2;
814
815        // Adjust radius for aspect ratio - use width as limiting factor
816        let radius = center_x.min(center_y * 2).saturating_sub(1);
817
818        // Draw the pie chart
819        let mut cumulative_percent = self.start * 100.0;
820        for slice in &self.slices {
821            let percent = self.percentage(slice);
822            self.render_slice(
823                pie_area,
824                buf,
825                center_x,
826                center_y,
827                radius,
828                cumulative_percent,
829                percent,
830                slice.color,
831            );
832            cumulative_percent += percent;
833        }
834
835        self.draw_center(pie_area, buf);
836
837        // Draw legend if enabled
838        if let Some(legend_area) = legend_area_opt {
839            self.render_legend(buf, legend_area);
840        }
841    }
842
843    /// Returns the `(start_angle, end_angle, is_full_circle)` for a slice.
844    ///
845    /// Angles start at the top of the circle (12 o'clock) and increase
846    /// clockwise. A slice covering the whole circle is flagged so callers can
847    /// fill the entire disc instead of collapsing to a single boundary line.
848    fn slice_angles(start_percent: f64, percent: f64) -> (f64, f64, bool) {
849        let start_angle = (start_percent / 100.0) * 2.0 * PI - PI / 2.0;
850        let end_angle = ((start_percent + percent) / 100.0) * 2.0 * PI - PI / 2.0;
851        let is_full_circle = percent >= 100.0 - f64::EPSILON;
852        (start_angle, end_angle, is_full_circle)
853    }
854
855    #[allow(clippy::too_many_arguments, clippy::similar_names)]
856    fn render_slice(
857        &self,
858        area: Rect,
859        buf: &mut Buffer,
860        center_x: u16,
861        center_y: u16,
862        radius: u16,
863        start_percent: f64,
864        percent: f64,
865        color: Color,
866    ) {
867        if radius == 0 || percent <= 0.0 {
868            return;
869        }
870
871        // A slice covering the whole (or effectively the whole) circle must be
872        // rendered as a full disc. Otherwise the start and end angles collapse
873        // to the same value and only the boundary line gets drawn.
874        let (start_angle, end_angle, is_full_circle) = Self::slice_angles(start_percent, percent);
875
876        // Scan the entire area around the center
877        let scan_width = i32::from(radius + 1);
878        let scan_height = i32::from((radius / 2) + 1); // Account for aspect ratio
879
880        for dy in -scan_height..=scan_height {
881            for dx in -scan_width..=scan_width {
882                // Calculate actual position in buffer
883                let x = i32::from(area.x) + i32::from(center_x) + dx;
884                let y = i32::from(area.y) + i32::from(center_y) + dy;
885
886                // Check bounds
887                if x < i32::from(area.x)
888                    || x >= i32::from(area.x + area.width)
889                    || y < i32::from(area.y)
890                    || y >= i32::from(area.y + area.height)
891                {
892                    continue;
893                }
894
895                // Adjust for aspect ratio: multiply y distance by 2
896                #[allow(clippy::cast_precision_loss)]
897                let adjusted_dx = f64::from(dx);
898                #[allow(clippy::cast_precision_loss)]
899                let adjusted_dy = f64::from(dy * 2);
900
901                // Calculate distance from center
902                let distance = (adjusted_dx * adjusted_dx + adjusted_dy * adjusted_dy).sqrt();
903
904                // Check if point is within radius
905                #[allow(clippy::cast_precision_loss)]
906                if distance <= f64::from(radius) && distance >= self.hole * f64::from(radius) {
907                    // Calculate angle from center (0 = right, PI/2 = up, PI = left, 3PI/2 = down)
908                    let angle = adjusted_dy.atan2(adjusted_dx);
909
910                    // Check if angle is within slice
911                    if is_full_circle || Self::is_angle_in_slice(angle, start_angle, end_angle) {
912                        #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
913                        {
914                            let cell = &mut buf[(x as u16, y as u16)];
915                            cell.set_char(self.pie_char).set_fg(color);
916                        }
917                    }
918                }
919            }
920        }
921    }
922
923    fn is_angle_in_slice(angle: f64, start: f64, end: f64) -> bool {
924        // Normalize angles to [0, 2π]
925        let normalize = |a: f64| {
926            let mut normalized = a % (2.0 * PI);
927            if normalized < 0.0 {
928                normalized += 2.0 * PI;
929            }
930            normalized
931        };
932
933        let norm_angle = normalize(angle);
934        let norm_start = normalize(start);
935        let norm_end = normalize(end);
936
937        if norm_start <= norm_end {
938            norm_angle >= norm_start && norm_angle <= norm_end
939        } else {
940            // Handle wrap around at 2π/0
941            norm_angle >= norm_start || norm_angle <= norm_end
942        }
943    }
944
945    fn format_legend_text(&self, slice: &PieSlice, total: f64, spacing: &str) -> String {
946        if self.show_percentages {
947            let percent = Self::value_percent(slice.value, total);
948            format!(
949                "{} {} {:.1}%{}",
950                self.legend_marker, slice.label, percent, spacing
951            )
952        } else {
953            format!("{} {}{}", self.legend_marker, slice.label, spacing)
954        }
955    }
956
957    /// Rendered display width of a single legend entry (marker, label, and an
958    /// optional percentage) followed by two spaces of trailing padding.
959    fn legend_item_width(&self, slice: &PieSlice, total: f64) -> u16 {
960        u16::try_from(self.format_legend_text(slice, total, "  ").chars().count())
961            .unwrap_or(u16::MAX)
962    }
963
964    fn calculate_aligned_x(&self, legend_area: Rect, content_width: u16) -> u16 {
965        match self.legend_alignment {
966            LegendAlignment::Left => legend_area.x,
967            LegendAlignment::Center => {
968                legend_area.x + (legend_area.width.saturating_sub(content_width)) / 2
969            }
970            LegendAlignment::Right => {
971                legend_area.x + legend_area.width.saturating_sub(content_width)
972            }
973        }
974    }
975
976    fn render_legend(&self, buf: &mut Buffer, legend_area: Rect) {
977        let total = self.total_value();
978
979        match self.legend_layout {
980            LegendLayout::Vertical => {
981                self.render_vertical_legend(buf, legend_area, total);
982            }
983            LegendLayout::Horizontal => {
984                self.render_horizontal_legend(buf, legend_area, total);
985            }
986        }
987    }
988
989    fn render_vertical_legend(&self, buf: &mut Buffer, legend_area: Rect, total: f64) {
990        for (idx, slice) in self.slices.iter().enumerate() {
991            #[allow(clippy::cast_possible_truncation)]
992            let y_offset = (idx as u16) * 2;
993
994            if y_offset >= legend_area.height {
995                break;
996            }
997
998            let legend_text = self.format_legend_text(slice, total, "");
999            #[allow(clippy::cast_possible_truncation)]
1000            let text_width = u16::try_from(legend_text.chars().count()).unwrap_or(u16::MAX);
1001            let x_pos = self.calculate_aligned_x(legend_area, text_width);
1002
1003            let line = Line::from(vec![Span::styled(
1004                legend_text,
1005                Style::default().fg(slice.color),
1006            )]);
1007            let item_area = Rect {
1008                x: x_pos,
1009                y: legend_area.y + y_offset,
1010                width: text_width.min(legend_area.width),
1011                height: 1,
1012            };
1013
1014            line.render(item_area, buf);
1015        }
1016    }
1017
1018    fn render_horizontal_legend(&self, buf: &mut Buffer, legend_area: Rect, total: f64) {
1019        let mut total_width = 0u16;
1020        let mut item_widths = Vec::new();
1021
1022        for slice in &self.slices {
1023            let legend_text = self.format_legend_text(slice, total, "  ");
1024            #[allow(clippy::cast_possible_truncation)]
1025            let text_width = u16::try_from(legend_text.chars().count()).unwrap_or(u16::MAX);
1026            item_widths.push(text_width);
1027            total_width = total_width.saturating_add(text_width);
1028        }
1029
1030        let start_x = self.calculate_aligned_x(legend_area, total_width.min(legend_area.width));
1031        let mut x_offset = 0u16;
1032
1033        for (idx, slice) in self.slices.iter().enumerate() {
1034            if x_offset >= legend_area.width {
1035                break;
1036            }
1037
1038            let legend_text = self.format_legend_text(slice, total, "  ");
1039            let text_width = item_widths[idx];
1040
1041            let line = Line::from(vec![Span::styled(
1042                legend_text,
1043                Style::default().fg(slice.color),
1044            )]);
1045            let item_area = Rect {
1046                x: start_x + x_offset,
1047                y: legend_area.y,
1048                width: text_width.min(legend_area.width.saturating_sub(x_offset)),
1049                height: 1,
1050            };
1051
1052            line.render(item_area, buf);
1053            x_offset = x_offset.saturating_add(text_width);
1054        }
1055    }
1056
1057    #[allow(clippy::too_many_lines)]
1058    /// Where the pie and the legend are drawn inside `area` (inside the block,
1059    /// if there is one): `(pie_area, legend_area)`.
1060    ///
1061    /// # Example
1062    ///
1063    /// ```
1064    /// use ratatui::{layout::Rect, style::Color};
1065    /// use tui_piechart::{PieChart, PieSlice};
1066    ///
1067    /// let chart = PieChart::new(vec![PieSlice::new("a", 1.0, Color::Red)]);
1068    /// let (pie, legend) = chart.areas(Rect::new(0, 0, 60, 20));
1069    /// assert!(!pie.is_empty() && legend.is_some());
1070    /// ```
1071    #[must_use]
1072    pub fn areas(&self, area: Rect) -> (Rect, Option<Rect>) {
1073        let inner = self.block.as_ref().map_or(area, |b| b.inner(area));
1074        self.calculate_layout(inner)
1075    }
1076
1077    fn calculate_layout(&self, area: Rect) -> (Rect, Option<Rect>) {
1078        if !self.show_legend || area.width < 20 || area.height < 10 {
1079            return (area, None);
1080        }
1081
1082        // Vertical layout uses Left/Right positions, Horizontal layout uses Top/Bottom
1083        match (self.legend_position, self.legend_layout) {
1084            // Left/Right with Vertical layout - proper vertical stacking on sides
1085            (LegendPosition::Left | LegendPosition::Right, LegendLayout::Vertical) => {
1086                let legend_width = self
1087                    .calculate_legend_width()
1088                    .min(area.width / Self::LEGEND_VERTICAL_MAX_RATIO)
1089                    .max(Self::LEGEND_VERTICAL_MIN_WIDTH);
1090                let is_left = matches!(self.legend_position, LegendPosition::Left);
1091                Self::layout_horizontal_split(area, legend_width, is_left)
1092            }
1093            // Top/Bottom with Horizontal layout - single row at top/bottom
1094            (LegendPosition::Top | LegendPosition::Bottom, LegendLayout::Horizontal) => {
1095                let is_top = matches!(self.legend_position, LegendPosition::Top);
1096                Self::layout_vertical_split(area, Self::LEGEND_HORIZONTAL_HEIGHT, is_top)
1097            }
1098            // Fallback: use horizontal layout for incompatible combinations
1099            (LegendPosition::Left | LegendPosition::Right, LegendLayout::Horizontal) => {
1100                // Horizontal layout on sides - allocate limited width
1101                let legend_width = self
1102                    .calculate_legend_horizontal_width()
1103                    .min(
1104                        (area.width * (Self::LEGEND_HORIZONTAL_MAX_RATIO - 1))
1105                            / Self::LEGEND_HORIZONTAL_MAX_RATIO,
1106                    )
1107                    .min(Self::LEGEND_HORIZONTAL_MAX_WIDTH);
1108                let is_left = matches!(self.legend_position, LegendPosition::Left);
1109                Self::layout_horizontal_split(area, legend_width, is_left)
1110            }
1111            (LegendPosition::Top | LegendPosition::Bottom, LegendLayout::Vertical) => {
1112                // Vertical layout at top/bottom - use 2-column grid with minimal height
1113                let legend_height = self.calculate_vertical_grid_height(area.width);
1114                let is_top = matches!(self.legend_position, LegendPosition::Top);
1115                Self::layout_vertical_split(area, legend_height, is_top)
1116            }
1117        }
1118    }
1119
1120    fn calculate_vertical_grid_height(&self, available_width: u16) -> u16 {
1121        // For vertical layout at top/bottom, use 2-column grid
1122        let max_item_width = self.calculate_legend_width();
1123        let columns = (available_width.saturating_sub(Self::LEGEND_PADDING * 2)
1124            / max_item_width.max(1))
1125        .clamp(1, 2);
1126
1127        #[allow(clippy::cast_possible_truncation)]
1128        let num_items = self.slices.len() as u16;
1129
1130        // Calculate rows: ceil(items / columns)
1131        let rows = num_items.div_ceil(columns);
1132        // Each row needs 2 lines (item + spacing), plus account for padding that will be subtracted
1133        (rows * 2 + Self::LEGEND_PADDING).clamp(4, Self::LEGEND_VERTICAL_MAX_HEIGHT)
1134    }
1135
1136    fn layout_horizontal_split(
1137        area: Rect,
1138        legend_width: u16,
1139        legend_on_left: bool,
1140    ) -> (Rect, Option<Rect>) {
1141        if area.width <= legend_width {
1142            return (area, None);
1143        }
1144
1145        let pie_width = area
1146            .width
1147            .saturating_sub(legend_width + Self::LEGEND_SPACING);
1148
1149        if legend_on_left {
1150            (
1151                Rect {
1152                    x: area.x + legend_width + Self::LEGEND_SPACING,
1153                    y: area.y,
1154                    width: pie_width,
1155                    height: area.height,
1156                },
1157                Some(Rect {
1158                    x: area.x,
1159                    y: area.y + Self::LEGEND_PADDING,
1160                    width: legend_width,
1161                    height: area.height.saturating_sub(Self::LEGEND_PADDING * 2),
1162                }),
1163            )
1164        } else {
1165            (
1166                Rect {
1167                    x: area.x,
1168                    y: area.y,
1169                    width: pie_width,
1170                    height: area.height,
1171                },
1172                Some(Rect {
1173                    x: area.x + pie_width + Self::LEGEND_SPACING,
1174                    y: area.y + Self::LEGEND_PADDING,
1175                    width: legend_width,
1176                    height: area.height.saturating_sub(Self::LEGEND_PADDING * 2),
1177                }),
1178            )
1179        }
1180    }
1181
1182    fn layout_vertical_split(
1183        area: Rect,
1184        legend_height: u16,
1185        legend_on_top: bool,
1186    ) -> (Rect, Option<Rect>) {
1187        if area.height <= legend_height {
1188            return (area, None);
1189        }
1190
1191        let pie_height = area
1192            .height
1193            .saturating_sub(legend_height + Self::LEGEND_SPACING);
1194
1195        if legend_on_top {
1196            (
1197                Rect {
1198                    x: area.x,
1199                    y: area.y + legend_height + Self::LEGEND_SPACING,
1200                    width: area.width,
1201                    height: pie_height,
1202                },
1203                Some(Rect {
1204                    x: area.x + Self::LEGEND_PADDING,
1205                    y: area.y + Self::LEGEND_PADDING,
1206                    width: area.width.saturating_sub(Self::LEGEND_PADDING * 2),
1207                    height: legend_height.saturating_sub(Self::LEGEND_PADDING),
1208                }),
1209            )
1210        } else {
1211            (
1212                Rect {
1213                    x: area.x,
1214                    y: area.y,
1215                    width: area.width,
1216                    height: pie_height,
1217                },
1218                Some(Rect {
1219                    x: area.x + Self::LEGEND_PADDING,
1220                    y: area.y + pie_height + Self::LEGEND_SPACING,
1221                    width: area.width.saturating_sub(Self::LEGEND_PADDING * 2),
1222                    height: legend_height.saturating_sub(Self::LEGEND_PADDING),
1223                }),
1224            )
1225        }
1226    }
1227
1228    fn calculate_legend_width(&self) -> u16 {
1229        let total = self.total_value();
1230        let widths = self.slices.iter().map(|s| self.legend_item_width(s, total));
1231
1232        let base = match self.legend_layout {
1233            // For vertical layout, the column is as wide as the widest item.
1234            LegendLayout::Vertical => widths.max().unwrap_or(0),
1235            // For horizontal layout, all items sit on one row.
1236            LegendLayout::Horizontal => widths.fold(0u16, u16::saturating_add),
1237        };
1238
1239        base.saturating_add(2)
1240    }
1241
1242    fn calculate_legend_horizontal_width(&self) -> u16 {
1243        let total = self.total_value();
1244        self.slices
1245            .iter()
1246            .map(|s| self.legend_item_width(s, total))
1247            .fold(0u16, u16::saturating_add)
1248            .saturating_add(2)
1249    }
1250
1251    #[allow(clippy::similar_names)]
1252    fn render_piechart_braille(&self, area: Rect, buf: &mut Buffer) {
1253        // Calculate layout with legend positioning
1254        let (pie_area, legend_area_opt) = self.calculate_layout(area);
1255
1256        // Calculate the center and radius of the pie chart
1257        let center_x_chars = pie_area.width / 2;
1258        let center_y_chars = pie_area.height / 2;
1259
1260        // Each character cell has 2x4 braille dots
1261        let center_x_dots = center_x_chars * 2;
1262        let center_y_dots = center_y_chars * 4;
1263
1264        // Calculate radius in dots
1265        // Braille dots are equally spaced in physical screen space because:
1266        // - Character cells are ~2:1 (height:width)
1267        // - But braille has 2 horizontal dots and 4 vertical dots per character
1268        // - So: horizontal spacing = W/2, vertical spacing = 2W/4 = W/2 (equal!)
1269        let radius = (center_x_dots).min(center_y_dots).saturating_sub(2);
1270
1271        // Create a 2D array to store which slice each braille dot belongs to
1272        let width_dots = pie_area.width * 2;
1273        let height_dots = pie_area.height * 4;
1274
1275        let mut dot_slices: Vec<Vec<Option<usize>>> =
1276            vec![vec![None; width_dots as usize]; height_dots as usize];
1277
1278        // Calculate slice assignments for each dot
1279        let mut cumulative_percent = self.start * 100.0;
1280        for (slice_idx, slice) in self.slices.iter().enumerate() {
1281            let percent = self.percentage(slice);
1282            let (start_angle, end_angle, is_full_circle) =
1283                Self::slice_angles(cumulative_percent, percent);
1284
1285            for dy in 0..height_dots {
1286                for dx in 0..width_dots {
1287                    let rel_x = f64::from(dx) - f64::from(center_x_dots);
1288                    let rel_y = f64::from(dy) - f64::from(center_y_dots);
1289
1290                    // No aspect ratio compensation needed for braille dots
1291                    // They're already equally spaced in physical screen space
1292                    let distance = (rel_x * rel_x + rel_y * rel_y).sqrt();
1293
1294                    if distance <= f64::from(radius) && distance >= self.hole * f64::from(radius) {
1295                        let angle = rel_y.atan2(rel_x);
1296                        if is_full_circle || Self::is_angle_in_slice(angle, start_angle, end_angle)
1297                        {
1298                            dot_slices[dy as usize][dx as usize] = Some(slice_idx);
1299                        }
1300                    }
1301                }
1302            }
1303
1304            cumulative_percent += percent;
1305        }
1306
1307        // Convert dot assignments to braille characters
1308        for char_y in 0..pie_area.height {
1309            for char_x in 0..pie_area.width {
1310                let base_dot_x = char_x * 2;
1311                let base_dot_y = char_y * 4;
1312
1313                // Braille pattern mapping (dots are numbered 1-8)
1314                // Dot positions in a 2x4 grid:
1315                // 1 4
1316                // 2 5
1317                // 3 6
1318                // 7 8
1319                let dot_positions = [
1320                    (0, 0, 0x01), // dot 1
1321                    (0, 1, 0x02), // dot 2
1322                    (0, 2, 0x04), // dot 3
1323                    (1, 0, 0x08), // dot 4
1324                    (1, 1, 0x10), // dot 5
1325                    (1, 2, 0x20), // dot 6
1326                    (0, 3, 0x40), // dot 7
1327                    (1, 3, 0x80), // dot 8
1328                ];
1329
1330                let mut pattern = 0u32;
1331                let mut slice_colors: Vec<(usize, u32)> = Vec::new();
1332
1333                for (dx, dy, bit) in dot_positions {
1334                    let dot_x = base_dot_x + dx;
1335                    let dot_y = base_dot_y + dy;
1336
1337                    if dot_y < height_dots
1338                        && dot_x < width_dots
1339                        && let Some(slice_idx) = dot_slices[dot_y as usize][dot_x as usize]
1340                    {
1341                        pattern |= bit;
1342                        // Track which slice and how many dots
1343                        if let Some(entry) =
1344                            slice_colors.iter_mut().find(|(idx, _)| *idx == slice_idx)
1345                        {
1346                            entry.1 += 1;
1347                        } else {
1348                            slice_colors.push((slice_idx, 1));
1349                        }
1350                    }
1351                }
1352
1353                if pattern > 0 {
1354                    // Use the color of the slice with the most dots in this character
1355                    if let Some((slice_idx, _)) = slice_colors.iter().max_by_key(|(_, count)| count)
1356                    {
1357                        let braille_char = char::from_u32(0x2800 + pattern).unwrap_or('⠀');
1358                        let color = self.slices[*slice_idx].color;
1359
1360                        let cell = &mut buf[(pie_area.x + char_x, pie_area.y + char_y)];
1361                        cell.set_char(braille_char).set_fg(color);
1362                    }
1363                }
1364            }
1365        }
1366
1367        self.draw_center(pie_area, buf);
1368
1369        // Draw legend if enabled
1370        if let Some(legend_area) = legend_area_opt {
1371            self.render_legend(buf, legend_area);
1372        }
1373    }
1374}
1375
1376#[cfg(test)]
1377#[allow(clippy::float_cmp)]
1378#[allow(unnameable_test_items)]
1379mod tests {
1380    use super::*;
1381
1382    #[test]
1383    fn pie_slice_new() {
1384        let slice = PieSlice::new("Test", 50.0, Color::Red);
1385        assert_eq!(slice.label(), "Test");
1386        assert_eq!(slice.value(), 50.0);
1387        assert_eq!(slice.color(), Color::Red);
1388    }
1389
1390    #[test]
1391    fn piechart_new() {
1392        let slices = vec![
1393            PieSlice::new("A", 30.0, Color::Red),
1394            PieSlice::new("B", 70.0, Color::Blue),
1395        ];
1396        let piechart = PieChart::new(slices.clone());
1397        assert_eq!(piechart.slices, slices);
1398    }
1399
1400    #[test]
1401    fn piechart_default() {
1402        let piechart = PieChart::default();
1403        assert_eq!(piechart.slices, [] as [PieSlice<'_>; 0]);
1404        assert!(piechart.show_legend);
1405        assert!(piechart.show_percentages);
1406    }
1407
1408    #[test]
1409    fn piechart_slices() {
1410        let slices = vec![PieSlice::new("Test", 100.0, Color::Green)];
1411        let piechart = PieChart::default().slices(slices.clone());
1412        assert_eq!(piechart.slices, slices);
1413    }
1414
1415    #[test]
1416    fn piechart_style() {
1417        let style = Style::default().fg(Color::Red);
1418        let piechart = PieChart::default().style(style);
1419        assert_eq!(piechart.style, style);
1420    }
1421
1422    #[test]
1423    fn piechart_show_legend() {
1424        let piechart = PieChart::default().show_legend(false);
1425        assert!(!piechart.show_legend);
1426    }
1427
1428    #[test]
1429    fn piechart_show_percentages() {
1430        let piechart = PieChart::default().show_percentages(false);
1431        assert!(!piechart.show_percentages);
1432    }
1433
1434    #[test]
1435    fn piechart_pie_char() {
1436        let piechart = PieChart::default().pie_char('█');
1437        assert_eq!(piechart.pie_char, '█');
1438    }
1439
1440    #[test]
1441    fn piechart_total_value() {
1442        let slices = vec![
1443            PieSlice::new("A", 30.0, Color::Red),
1444            PieSlice::new("B", 70.0, Color::Blue),
1445        ];
1446        let piechart = PieChart::new(slices);
1447        assert_eq!(piechart.total_value(), 100.0);
1448    }
1449
1450    #[test]
1451    fn piechart_percentage() {
1452        let slices = vec![
1453            PieSlice::new("A", 30.0, Color::Red),
1454            PieSlice::new("B", 70.0, Color::Blue),
1455        ];
1456        let piechart = PieChart::new(slices);
1457        assert_eq!(
1458            piechart.percentage(&PieSlice::new("A", 30.0, Color::Red)),
1459            30.0
1460        );
1461    }
1462
1463    // Render tests - using macros for common patterns
1464    render_empty_test!(piechart_render_empty_area, PieChart::default());
1465
1466    render_with_size_test!(
1467        piechart_render_with_block,
1468        {
1469            let slices = vec![PieSlice::new("Test", 100.0, Color::Red)];
1470            PieChart::new(slices).block(Block::bordered())
1471        },
1472        width: 20,
1473        height: 10
1474    );
1475
1476    render_test!(
1477        piechart_render_basic,
1478        {
1479            let slices = vec![
1480                PieSlice::new("Rust", 45.0, Color::Red),
1481                PieSlice::new("Go", 30.0, Color::Blue),
1482                PieSlice::new("Python", 25.0, Color::Green),
1483            ];
1484            PieChart::new(slices)
1485        },
1486        Rect::new(0, 0, 40, 20)
1487    );
1488
1489    #[test]
1490    fn piechart_styled_trait() {
1491        use ratatui::style::Stylize;
1492        let piechart = PieChart::default().red();
1493        assert_eq!(piechart.style.fg, Some(Color::Red));
1494    }
1495
1496    #[test]
1497    fn piechart_with_multiple_slices() {
1498        let slices = vec![
1499            PieSlice::new("A", 25.0, Color::Red),
1500            PieSlice::new("B", 25.0, Color::Blue),
1501            PieSlice::new("C", 25.0, Color::Green),
1502            PieSlice::new("D", 25.0, Color::Yellow),
1503        ];
1504        let piechart = PieChart::new(slices);
1505        assert_eq!(piechart.total_value(), 100.0);
1506    }
1507
1508    // Using render macro for the visual test
1509    render_with_size_test!(
1510        piechart_multi_slice_render,
1511        {
1512            let slices = vec![
1513                PieSlice::new("A", 25.0, Color::Red),
1514                PieSlice::new("B", 25.0, Color::Blue),
1515                PieSlice::new("C", 25.0, Color::Green),
1516                PieSlice::new("D", 25.0, Color::Yellow),
1517            ];
1518            PieChart::new(slices)
1519        },
1520        width: 50,
1521        height: 30
1522    );
1523
1524    #[test]
1525    fn piechart_zero_values() {
1526        let slices = vec![
1527            PieSlice::new("A", 0.0, Color::Red),
1528            PieSlice::new("B", 0.0, Color::Blue),
1529        ];
1530        let piechart = PieChart::new(slices);
1531        assert_eq!(piechart.total_value(), 0.0);
1532    }
1533
1534    #[test]
1535    fn piechart_method_chaining() {
1536        use ratatui::widgets::Block;
1537
1538        let slices = vec![PieSlice::new("Test", 100.0, Color::Red)];
1539        let piechart = PieChart::new(slices)
1540            .show_legend(true)
1541            .show_percentages(true)
1542            .pie_char('█')
1543            .block(Block::bordered().title("Test"))
1544            .style(Style::default().fg(Color::White));
1545
1546        assert!(piechart.show_legend);
1547        assert!(piechart.show_percentages);
1548        assert_eq!(piechart.pie_char, '█');
1549        assert!(piechart.block.is_some());
1550        assert_eq!(piechart.style.fg, Some(Color::White));
1551    }
1552
1553    #[test]
1554    fn piechart_custom_symbols() {
1555        use crate::symbols;
1556
1557        let piechart = PieChart::default().pie_char(symbols::PIE_CHAR_BLOCK);
1558        assert_eq!(piechart.pie_char, '█');
1559
1560        let piechart = PieChart::default().pie_char(symbols::PIE_CHAR_CIRCLE);
1561        assert_eq!(piechart.pie_char, '◉');
1562
1563        let piechart = PieChart::default().pie_char(symbols::PIE_CHAR_SQUARE);
1564        assert_eq!(piechart.pie_char, '■');
1565    }
1566
1567    #[test]
1568    fn piechart_is_angle_in_slice() {
1569        use std::f64::consts::PI;
1570
1571        // Test angle in range
1572        assert!(PieChart::is_angle_in_slice(PI / 4.0, 0.0, PI / 2.0));
1573
1574        // Test angle outside range
1575        assert!(!PieChart::is_angle_in_slice(PI, 0.0, PI / 2.0));
1576
1577        // Test wrap around
1578        assert!(PieChart::is_angle_in_slice(0.1, 1.5 * PI, 0.5));
1579    }
1580
1581    // --- Resolution ---
1582
1583    matches_test!(
1584        piechart_resolution_standard,
1585        PieChart::default()
1586            .resolution(Resolution::Standard)
1587            .resolution,
1588        Resolution::Standard
1589    );
1590    matches_test!(
1591        piechart_resolution_braille,
1592        PieChart::default()
1593            .resolution(Resolution::Braille)
1594            .resolution,
1595        Resolution::Braille
1596    );
1597    matches_test!(
1598        piechart_high_resolution_true,
1599        PieChart::default().high_resolution(true).resolution,
1600        Resolution::Braille
1601    );
1602    matches_test!(
1603        piechart_high_resolution_false,
1604        PieChart::default().high_resolution(false).resolution,
1605        Resolution::Standard
1606    );
1607
1608    // --- Legend position / layout / alignment setters ---
1609
1610    matches_test!(
1611        piechart_legend_position_left,
1612        PieChart::default()
1613            .legend_position(LegendPosition::Left)
1614            .legend_position,
1615        LegendPosition::Left
1616    );
1617    matches_test!(
1618        piechart_legend_position_right,
1619        PieChart::default()
1620            .legend_position(LegendPosition::Right)
1621            .legend_position,
1622        LegendPosition::Right
1623    );
1624    matches_test!(
1625        piechart_legend_position_top,
1626        PieChart::default()
1627            .legend_position(LegendPosition::Top)
1628            .legend_position,
1629        LegendPosition::Top
1630    );
1631    matches_test!(
1632        piechart_legend_position_bottom,
1633        PieChart::default()
1634            .legend_position(LegendPosition::Bottom)
1635            .legend_position,
1636        LegendPosition::Bottom
1637    );
1638    matches_test!(
1639        piechart_legend_layout_horizontal,
1640        PieChart::default()
1641            .legend_layout(LegendLayout::Horizontal)
1642            .legend_layout,
1643        LegendLayout::Horizontal
1644    );
1645    matches_test!(
1646        piechart_legend_layout_vertical,
1647        PieChart::default()
1648            .legend_layout(LegendLayout::Vertical)
1649            .legend_layout,
1650        LegendLayout::Vertical
1651    );
1652    matches_test!(
1653        piechart_legend_alignment_left,
1654        PieChart::default()
1655            .legend_alignment(LegendAlignment::Left)
1656            .legend_alignment,
1657        LegendAlignment::Left
1658    );
1659    matches_test!(
1660        piechart_legend_alignment_center,
1661        PieChart::default()
1662            .legend_alignment(LegendAlignment::Center)
1663            .legend_alignment,
1664        LegendAlignment::Center
1665    );
1666    matches_test!(
1667        piechart_legend_alignment_right,
1668        PieChart::default()
1669            .legend_alignment(LegendAlignment::Right)
1670            .legend_alignment,
1671        LegendAlignment::Right
1672    );
1673
1674    // --- legend_marker setter ---
1675
1676    #[test]
1677    fn piechart_legend_marker_custom() {
1678        use crate::symbols::LEGEND_MARKER;
1679        let piechart = PieChart::default().legend_marker(LEGEND_MARKER);
1680        assert_eq!(piechart.legend_marker, LEGEND_MARKER);
1681    }
1682
1683    // --- format_legend_text ---
1684
1685    #[test]
1686    fn piechart_format_legend_text_with_percentage() {
1687        let slices = vec![
1688            PieSlice::new("Rust", 50.0, Color::Red),
1689            PieSlice::new("Go", 50.0, Color::Blue),
1690        ];
1691        let piechart = PieChart::new(slices.clone()).show_percentages(true);
1692        let text = piechart.format_legend_text(&slices[0], 100.0, "");
1693        assert!(text.contains("Rust"));
1694        assert!(text.contains("50.0%"));
1695    }
1696
1697    #[test]
1698    fn piechart_format_legend_text_without_percentage() {
1699        let slices = vec![PieSlice::new("Rust", 50.0, Color::Red)];
1700        let piechart = PieChart::new(slices.clone()).show_percentages(false);
1701        let text = piechart.format_legend_text(&slices[0], 100.0, "");
1702        assert!(text.contains("Rust"));
1703        assert!(!text.contains('%'));
1704    }
1705
1706    #[test]
1707    fn piechart_format_legend_text_zero_total() {
1708        let slices = vec![PieSlice::new("X", 0.0, Color::Red)];
1709        let piechart = PieChart::new(slices.clone()).show_percentages(true);
1710        let text = piechart.format_legend_text(&slices[0], 0.0, "");
1711        assert!(text.contains("0.0%"));
1712    }
1713
1714    // --- calculate_aligned_x ---
1715
1716    #[test]
1717    fn piechart_calculate_aligned_x_left() {
1718        let slices = vec![PieSlice::new("A", 100.0, Color::Red)];
1719        let piechart = PieChart::new(slices).legend_alignment(LegendAlignment::Left);
1720        let area = Rect::new(5, 0, 20, 10);
1721        assert_eq!(piechart.calculate_aligned_x(area, 10), 5);
1722    }
1723
1724    #[test]
1725    fn piechart_calculate_aligned_x_center() {
1726        let slices = vec![PieSlice::new("A", 100.0, Color::Red)];
1727        let piechart = PieChart::new(slices).legend_alignment(LegendAlignment::Center);
1728        let area = Rect::new(0, 0, 20, 10);
1729        // (20 - 10) / 2 = 5
1730        assert_eq!(piechart.calculate_aligned_x(area, 10), 5);
1731    }
1732
1733    #[test]
1734    fn piechart_calculate_aligned_x_right() {
1735        let slices = vec![PieSlice::new("A", 100.0, Color::Red)];
1736        let piechart = PieChart::new(slices).legend_alignment(LegendAlignment::Right);
1737        let area = Rect::new(0, 0, 20, 10);
1738        // 20 - 10 = 10
1739        assert_eq!(piechart.calculate_aligned_x(area, 10), 10);
1740    }
1741
1742    // --- Braille render ---
1743
1744    render_test!(
1745        piechart_render_braille,
1746        {
1747            let slices = vec![
1748                PieSlice::new("Rust", 60.0, Color::Red),
1749                PieSlice::new("Go", 40.0, Color::Blue),
1750            ];
1751            PieChart::new(slices).resolution(Resolution::Braille)
1752        },
1753        Rect::new(0, 0, 40, 20)
1754    );
1755
1756    render_test!(
1757        piechart_render_braille_with_legend,
1758        {
1759            let slices = vec![
1760                PieSlice::new("Rust", 60.0, Color::Red),
1761                PieSlice::new("Go", 40.0, Color::Blue),
1762            ];
1763            PieChart::new(slices)
1764                .resolution(Resolution::Braille)
1765                .show_legend(true)
1766        },
1767        Rect::new(0, 0, 40, 20)
1768    );
1769
1770    // --- Legend layout render paths ---
1771
1772    render_test!(
1773        piechart_render_legend_left,
1774        {
1775            let slices = vec![
1776                PieSlice::new("Alpha", 50.0, Color::Red),
1777                PieSlice::new("Beta", 50.0, Color::Blue),
1778            ];
1779            PieChart::new(slices)
1780                .show_legend(true)
1781                .legend_position(LegendPosition::Left)
1782                .legend_layout(LegendLayout::Vertical)
1783        },
1784        Rect::new(0, 0, 60, 20)
1785    );
1786
1787    render_test!(
1788        piechart_render_legend_right,
1789        {
1790            let slices = vec![
1791                PieSlice::new("Alpha", 50.0, Color::Red),
1792                PieSlice::new("Beta", 50.0, Color::Blue),
1793            ];
1794            PieChart::new(slices)
1795                .show_legend(true)
1796                .legend_position(LegendPosition::Right)
1797                .legend_layout(LegendLayout::Vertical)
1798        },
1799        Rect::new(0, 0, 60, 20)
1800    );
1801
1802    render_test!(
1803        piechart_render_legend_top_horizontal,
1804        {
1805            let slices = vec![
1806                PieSlice::new("Alpha", 50.0, Color::Red),
1807                PieSlice::new("Beta", 50.0, Color::Blue),
1808            ];
1809            PieChart::new(slices)
1810                .show_legend(true)
1811                .legend_position(LegendPosition::Top)
1812                .legend_layout(LegendLayout::Horizontal)
1813        },
1814        Rect::new(0, 0, 60, 20)
1815    );
1816
1817    render_test!(
1818        piechart_render_legend_bottom_horizontal,
1819        {
1820            let slices = vec![
1821                PieSlice::new("Alpha", 50.0, Color::Red),
1822                PieSlice::new("Beta", 50.0, Color::Blue),
1823            ];
1824            PieChart::new(slices)
1825                .show_legend(true)
1826                .legend_position(LegendPosition::Bottom)
1827                .legend_layout(LegendLayout::Horizontal)
1828        },
1829        Rect::new(0, 0, 60, 20)
1830    );
1831
1832    render_test!(
1833        piechart_render_legend_top_vertical,
1834        {
1835            let slices = vec![
1836                PieSlice::new("Alpha", 50.0, Color::Red),
1837                PieSlice::new("Beta", 50.0, Color::Blue),
1838            ];
1839            PieChart::new(slices)
1840                .show_legend(true)
1841                .legend_position(LegendPosition::Top)
1842                .legend_layout(LegendLayout::Vertical)
1843        },
1844        Rect::new(0, 0, 60, 20)
1845    );
1846
1847    render_test!(
1848        piechart_render_legend_bottom_vertical,
1849        {
1850            let slices = vec![
1851                PieSlice::new("Alpha", 50.0, Color::Red),
1852                PieSlice::new("Beta", 50.0, Color::Blue),
1853            ];
1854            PieChart::new(slices)
1855                .show_legend(true)
1856                .legend_position(LegendPosition::Bottom)
1857                .legend_layout(LegendLayout::Vertical)
1858        },
1859        Rect::new(0, 0, 60, 20)
1860    );
1861
1862    render_test!(
1863        piechart_render_legend_left_horizontal,
1864        {
1865            let slices = vec![
1866                PieSlice::new("Alpha", 50.0, Color::Red),
1867                PieSlice::new("Beta", 50.0, Color::Blue),
1868            ];
1869            PieChart::new(slices)
1870                .show_legend(true)
1871                .legend_position(LegendPosition::Left)
1872                .legend_layout(LegendLayout::Horizontal)
1873        },
1874        Rect::new(0, 0, 60, 20)
1875    );
1876
1877    render_test!(
1878        piechart_render_legend_right_horizontal,
1879        {
1880            let slices = vec![
1881                PieSlice::new("Alpha", 50.0, Color::Red),
1882                PieSlice::new("Beta", 50.0, Color::Blue),
1883            ];
1884            PieChart::new(slices)
1885                .show_legend(true)
1886                .legend_position(LegendPosition::Right)
1887                .legend_layout(LegendLayout::Horizontal)
1888        },
1889        Rect::new(0, 0, 60, 20)
1890    );
1891
1892    // --- Legend with percentages ---
1893
1894    render_test!(
1895        piechart_render_legend_with_percentages,
1896        {
1897            let slices = vec![
1898                PieSlice::new("Rust", 45.0, Color::Red),
1899                PieSlice::new("Go", 30.0, Color::Blue),
1900                PieSlice::new("Python", 25.0, Color::Green),
1901            ];
1902            PieChart::new(slices)
1903                .show_legend(true)
1904                .show_percentages(true)
1905        },
1906        Rect::new(0, 0, 60, 20)
1907    );
1908
1909    // Legend alignment render paths
1910    render_test!(
1911        piechart_render_legend_alignment_center,
1912        {
1913            let slices = vec![
1914                PieSlice::new("A", 50.0, Color::Red),
1915                PieSlice::new("B", 50.0, Color::Blue),
1916            ];
1917            PieChart::new(slices)
1918                .show_legend(true)
1919                .legend_alignment(LegendAlignment::Center)
1920        },
1921        Rect::new(0, 0, 60, 20)
1922    );
1923
1924    render_test!(
1925        piechart_render_legend_alignment_right,
1926        {
1927            let slices = vec![
1928                PieSlice::new("A", 50.0, Color::Red),
1929                PieSlice::new("B", 50.0, Color::Blue),
1930            ];
1931            PieChart::new(slices)
1932                .show_legend(true)
1933                .legend_alignment(LegendAlignment::Right)
1934        },
1935        Rect::new(0, 0, 60, 20)
1936    );
1937
1938    // --- calculate_layout: small area returns no legend ---
1939
1940    #[test]
1941    fn piechart_layout_too_small_no_legend() {
1942        let slices = vec![PieSlice::new("A", 100.0, Color::Red)];
1943        let piechart = PieChart::new(slices).show_legend(true);
1944        // area too narrow (< 20)
1945        let area = Rect::new(0, 0, 10, 5);
1946        let (pie_area, legend_opt) = piechart.calculate_layout(area);
1947        assert_eq!(pie_area, area);
1948        assert!(legend_opt.is_none());
1949    }
1950
1951    #[test]
1952    fn piechart_layout_show_legend_false_no_legend() {
1953        let slices = vec![PieSlice::new("A", 100.0, Color::Red)];
1954        let piechart = PieChart::new(slices).show_legend(false);
1955        let area = Rect::new(0, 0, 60, 20);
1956        let (pie_area, legend_opt) = piechart.calculate_layout(area);
1957        assert_eq!(pie_area, area);
1958        assert!(legend_opt.is_none());
1959    }
1960
1961    // --- Render with no slices (empty) ---
1962
1963    render_empty_test!(piechart_render_empty_slices, PieChart::default());
1964
1965    // --- Render single slice ---
1966
1967    render_test!(
1968        piechart_render_single_slice,
1969        PieChart::new(vec![PieSlice::new("Only", 100.0, Color::Cyan)]),
1970        Rect::new(0, 0, 30, 15)
1971    );
1972
1973    // --- Percentage zero total ---
1974
1975    #[test]
1976    fn piechart_percentage_zero_total() {
1977        let slices = vec![PieSlice::new("A", 0.0, Color::Red)];
1978        let piechart = PieChart::new(slices.clone());
1979        assert_eq!(piechart.percentage(&slices[0]), 0.0);
1980    }
1981
1982    // --- calculate_legend_width Vertical: zero total with percentages (line 1041) ---
1983    // Must call the private method directly: render_piechart returns early when total == 0,
1984    // so the zero-total branch inside calculate_legend_width is only reachable this way.
1985
1986    #[test]
1987    fn piechart_calculate_legend_width_vertical_zero_total_with_percentages() {
1988        let slices = vec![
1989            PieSlice::new("A", 0.0, Color::Red),
1990            PieSlice::new("B", 0.0, Color::Blue),
1991        ];
1992        let piechart = PieChart::new(slices)
1993            .legend_layout(LegendLayout::Vertical)
1994            .show_percentages(true);
1995        let width = piechart.calculate_legend_width();
1996        // Each label shows "• A 0.0%  " — width must be > 0
1997        assert!(width > 0);
1998    }
1999
2000    render_test!(
2001        piechart_render_legend_vertical_zero_total_with_percentages,
2002        PieChart::new(vec![
2003            PieSlice::new("A", 0.0, Color::Red),
2004            PieSlice::new("B", 0.0, Color::Blue),
2005        ])
2006        .show_legend(true)
2007        .show_percentages(true)
2008        .legend_position(LegendPosition::Right)
2009        .legend_layout(LegendLayout::Vertical),
2010        Rect::new(0, 0, 60, 20)
2011    );
2012
2013    // --- calculate_legend_width Vertical: show_percentages=false (line 1045) ---
2014
2015    render_test!(
2016        piechart_render_legend_vertical_no_percentages,
2017        PieChart::new(vec![
2018            PieSlice::new("Rust", 60.0, Color::Red),
2019            PieSlice::new("Go", 40.0, Color::Blue),
2020        ])
2021        .show_legend(true)
2022        .show_percentages(false)
2023        .legend_position(LegendPosition::Right)
2024        .legend_layout(LegendLayout::Vertical),
2025        Rect::new(0, 0, 60, 20)
2026    );
2027
2028    // --- render_piechart: total <= 0.0 guard (line 631) ---
2029
2030    render_test!(
2031        piechart_render_all_zero_values,
2032        PieChart::new(vec![
2033            PieSlice::new("A", 0.0, Color::Red),
2034            PieSlice::new("B", 0.0, Color::Blue),
2035        ]),
2036        Rect::new(0, 0, 40, 20)
2037    );
2038
2039    // --- render_slice: percent <= 0.0 guard (line 691) ---
2040
2041    render_test!(
2042        piechart_render_zero_value_slice_in_mix,
2043        PieChart::new(vec![
2044            PieSlice::new("A", 100.0, Color::Red),
2045            PieSlice::new("B", 0.0, Color::Blue),
2046        ]),
2047        Rect::new(0, 0, 40, 20)
2048    );
2049
2050    // --- render_slice: radius == 0 guard — tiny 1×1 area (line 691) ---
2051
2052    render_test!(
2053        piechart_render_tiny_area_radius_zero,
2054        PieChart::new(vec![PieSlice::new("A", 100.0, Color::Red)]),
2055        Rect::new(0, 0, 1, 1)
2056    );
2057
2058    // --- render_vertical_legend: overflow break (line 814) ---
2059    // Many slices in a tall-enough outer area but tiny legend height forces the break.
2060
2061    render_test!(
2062        piechart_render_vertical_legend_overflow,
2063        PieChart::new(vec![
2064            PieSlice::new("Slice1", 10.0, Color::Red),
2065            PieSlice::new("Slice2", 10.0, Color::Blue),
2066            PieSlice::new("Slice3", 10.0, Color::Green),
2067            PieSlice::new("Slice4", 10.0, Color::Yellow),
2068            PieSlice::new("Slice5", 10.0, Color::Cyan),
2069            PieSlice::new("Slice6", 10.0, Color::Magenta),
2070            PieSlice::new("Slice7", 10.0, Color::White),
2071            PieSlice::new("Slice8", 10.0, Color::Red),
2072            PieSlice::new("Slice9", 10.0, Color::Blue),
2073            PieSlice::new("Slice10", 10.0, Color::Green),
2074        ])
2075        .show_legend(true)
2076        .legend_position(LegendPosition::Right)
2077        .legend_layout(LegendLayout::Vertical),
2078        // height=12 → legend area height ≈ 10 → only 5 items fit (each takes 2 rows)
2079        Rect::new(0, 0, 60, 12)
2080    );
2081
2082    // --- render_horizontal_legend: overflow break (line 854) ---
2083    // Many slices with a very narrow area forces the x_offset >= width break.
2084
2085    render_test!(
2086        piechart_render_horizontal_legend_overflow,
2087        PieChart::new(vec![
2088            PieSlice::new("LongLabelA", 20.0, Color::Red),
2089            PieSlice::new("LongLabelB", 20.0, Color::Blue),
2090            PieSlice::new("LongLabelC", 20.0, Color::Green),
2091            PieSlice::new("LongLabelD", 20.0, Color::Yellow),
2092            PieSlice::new("LongLabelE", 20.0, Color::Cyan),
2093        ])
2094        .show_legend(true)
2095        .legend_position(LegendPosition::Bottom)
2096        .legend_layout(LegendLayout::Horizontal),
2097        // width=22 is very narrow relative to the label sizes
2098        Rect::new(0, 0, 22, 15)
2099    );
2100
2101    // --- layout_horizontal_split: early return when area.width <= legend_width (line 988) ---
2102
2103    #[test]
2104    fn piechart_layout_horizontal_split_too_narrow() {
2105        let area = Rect::new(0, 0, 5, 20);
2106        // legend_width (100) > area.width (5) → early return
2107        let (pie_area, legend_opt) = PieChart::<'_>::layout_horizontal_split(area, 100, true);
2108        assert_eq!(pie_area, area);
2109        assert!(legend_opt.is_none());
2110    }
2111
2112    // --- layout_vertical_split: early return when area.height <= legend_height (line 1041) ---
2113
2114    #[test]
2115    fn piechart_layout_vertical_split_too_short() {
2116        let area = Rect::new(0, 0, 60, 3);
2117        // legend_height (100) > area.height (3) → early return
2118        let (pie_area, legend_opt) = PieChart::<'_>::layout_vertical_split(area, 100, true);
2119        assert_eq!(pie_area, area);
2120        assert!(legend_opt.is_none());
2121    }
2122
2123    // --- calculate_legend_width: LegendLayout::Horizontal branch (lines 1057-1076) ---
2124    // This branch is only reachable by calling the method directly in tests.
2125
2126    #[test]
2127    fn piechart_calculate_legend_width_horizontal_with_percentages() {
2128        let slices = vec![
2129            PieSlice::new("Rust", 60.0, Color::Red),
2130            PieSlice::new("Go", 40.0, Color::Blue),
2131        ];
2132        let piechart = PieChart::new(slices)
2133            .legend_layout(LegendLayout::Horizontal)
2134            .show_percentages(true);
2135        let width = piechart.calculate_legend_width();
2136        assert!(width > 0);
2137    }
2138
2139    #[test]
2140    fn piechart_calculate_legend_width_horizontal_without_percentages() {
2141        let slices = vec![
2142            PieSlice::new("Alpha", 50.0, Color::Red),
2143            PieSlice::new("Beta", 50.0, Color::Blue),
2144        ];
2145        let piechart = PieChart::new(slices)
2146            .legend_layout(LegendLayout::Horizontal)
2147            .show_percentages(false);
2148        let width = piechart.calculate_legend_width();
2149        assert!(width > 0);
2150    }
2151
2152    #[test]
2153    fn piechart_calculate_legend_width_horizontal_zero_total() {
2154        let slices = vec![
2155            PieSlice::new("A", 0.0, Color::Red),
2156            PieSlice::new("B", 0.0, Color::Blue),
2157        ];
2158        let piechart = PieChart::new(slices)
2159            .legend_layout(LegendLayout::Horizontal)
2160            .show_percentages(true);
2161        let width = piechart.calculate_legend_width();
2162        // Zero total → 0.0% for each item, but width is still > 0
2163        assert!(width > 0);
2164    }
2165
2166    // --- calculate_legend_horizontal_width: zero total branch (lines 1090, 1094) ---
2167
2168    #[test]
2169    fn piechart_calculate_legend_horizontal_width_zero_total() {
2170        let slices = vec![
2171            PieSlice::new("X", 0.0, Color::Red),
2172            PieSlice::new("Y", 0.0, Color::Blue),
2173        ];
2174        let piechart = PieChart::new(slices).show_percentages(true);
2175        let width = piechart.calculate_legend_horizontal_width();
2176        assert!(width > 0);
2177    }
2178
2179    #[test]
2180    fn piechart_calculate_legend_horizontal_width_without_percentages() {
2181        let slices = vec![PieSlice::new("Item", 100.0, Color::Green)];
2182        let piechart = PieChart::new(slices).show_percentages(false);
2183        let width = piechart.calculate_legend_horizontal_width();
2184        assert!(width > 0);
2185    }
2186
2187    // --- calculate_vertical_grid_height: very narrow width clamps columns to 1 ---
2188
2189    #[test]
2190    fn piechart_calculate_vertical_grid_height_narrow() {
2191        let slices = vec![
2192            PieSlice::new("A", 50.0, Color::Red),
2193            PieSlice::new("B", 50.0, Color::Blue),
2194        ];
2195        let piechart = PieChart::new(slices);
2196        // width=1 → columns clamped to 1 → all items stack in one column
2197        let height = piechart.calculate_vertical_grid_height(1);
2198        assert!(height >= 4);
2199    }
2200
2201    // --- value_percent / slice_angles helpers ---
2202
2203    #[test]
2204    fn piechart_value_percent_positive_total() {
2205        assert_eq!(PieChart::value_percent(25.0, 200.0), 12.5);
2206    }
2207
2208    #[test]
2209    fn piechart_value_percent_zero_total() {
2210        assert_eq!(PieChart::value_percent(25.0, 0.0), 0.0);
2211    }
2212
2213    #[test]
2214    fn piechart_value_percent_negative_total() {
2215        // Non-positive totals are treated as empty to avoid nonsensical output.
2216        assert_eq!(PieChart::value_percent(25.0, -5.0), 0.0);
2217    }
2218
2219    #[test]
2220    fn piechart_slice_angles_full_circle_flag() {
2221        let (_, _, is_full) = PieChart::slice_angles(0.0, 100.0);
2222        assert!(is_full);
2223    }
2224
2225    #[test]
2226    fn piechart_slice_angles_partial_not_full() {
2227        let (start, end, is_full) = PieChart::slice_angles(0.0, 50.0);
2228        assert!(!is_full);
2229        assert!((end - start - PI).abs() < 1e-9);
2230    }
2231
2232    #[test]
2233    fn piechart_legend_item_width_matches_text() {
2234        let slices = vec![PieSlice::new("Rust", 50.0, Color::Red)];
2235        let chart = PieChart::new(slices.clone()).show_percentages(true);
2236        let expected = chart
2237            .format_legend_text(&slices[0], 100.0, "  ")
2238            .chars()
2239            .count();
2240        assert_eq!(
2241            usize::from(chart.legend_item_width(&slices[0], 100.0)),
2242            expected
2243        );
2244    }
2245
2246    #[test]
2247    fn piechart_legend_item_width_unicode_label() {
2248        // Multi-byte labels must be measured by character count, not byte length.
2249        let slices = vec![PieSlice::new("日本語", 100.0, Color::Red)];
2250        let chart = PieChart::new(slices.clone()).show_percentages(false);
2251        // "■ 日本語  " => marker(1) + space(1) + 3 chars + 2 trailing spaces = 7
2252        assert_eq!(chart.legend_item_width(&slices[0], 100.0), 7);
2253    }
2254
2255    // --- Full circle rendering (regression for issue #2) ---
2256
2257    #[test]
2258    fn piechart_full_circle_fills_more_than_a_line() {
2259        fn filled_cells(chart: &PieChart) -> usize {
2260            let mut buffer = Buffer::empty(Rect::new(0, 0, 30, 15));
2261            Widget::render(chart, buffer.area, &mut buffer);
2262            buffer
2263                .content
2264                .iter()
2265                .filter(|c| !c.symbol().trim().is_empty())
2266                .count()
2267        }
2268
2269        let standard = PieChart::new(vec![PieSlice::new("Only", 100.0, Color::Green)])
2270            .show_legend(false)
2271            .show_percentages(false);
2272        assert!(filled_cells(&standard) > 30);
2273
2274        let braille = PieChart::new(vec![PieSlice::new("Only", 100.0, Color::Green)])
2275            .resolution(Resolution::Braille)
2276            .show_legend(false)
2277            .show_percentages(false);
2278        assert!(filled_cells(&braille) > 30);
2279    }
2280}