1
//! The series legend: rows of swatch and name drawn above the plot, never over it.
2

            
3
use plotters::coord::Shift;
4
use plotters::prelude::*;
5
use plotters::style::text_anchor::{HPos, Pos, VPos};
6

            
7
use super::{DrawResult, bars_name_themselves, color_for};
8
use crate::layout::Metrics;
9
use crate::spec::{ChartKind, ChartSpec};
10

            
11
/// Series indices on each row of the legend.
12
type Rows = Vec<Vec<usize>>;
13

            
14
52262
fn font(metrics: Metrics) -> (&'static str, u32) {
15
52262
    ("sans-serif", metrics.px(11))
16
52262
}
17

            
18
12796
fn row_height(metrics: Metrics) -> i32 {
19
12796
    metrics.px_i32(18)
20
12796
}
21

            
22
8120
fn gap(metrics: Metrics) -> i32 {
23
8120
    metrics.px_i32(14)
24
8120
}
25

            
26
32683
pub(super) fn pixels(length: u32) -> i32 {
27
32683
    i32::try_from(length).unwrap_or(i32::MAX)
28
32683
}
29

            
30
21598
pub(super) fn text_width<DB: DrawingBackend>(
31
21598
    area: &DrawingArea<DB, Shift>,
32
21598
    text: &str,
33
21598
    metrics: Metrics,
34
21598
) -> i32 {
35
21598
    let style = (font(metrics).0, font(metrics).1, &metrics.ink).into_text_style(area);
36
21598
    pixels(area.estimate_text_size(text, &style).map_or(0, |(w, _)| w))
37
21598
}
38

            
39
/// The pixel width of every entry: swatch, space and name.
40
4533
fn entry_widths<DB: DrawingBackend>(
41
4533
    area: &DrawingArea<DB, Shift>,
42
4533
    spec: &ChartSpec,
43
4533
    metrics: Metrics,
44
4533
) -> Vec<i32> {
45
4533
    spec.series
46
4533
        .iter()
47
13474
        .map(|series| metrics.px_i32(14) + text_width(area, &series.label, metrics))
48
        .collect()
49
4533
}
50

            
51
/// Entries packed left to right, a new row when the next does not fit in `avail`.
52
1862
fn pack(widths: &[i32], avail: i32, gap: i32) -> Rows {
53
1862
    let mut rows: Rows = Vec::new();
54
1862
    let mut used = 0;
55
1862
    for (index, width) in widths.iter().enumerate() {
56
4423
        match rows.last_mut() {
57
2562
            Some(row) if used + gap + width <= avail => {
58
2540
                row.push(index);
59
2540
                used += gap + width;
60
            }
61
            _ => {
62
1883
                rows.push(vec![index]);
63
1883
                used = *width;
64
            }
65
        }
66
    }
67
1862
    rows
68
1862
}
69

            
70
5
pub(super) fn more_label(hidden: usize) -> String {
71
5
    format!("+{hidden} more")
72
5
}
73

            
74
/// The legend rows of a chart, as many as fit in `max_height`. When entries are cut,
75
/// the last row ends with a "+N more" entry, indexed after the series.
76
pub(super) struct Legend {
77
    widths: Vec<i32>,
78
    rows: Rows,
79
    more: String,
80
    metrics: Metrics,
81
}
82

            
83
impl Legend {
84
    /// Empty when the axis labels already name every bar.
85
4533
    pub fn new<DB: DrawingBackend>(
86
4533
        area: &DrawingArea<DB, Shift>,
87
4533
        spec: &ChartSpec,
88
4533
        metrics: Metrics,
89
4533
        max_height: i32,
90
4533
    ) -> Self {
91
4533
        let mut widths = entry_widths(area, spec, metrics);
92
4533
        let avail = pixels(area.dim_in_pixel().0) - 2 * metrics.px_i32(8);
93
4533
        let mut rows = if bars_name_themselves(spec) {
94
2674
            Vec::new()
95
        } else {
96
1859
            pack(&widths, avail, gap(metrics))
97
        };
98
4533
        let capacity = usize::try_from(max_height / row_height(metrics)).unwrap_or(0);
99
4533
        let mut more = String::new();
100
4533
        if rows.len() > capacity {
101
2
            rows.truncate(capacity);
102
2
            more = Self::append_more(area, &mut rows, &mut widths, avail, metrics);
103
4531
        }
104
4533
        Self {
105
4533
            widths,
106
4533
            rows,
107
4533
            more,
108
4533
            metrics,
109
4533
        }
110
4533
    }
111

            
112
    /// Drops trailing entries of the last row until "+N more" fits after them.
113
2
    fn append_more<DB: DrawingBackend>(
114
2
        area: &DrawingArea<DB, Shift>,
115
2
        rows: &mut Rows,
116
2
        widths: &mut Vec<i32>,
117
2
        avail: i32,
118
2
        metrics: Metrics,
119
2
    ) -> String {
120
2
        let total = widths.len();
121
        loop {
122
3
            let shown: usize = rows.iter().map(Vec::len).sum();
123
3
            let label = more_label(total - shown);
124
3
            let width = text_width(area, &label, metrics);
125
3
            let Some(last) = rows.last_mut() else {
126
                return String::new();
127
            };
128
3
            let used: i32 = last.iter().filter_map(|&i| widths.get(i)).sum::<i32>()
129
3
                + gap(metrics) * pixels(u32::try_from(last.len()).unwrap_or(0));
130
3
            if used + width <= avail || last.is_empty() {
131
2
                last.push(total);
132
2
                widths.push(width);
133
2
                return label;
134
1
            }
135
1
            last.pop();
136
        }
137
2
    }
138

            
139
    /// The height the legend takes from the chart.
140
4533
    pub fn height(&self) -> i32 {
141
4533
        i32::try_from(self.rows.len()).unwrap_or(0) * row_height(self.metrics)
142
4533
    }
143

            
144
4533
    pub fn draw<DB: DrawingBackend>(
145
4533
        &self,
146
4533
        area: &DrawingArea<DB, Shift>,
147
4533
        spec: &ChartSpec,
148
4533
    ) -> DrawResult<DB> {
149
4533
        let metrics = self.metrics;
150
4533
        let style = (font(metrics).0, font(metrics).1, &metrics.ink)
151
4533
            .into_text_style(area)
152
4533
            .pos(Pos::new(HPos::Left, VPos::Center));
153
4533
        let (swatch_w, swatch_h) = (metrics.px_i32(10), metrics.px_i32(6));
154
4533
        let canvas = pixels(area.dim_in_pixel().0);
155

            
156
4533
        for (row_index, row) in self.rows.iter().enumerate() {
157
4393
            let used = row.iter().filter_map(|&i| self.widths.get(i)).sum::<i32>()
158
1865
                + gap(metrics) * i32::try_from(row.len().saturating_sub(1)).unwrap_or(0);
159
1865
            let mut x = ((canvas - used) / 2).max(0);
160
1865
            let y = i32::try_from(row_index).unwrap_or(0) * row_height(metrics)
161
1865
                + row_height(metrics) / 2;
162
1865
            for &index in row {
163
4393
                let Some(width) = self.widths.get(index) else {
164
                    continue;
165
                };
166
4393
                let Some(series) = spec.series.get(index) else {
167
2
                    area.draw_text(&self.more, &style, (x, y))?;
168
2
                    x += width + gap(metrics);
169
2
                    continue;
170
                };
171
4391
                let color = color_for(index);
172
4391
                let top = y - swatch_h / 2;
173
4391
                if matches!(spec.kind, ChartKind::Line) {
174
1670
                    area.draw(&PathElement::new(
175
1670
                        vec![(x, y), (x + swatch_w, y)],
176
1670
                        color.stroke_width(metrics.px(2)),
177
1670
                    ))?;
178
                } else {
179
2721
                    let corners = [(x, top), (x + swatch_w, top + swatch_h)];
180
2721
                    area.draw(&Rectangle::new(corners, color.filled()))?;
181
2721
                    area.draw(&Rectangle::new(corners, metrics.ink.stroke_width(1)))?;
182
                }
183
4391
                area.draw_text(&series.label, &style, (x + metrics.px_i32(14), y))?;
184
4391
                x += width + gap(metrics);
185
            }
186
        }
187
4533
        Ok(())
188
4533
    }
189
}
190

            
191
#[cfg(test)]
192
mod tests;