1#![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
110pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
139pub enum Resolution {
140 #[default]
144 Standard,
145
146 Braille,
151}
152
153#[derive(Debug, Clone, PartialEq)]
166pub struct PieSlice<'a> {
167 label: &'a str,
169 value: f64,
171 color: Color,
173}
174
175impl<'a> PieSlice<'a> {
176 #[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 #[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 #[must_use]
210 pub const fn label(&self) -> &'a str {
211 self.label
212 }
213
214 #[must_use]
216 pub const fn value(&self) -> f64 {
217 self.value
218 }
219
220 #[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#[derive(Debug, Clone, PartialEq)]
253pub struct PieChart<'a> {
254 slices: Vec<PieSlice<'a>>,
256 block: Option<Block<'a>>,
258 style: Style,
260 theme_style: Style,
262 show_legend: bool,
264 show_percentages: bool,
266 pie_char: char,
268 legend_marker: &'a str,
270 resolution: Resolution,
272 legend_position: LegendPosition,
274 legend_layout: LegendLayout,
276 legend_alignment: LegendAlignment,
278 pie_style: PieStyle,
280 hole: f64,
282 start: f64,
284 gap: f64,
286 explode: f64,
288 center: Option<&'a str>,
290}
291
292impl Default for PieChart<'_> {
293 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 #[must_use]
343 pub fn new(slices: Vec<PieSlice<'a>>) -> Self {
344 Self {
345 slices,
346 ..Default::default()
347 }
348 }
349
350 #[must_use]
355 pub fn slice_list(&self) -> &[PieSlice<'a>] {
356 &self.slices
357 }
358
359 #[must_use]
373 pub fn slices(mut self, slices: Vec<PieSlice<'a>>) -> Self {
374 self.slices = slices;
375 self
376 }
377
378 #[must_use]
392 pub fn block(mut self, block: Block<'a>) -> Self {
393 self.block = Some(block);
394 self
395 }
396
397 #[must_use]
409 pub fn style<S: Into<Style>>(mut self, style: S) -> Self {
410 self.style = style.into();
411 self
412 }
413
414 #[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 #[must_use]
440 pub const fn show_legend(mut self, show: bool) -> Self {
441 self.show_legend = show;
442 self
443 }
444
445 #[must_use]
455 pub const fn show_percentages(mut self, show: bool) -> Self {
456 self.show_percentages = show;
457 self
458 }
459
460 #[must_use]
483 pub const fn pie_char(mut self, c: char) -> Self {
484 self.pie_char = c;
485 self
486 }
487
488 #[must_use]
518 pub const fn legend_marker(mut self, marker: &'a str) -> Self {
519 self.legend_marker = marker;
520 self
521 }
522
523 #[must_use]
538 pub const fn resolution(mut self, resolution: Resolution) -> Self {
539 self.resolution = resolution;
540 self
541 }
542
543 #[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 #[must_use]
576 pub const fn legend_position(mut self, position: LegendPosition) -> Self {
577 self.legend_position = position;
578 self
579 }
580
581 #[must_use]
597 pub const fn legend_layout(mut self, layout: LegendLayout) -> Self {
598 self.legend_layout = layout;
599 self
600 }
601
602 #[must_use]
618 pub const fn legend_alignment(mut self, alignment: LegendAlignment) -> Self {
619 self.legend_alignment = alignment;
620 self
621 }
622
623 #[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 #[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 #[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 #[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 #[must_use]
688 pub const fn pie_style(mut self, style: PieStyle) -> Self {
689 self.pie_style = style;
690 self
691 }
692
693 #[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 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 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 const LEGEND_VERTICAL_MAX_RATIO: u16 = 3;
758
759 const LEGEND_VERTICAL_MIN_WIDTH: u16 = 20;
761
762 const LEGEND_HORIZONTAL_MAX_RATIO: u16 = 5;
765
766 const LEGEND_HORIZONTAL_MAX_WIDTH: u16 = 60;
768
769 const LEGEND_VERTICAL_MAX_HEIGHT: u16 = 9;
772
773 const LEGEND_HORIZONTAL_HEIGHT: u16 = 3;
775
776 const LEGEND_SPACING: u16 = 1;
778
779 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 }
801 Resolution::Braille => {
802 self.render_piechart_braille(area, buf);
803 return;
804 }
805 }
806
807 let (pie_area, legend_area_opt) = self.calculate_layout(area);
809
810 let center_x = pie_area.width / 2;
813 let center_y = pie_area.height / 2;
814
815 let radius = center_x.min(center_y * 2).saturating_sub(1);
817
818 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 if let Some(legend_area) = legend_area_opt {
839 self.render_legend(buf, legend_area);
840 }
841 }
842
843 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 let (start_angle, end_angle, is_full_circle) = Self::slice_angles(start_percent, percent);
875
876 let scan_width = i32::from(radius + 1);
878 let scan_height = i32::from((radius / 2) + 1); for dy in -scan_height..=scan_height {
881 for dx in -scan_width..=scan_width {
882 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 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 #[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 let distance = (adjusted_dx * adjusted_dx + adjusted_dy * adjusted_dy).sqrt();
903
904 #[allow(clippy::cast_precision_loss)]
906 if distance <= f64::from(radius) && distance >= self.hole * f64::from(radius) {
907 let angle = adjusted_dy.atan2(adjusted_dx);
909
910 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 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 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 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 #[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 match (self.legend_position, self.legend_layout) {
1084 (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 (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 (LegendPosition::Left | LegendPosition::Right, LegendLayout::Horizontal) => {
1100 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 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 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 let rows = num_items.div_ceil(columns);
1132 (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 LegendLayout::Vertical => widths.max().unwrap_or(0),
1235 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 let (pie_area, legend_area_opt) = self.calculate_layout(area);
1255
1256 let center_x_chars = pie_area.width / 2;
1258 let center_y_chars = pie_area.height / 2;
1259
1260 let center_x_dots = center_x_chars * 2;
1262 let center_y_dots = center_y_chars * 4;
1263
1264 let radius = (center_x_dots).min(center_y_dots).saturating_sub(2);
1270
1271 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 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 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 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 let dot_positions = [
1320 (0, 0, 0x01), (0, 1, 0x02), (0, 2, 0x04), (1, 0, 0x08), (1, 1, 0x10), (1, 2, 0x20), (0, 3, 0x40), (1, 3, 0x80), ];
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 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 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 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_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 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 assert!(PieChart::is_angle_in_slice(PI / 4.0, 0.0, PI / 2.0));
1573
1574 assert!(!PieChart::is_angle_in_slice(PI, 0.0, PI / 2.0));
1576
1577 assert!(PieChart::is_angle_in_slice(0.1, 1.5 * PI, 0.5));
1579 }
1580
1581 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 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 #[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 #[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 #[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 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 assert_eq!(piechart.calculate_aligned_x(area, 10), 10);
1740 }
1741
1742 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 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 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 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 #[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 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_empty_test!(piechart_render_empty_slices, PieChart::default());
1964
1965 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 #[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 #[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 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 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_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_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_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_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 Rect::new(0, 0, 60, 12)
2080 );
2081
2082 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 Rect::new(0, 0, 22, 15)
2099 );
2100
2101 #[test]
2104 fn piechart_layout_horizontal_split_too_narrow() {
2105 let area = Rect::new(0, 0, 5, 20);
2106 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 #[test]
2115 fn piechart_layout_vertical_split_too_short() {
2116 let area = Rect::new(0, 0, 60, 3);
2117 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 #[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 assert!(width > 0);
2164 }
2165
2166 #[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 #[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 let height = piechart.calculate_vertical_grid_height(1);
2198 assert!(height >= 4);
2199 }
2200
2201 #[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 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 let slices = vec![PieSlice::new("日本語", 100.0, Color::Red)];
2250 let chart = PieChart::new(slices.clone()).show_percentages(false);
2251 assert_eq!(chart.legend_item_width(&slices[0], 100.0), 7);
2253 }
2254
2255 #[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}