1use plotters::prelude::RGBColor;
4
5use crate::spec::ChartSpec;
6
7pub const DEFAULT_TEXT_PX: u32 = 9;
11
12#[derive(Debug, Clone, Copy)]
15pub(crate) struct Metrics {
16 text: u32,
17 pub ink: RGBColor,
18}
19
20impl Metrics {
21 pub fn new(text_px: u32, ink: RGBColor) -> Self {
22 Self {
23 text: text_px.max(1),
24 ink,
25 }
26 }
27
28 pub fn px(self, base: u32) -> u32 {
30 base.saturating_mul(self.text)
31 .saturating_add(DEFAULT_TEXT_PX / 2)
32 / DEFAULT_TEXT_PX
33 }
34
35 pub fn gap(self) -> i32 {
37 i32::try_from(self.text.saturating_mul(2) / 5).unwrap_or(i32::MAX)
38 }
39
40 pub fn px_i32(self, base: u32) -> i32 {
41 i32::try_from(self.px(base)).unwrap_or(i32::MAX)
42 }
43}
44
45const SLOT_GAP: f64 = 1.0 / 7.0;
47
48fn units(count: usize) -> f64 {
49 f64::from(u32::try_from(count).unwrap_or(u32::MAX))
50}
51
52pub(crate) struct Slots {
55 counts: Vec<usize>,
56}
57
58impl Slots {
59 pub fn single(labels: usize) -> Self {
61 Self {
62 counts: vec![1; labels],
63 }
64 }
65
66 pub fn grouped(spec: &ChartSpec, labels: &[String]) -> Self {
68 let counts = labels
69 .iter()
70 .map(|label| {
71 spec.series
72 .iter()
73 .filter(|series| series.points.iter().any(|p| &p.x == label))
74 .count()
75 .max(1)
76 })
77 .collect();
78 Self { counts }
79 }
80
81 pub fn len(&self) -> f64 {
83 units(self.counts.len())
84 }
85
86 pub fn centre(label: usize) -> f64 {
88 units(label) + 0.5
89 }
90
91 pub fn span(&self, label: usize, rank: usize) -> (f64, f64) {
93 let bars = self.counts.get(label).copied().unwrap_or(1).max(1);
94 let each = (1.0 - 2.0 * SLOT_GAP) / units(bars);
95 let left = units(label) + SLOT_GAP + units(rank) * each;
96 (left, left + each)
97 }
98}