1
//! Horizontal bars: one row per x label, the labels left of the axis.
2

            
3
use std::borrow::Cow;
4

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

            
9
use super::legend::{more_label, pixels, text_width};
10
use super::{DrawResult, MARGIN, X_AREA, format_y_label, note_height, title_height, x_labels};
11
use crate::layout::Metrics;
12
use crate::spec::{ChartKind, ChartSpec};
13

            
14
const ELLIPSIS: char = '…';
15

            
16
/// A label's share of the chart width: wider labels are cut.
17
const LABEL_SHARE: i32 = 3;
18

            
19
/// The least height of a row: the pitch of a note line.
20
674
fn row_height(metrics: Metrics) -> i32 {
21
674
    metrics.px_i32(14)
22
674
}
23

            
24
672
fn style<'a, DB: DrawingBackend>(
25
672
    area: &DrawingArea<DB, Shift>,
26
672
    metrics: &'a Metrics,
27
672
) -> TextStyle<'a> {
28
672
    ("sans-serif", metrics.px(11))
29
672
        .into_text_style(area)
30
672
        .color(&metrics.ink)
31
672
}
32

            
33
/// `label`, or its start and an ellipsis, so that `width` of the result is at most `cap`.
34
3383
fn cut(label: &str, cap: i32, width: impl Fn(&str) -> i32) -> String {
35
3383
    if width(label) <= cap {
36
3379
        return label.to_string();
37
4
    }
38
4
    let mut kept: Vec<char> = label.chars().collect();
39
46
    while kept.pop().is_some() {
40
45
        let cut: String = kept.iter().chain(&[ELLIPSIS]).collect();
41
45
        if width(&cut) <= cap {
42
3
            return cut;
43
42
        }
44
    }
45
1
    ELLIPSIS.to_string()
46
3383
}
47

            
48
/// The labels as drawn, each cut to its share of the chart width.
49
672
pub(super) fn row_labels<DB: DrawingBackend>(
50
672
    root: &DrawingArea<DB, Shift>,
51
672
    labels: &[String],
52
672
    metrics: Metrics,
53
672
) -> Vec<String> {
54
672
    let cap = pixels(root.dim_in_pixel().0) / LABEL_SHARE;
55
3395
    let width = |text: &str| text_width(root, text, metrics);
56
3378
    labels.iter().map(|label| cut(label, cap, width)).collect()
57
672
}
58

            
59
/// The width of the left axis area: the widest label and its gap to the axis.
60
672
pub(super) fn axis_width<DB: DrawingBackend>(
61
672
    root: &DrawingArea<DB, Shift>,
62
672
    labels: &[String],
63
672
    metrics: Metrics,
64
672
) -> u32 {
65
672
    let widest = labels
66
672
        .iter()
67
3378
        .map(|label| text_width(root, label, metrics))
68
        .max()
69
672
        .unwrap_or(0);
70
672
    u32::try_from(widest + 2 * metrics.gap()).unwrap_or(0)
71
672
}
72

            
73
/// How many value ticks fit in `plot_w`: one per widest tick label and a gap, from 2 to 6.
74
672
pub(super) fn tick_count<DB: DrawingBackend>(
75
672
    root: &DrawingArea<DB, Shift>,
76
672
    plot_w: i32,
77
672
    (low, high): (f64, f64),
78
672
    decimals: usize,
79
672
    metrics: Metrics,
80
672
) -> usize {
81
672
    let widest = [low, high]
82
672
        .iter()
83
1344
        .map(|&tick| text_width(root, &format_y_label(tick, decimals), metrics))
84
        .max()
85
672
        .unwrap_or(0);
86
672
    let pitch = (widest + metrics.px_i32(14)).max(1);
87
672
    usize::try_from(plot_w / pitch).unwrap_or(0).clamp(2, 6)
88
672
}
89

            
90
/// Each label right-aligned against the axis, centred on its row.
91
672
pub(super) fn draw_row_labels<DB, CT>(
92
672
    chart: &ChartContext<'_, DB, CT>,
93
672
    area: &DrawingArea<DB, Shift>,
94
672
    labels: &[String],
95
672
    x_min: f64,
96
672
    metrics: Metrics,
97
672
) -> DrawResult<DB>
98
672
where
99
672
    DB: DrawingBackend,
100
672
    CT: plotters::coord::CoordTranslate<From = (f64, f64)>,
101
{
102
672
    let text_style = style(area, &metrics).pos(Pos::new(HPos::Right, VPos::Center));
103
672
    for (idx, label) in labels.iter().enumerate() {
104
3378
        let (x, y) = chart
105
3378
            .plotting_area()
106
3378
            .map_coordinate(&(x_min, crate::layout::Slots::centre(idx)));
107
3378
        area.draw_text(label, &text_style, (x - metrics.gap(), y))?;
108
    }
109
672
    Ok(())
110
672
}
111

            
112
/// How many rows fit in `total_h` beside the title, value axis and `notes`.
113
674
fn capacity(metrics: Metrics, total_h: i32, notes: usize) -> usize {
114
674
    let chart_h = total_h - note_height(metrics, notes);
115
674
    let plot_h = chart_h
116
674
        - title_height(metrics, chart_h)
117
674
        - metrics.px_i32(X_AREA)
118
674
        - 2 * metrics.px_i32(MARGIN);
119
674
    usize::try_from(plot_h / row_height(metrics))
120
674
        .unwrap_or(0)
121
674
        .max(1)
122
674
}
123

            
124
/// `spec` with the rows that do not fit dropped and a "+N more" note for them.
125
5533
pub(super) fn capped<'a>(
126
5533
    spec: &'a ChartSpec,
127
5533
    metrics: Metrics,
128
5533
    total_h: i32,
129
5533
) -> Cow<'a, ChartSpec> {
130
5533
    if !matches!(spec.kind, ChartKind::HBar) {
131
4861
        return Cow::Borrowed(spec);
132
672
    }
133
672
    let mut labels = x_labels(spec);
134
672
    let fits = capacity(metrics, total_h, spec.notes.len());
135
672
    if labels.len() <= fits {
136
670
        return Cow::Borrowed(spec);
137
2
    }
138
2
    let fits = capacity(metrics, total_h, spec.notes.len() + 1);
139
2
    let hidden = labels.len().saturating_sub(fits);
140
2
    labels.truncate(fits);
141
2
    let mut kept = spec.clone();
142
2
    for series in &mut kept.series {
143
40
        series.points.retain(|p| labels.contains(&p.x));
144
    }
145
40
    kept.series.retain(|series| !series.points.is_empty());
146
2
    kept.notes.push(more_label(hidden));
147
2
    Cow::Owned(kept)
148
5533
}
149

            
150
#[cfg(all(test, feature = "svg"))]
151
mod tests;