1use ratatui::{buffer::Buffer, layout::Rect, style::Color, style::Modifier};
11use tui_piechart::{PieChart, PieSlice};
12
13use crate::util::format_compact;
14
15#[derive(Debug, Clone)]
34pub struct Pie<'a> {
35 chart: PieChart<'a>,
36 hidden: Vec<usize>,
37}
38
39impl<'a> Pie<'a> {
40 pub fn new(chart: PieChart<'a>) -> Self {
42 Self {
43 chart,
44 hidden: Vec::new(),
45 }
46 }
47
48 #[must_use]
51 pub fn hidden(mut self, hidden: impl IntoIterator<Item = usize>) -> Self {
52 self.hidden = hidden.into_iter().collect();
53 self
54 }
55
56 fn slices(&self, color: impl Fn(usize, &PieSlice<'a>) -> Color) -> Vec<PieSlice<'a>> {
57 self.chart
58 .slice_list()
59 .iter()
60 .enumerate()
61 .map(|(i, s)| {
62 let v = if self.hidden.contains(&i) {
63 0.0
64 } else {
65 s.value()
66 };
67 PieSlice::new(s.label(), v, color(i, s))
68 })
69 .collect()
70 }
71
72 fn render_into(&self, area: Rect, buf: &mut Buffer) {
73 let area = area.intersection(buf.area);
74 let visible = self.chart.clone().slices(self.slices(|_, s| s.color()));
75 ratatui::widgets::Widget::render(&visible, area, buf);
76 if area.is_empty() {
77 return;
78 }
79 let (pie, legend) = self.chart.areas(area);
80 let marks = if crate::interact::recording() || !self.hidden.is_empty() {
82 self.owners(area, pie, legend)
83 } else {
84 return;
85 };
86 for (i, rect) in &marks.legend {
87 if self.hidden.contains(i) {
88 for x in rect.left()..rect.right() {
89 let c = &mut buf[(x, rect.y)];
90 c.set_style(
91 ratatui::style::Style::default()
92 .add_modifier(Modifier::DIM | Modifier::CROSSED_OUT),
93 );
94 }
95 }
96 crate::interact::record_legend(*rect, *i, self.chart.slice_list()[*i].label());
97 }
98 let total: f64 = self
99 .chart
100 .slice_list()
101 .iter()
102 .enumerate()
103 .filter(|(i, _)| !self.hidden.contains(i))
104 .map(|(_, s)| s.value().max(0.0))
105 .sum();
106 crate::interact::record_grid(
107 pie,
108 &marks.pie,
109 |i| i,
110 |i| {
111 let s = &self.chart.slice_list()[i];
112 let pct = if total > 0.0 {
113 s.value().max(0.0) / total * 100.0
114 } else {
115 0.0
116 };
117 (
118 s.label().to_string(),
119 vec![format_compact(s.value()), format!("{pct:.1}%")],
120 )
121 },
122 );
123 }
124
125 fn owners(&self, area: Rect, pie: Rect, legend: Option<Rect>) -> Owners {
127 let key = |i: usize| Color::Rgb((i >> 8) as u8 + 1, i as u8, 77);
128 let sentinel = self.chart.clone().slices(self.slices(|i, _| key(i)));
129 let mut scratch = Buffer::empty(area);
130 ratatui::widgets::Widget::render(&sentinel, area, &mut scratch);
131 let n = self.chart.slice_list().len();
132 let owner = |c: &ratatui::buffer::Cell| match c.fg {
133 Color::Rgb(h, l, 77) if h >= 1 => {
134 let i = usize::from(h - 1) << 8 | usize::from(l);
135 (i < n).then_some(i)
136 }
137 _ => None,
138 };
139 let mut grid = vec![None; usize::from(pie.width) * usize::from(pie.height)];
140 for y in pie.top()..pie.bottom() {
141 for x in pie.left()..pie.right() {
142 if legend.is_some_and(|l| l.contains((x, y).into())) {
143 continue;
144 }
145 grid[usize::from(y - pie.y) * usize::from(pie.width) + usize::from(x - pie.x)] =
146 owner(&scratch[(x, y)]);
147 }
148 }
149 let mut rects: Vec<(usize, Rect)> = Vec::new();
150 if let Some(l) = legend {
151 for y in l.top()..l.bottom() {
152 for x in l.left()..l.right() {
153 if let Some(i) = owner(&scratch[(x, y)])
154 && rects.iter().all(|(j, _)| *j != i)
155 {
156 let label = self.chart.slice_list()[i].label().chars().count() as u16;
157 let w = (2 + label).min(l.right() - x);
158 rects.push((i, Rect::new(x, y, w, 1)));
159 }
160 }
161 }
162 }
163 Owners {
164 pie: grid,
165 legend: rects,
166 }
167 }
168}
169
170struct Owners {
171 pie: Vec<Option<usize>>,
172 legend: Vec<(usize, Rect)>,
173}
174
175widget_impls!(Pie<'_>);
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180 use crate::{HitKind, HitMap};
181
182 fn chart() -> PieChart<'static> {
183 PieChart::new(vec![
184 PieSlice::new("Rust", 60.0, Color::Red),
185 PieSlice::new("Go", 30.0, Color::Blue),
186 PieSlice::new("C", 10.0, Color::Green),
187 ])
188 }
189
190 fn capture(pie: Pie<'_>) -> (HitMap, Buffer) {
191 let area = Rect::new(0, 0, 70, 22);
192 let mut buf = Buffer::empty(area);
193 (HitMap::capture(pie, area, &mut buf), buf)
194 }
195
196 #[test]
197 fn slices_and_legend_are_reported() {
198 let (h, _) = capture(Pie::new(chart()));
199 for s in 0..3 {
200 assert!(
201 h.hits()
202 .iter()
203 .any(|x| x.kind == HitKind::Point && x.series == s)
204 );
205 assert!(
206 h.hits()
207 .iter()
208 .any(|x| x.kind == HitKind::Legend && x.series == s)
209 );
210 }
211 let big = h
212 .hits()
213 .iter()
214 .find(|x| x.series == 0 && x.kind == HitKind::Point)
215 .unwrap();
216 assert!(big.lines.iter().any(|l| l.starts_with("60.0")));
217 }
218
219 #[test]
220 fn hidden_slice_drops_out_and_is_dimmed() {
221 let (h, buf) = capture(Pie::new(chart()).hidden([1]));
222 assert!(
223 h.hits()
224 .iter()
225 .all(|x| x.series != 1 || x.kind == HitKind::Legend)
226 );
227 let leg = h.hits().iter().find(|x| x.series == 1).unwrap();
228 assert!(
229 buf[(leg.rect.x, leg.rect.y)]
230 .modifier
231 .contains(Modifier::CROSSED_OUT)
232 );
233 }
234
235 #[test]
236 fn styles_and_donut_work_too() {
237 use tui_piechart::PieStyle;
238 for style in [
239 PieStyle::Solid,
240 PieStyle::Segmented,
241 PieStyle::Hud,
242 PieStyle::Rose,
243 ] {
244 let (h, _) = capture(Pie::new(chart().pie_style(style).hole(0.4)));
245 assert!(
246 h.hits().iter().any(|x| x.kind == HitKind::Point),
247 "{style:?}"
248 );
249 }
250 }
251}