1
//! Backend-agnostic chart drawing. Both `render_svg` and
2
//! `render_canvas` call `draw_on` with their own drawing area, so a
3
//! chart drawn to SVG looks identical to one drawn to a canvas.
4

            
5
use plotters::coord::Shift;
6
use plotters::coord::cartesian::Cartesian2d;
7
use plotters::coord::types::RangedCoordf64;
8
use plotters::prelude::*;
9
use plotters::style::text_anchor::{HPos, Pos, VPos};
10

            
11
mod hbar;
12
mod legend;
13

            
14
use legend::{Legend, pixels};
15

            
16
use crate::layout::{Metrics, Slots};
17
use crate::spec::{ChartKind, ChartSpec, SeriesPoint};
18

            
19
/// Palette cycled through series. Deliberately short — in practice
20
/// reports have 2-5 series.
21
const PALETTE: &[RGBColor] = &[
22
    RGBColor(31, 119, 180),
23
    RGBColor(255, 127, 14),
24
    RGBColor(44, 160, 44),
25
    RGBColor(214, 39, 40),
26
    RGBColor(148, 103, 189),
27
    RGBColor(140, 86, 75),
28
    RGBColor(227, 119, 194),
29
];
30

            
31
/// Axes, grid, labels and title: about 4.5:1 against both white and black, so
32
/// the unfilled chart reads on a light and on a dark background.
33
pub(crate) const NEUTRAL: RGBColor = RGBColor(118, 118, 118);
34

            
35
17865
fn color_for(index: usize) -> RGBColor {
36
17865
    PALETTE[index % PALETTE.len()]
37
17865
}
38

            
39
type Chart<'a, DB> = ChartContext<'a, DB, Cartesian2d<RangedCoordf64, RangedCoordf64>>;
40

            
41
type DrawResult<DB> = Result<(), DrawingAreaErrorKind<<DB as DrawingBackend>::ErrorType>>;
42

            
43
/// Draw `spec` onto `root`. Common layout for every chart kind: title
44
/// across the top, chart in the middle, notes (if any) across the
45
/// bottom.
46
///
47
/// # Errors
48
///
49
/// Returns an error if the backend rejects a draw call (e.g. the
50
/// drawing area is zero-sized). Callers fall back to a plain-text
51
/// representation on failure.
52
5533
pub fn draw_on<DB>(
53
5533
    root: &DrawingArea<DB, Shift>,
54
5533
    spec: &ChartSpec,
55
5533
    text_px: u32,
56
5533
    ink: RGBColor,
57
5533
) -> DrawResult<DB>
58
5533
where
59
5533
    DB: DrawingBackend,
60
{
61
    // Before any text is drawn: without the embedded face plotters would look for
62
    // a system font, which a static musl binary cannot even attempt (see font.rs).
63
    #[cfg(not(target_arch = "wasm32"))]
64
5533
    crate::font::ensure_registered();
65

            
66
5533
    let metrics = Metrics::new(text_px, ink);
67
5533
    let (_, total_h) = root.dim_in_pixel();
68
5533
    let total_h = i32::try_from(total_h).unwrap_or(0);
69
5533
    let spec = &hbar::capped(spec, metrics, total_h);
70
5533
    let chart_h = total_h
71
5533
        .saturating_sub(note_height(metrics, spec.notes.len()))
72
5533
        .max(0);
73
5533
    let (chart_area, notes_area) = root.split_vertically(chart_h);
74

            
75
5533
    let x_labels = x_labels(spec);
76
5533
    if x_labels.is_empty() || spec.series.is_empty() {
77
1000
        chart_area.draw_text(
78
1000
            &spec.title,
79
1000
            &("sans-serif", metrics.px(TITLE_FONT), &metrics.ink).into_text_style(&chart_area),
80
1000
            (metrics.px_i32(10), metrics.px_i32(20)),
81
1000
        )?;
82
1000
        draw_notes(&notes_area, spec, metrics)?;
83
1000
        return Ok(());
84
4533
    }
85

            
86
4533
    let (y_min, y_max) = y_range(spec);
87
4533
    let horizontal = matches!(spec.kind, ChartKind::HBar);
88

            
89
    // Grouped bars share a slot between the series that have a point there;
90
    // stacked bars and lines use one bar or point per period.
91
4533
    let slots = match spec.kind {
92
3526
        ChartKind::Bar | ChartKind::HBar => Slots::grouped(spec, &x_labels),
93
1007
        ChartKind::StackedBar | ChartKind::Line => Slots::single(x_labels.len()),
94
    };
95
4533
    let decimals = y_decimals(y_max - y_min);
96

            
97
4533
    let title_h = title_height(metrics, chart_h);
98
4533
    let (title_area, below) = chart_area.split_vertically(title_h);
99
4533
    title_area.draw_text(
100
4533
        &spec.title,
101
4533
        &("sans-serif", metrics.px(TITLE_FONT), &metrics.ink)
102
4533
            .into_text_style(&title_area)
103
4533
            .pos(Pos::new(HPos::Center, VPos::Center)),
104
4533
        (
105
4533
            i32::try_from(title_area.dim_in_pixel().0 / 2).unwrap_or(0),
106
4533
            title_h / 2,
107
4533
        ),
108
4533
    )?;
109
4533
    let legend = Legend::new(&below, spec, metrics, (chart_h - title_h) / 3);
110
4533
    let (legend_area, plot_area) = below.split_vertically(legend.height());
111
4533
    legend.draw(&legend_area, spec)?;
112

            
113
4533
    let row_labels = match horizontal {
114
672
        true => hbar::row_labels(root, &x_labels, metrics),
115
3861
        false => Vec::new(),
116
    };
117
4533
    let y_area = match horizontal {
118
672
        true => hbar::axis_width(root, &row_labels, metrics),
119
3861
        false => metrics.px(60),
120
    };
121
4533
    let value_ticks = match horizontal {
122
        true => {
123
            let plot_w =
124
672
                pixels(plot_area.dim_in_pixel().0) - pixels(y_area) - 2 * metrics.px_i32(MARGIN);
125
672
            hbar::tick_count(root, plot_w, (y_min, y_max), decimals, metrics)
126
        }
127
3861
        false => 6,
128
    };
129
4533
    let (x_range, y_axis) = match horizontal {
130
672
        true => (y_min..y_max, slots.len()..0.0),
131
3861
        false => (0.0..slots.len(), y_min..y_max),
132
    };
133
4533
    let mut chart = ChartBuilder::on(&plot_area)
134
4533
        .x_label_area_size(metrics.px(X_AREA))
135
4533
        .y_label_area_size(y_area)
136
4533
        .margin(metrics.px(MARGIN))
137
4533
        .build_cartesian_2d(x_range, y_axis)?;
138

            
139
4533
    configure_mesh(&mut chart, spec, metrics, decimals, value_ticks)?;
140

            
141
4533
    match spec.kind {
142
838
        ChartKind::Line => draw_line(&mut chart, spec, &x_labels, metrics)?,
143
3526
        ChartKind::Bar | ChartKind::HBar => draw_bars(&mut chart, spec, &x_labels, false, &slots)?,
144
169
        ChartKind::StackedBar => draw_bars(&mut chart, spec, &x_labels, true, &slots)?,
145
    }
146

            
147
4533
    match horizontal {
148
672
        true => hbar::draw_row_labels(&chart, root, &row_labels, y_min, metrics)?,
149
3861
        false => draw_x_labels(&chart, root, &x_labels, y_min, metrics)?,
150
    }
151

            
152
4533
    draw_notes(&notes_area, spec, metrics)?;
153
4533
    Ok(())
154
5533
}
155

            
156
/// The title font, on the scale of [`DEFAULT_TEXT_PX`]: one step above the 11 of the labels.
157
const TITLE_FONT: u32 = 13;
158
const X_AREA: u32 = 36;
159
const MARGIN: u32 = 8;
160

            
161
6207
fn note_height(metrics: Metrics, notes: usize) -> i32 {
162
6207
    metrics.px_i32(16) * i32::try_from(notes).unwrap_or(0)
163
6207
}
164

            
165
5207
fn title_height(metrics: Metrics, chart_h: i32) -> i32 {
166
5207
    metrics.px_i32(22).min(chart_h / 3)
167
5207
}
168

            
169
/// The value axis the bars grow along, and the grid across it. A vertical chart's labels
170
/// are the x labels drawn by [`draw_x_labels`]; a horizontal one's are drawn by [`hbar`].
171
4533
fn configure_mesh<DB>(
172
4533
    chart: &mut Chart<'_, DB>,
173
4533
    spec: &ChartSpec,
174
4533
    metrics: Metrics,
175
4533
    decimals: usize,
176
4533
    value_ticks: usize,
177
4533
) -> DrawResult<DB>
178
4533
where
179
4533
    DB: DrawingBackend,
180
{
181
19503
    let value = |y: &f64| format_y_label(*y, decimals);
182
4533
    let blank = |_: &f64| String::new();
183
4533
    let mut mesh = chart.configure_mesh();
184
    // Cap the ticks so the default "one line per unit" doesn't draw
185
    // hundreds of rules on a chart whose range spans into the thousands.
186
4533
    match spec.kind {
187
672
        ChartKind::HBar => mesh
188
672
            .x_labels(value_ticks)
189
672
            .x_label_formatter(&value)
190
672
            .y_labels(1)
191
672
            .y_label_formatter(&blank)
192
672
            .set_tick_mark_size(LabelAreaPosition::Left, 0)
193
672
            .disable_y_mesh()
194
672
            .x_desc(&spec.y_label),
195
3861
        _ => mesh
196
3861
            .y_labels(6)
197
3861
            .y_label_formatter(&value)
198
3861
            .x_labels(1)
199
3861
            .x_label_formatter(&blank)
200
3861
            .set_tick_mark_size(LabelAreaPosition::Bottom, 0)
201
3861
            .disable_x_mesh()
202
3861
            .x_desc(&spec.x_label)
203
3861
            .y_desc(&spec.y_label),
204
    };
205
4533
    mesh.light_line_style(TRANSPARENT)
206
4533
        .axis_style(metrics.ink)
207
4533
        .bold_line_style(metrics.ink.mix(0.3))
208
4533
        .axis_desc_style(("sans-serif", metrics.px(12), &metrics.ink))
209
4533
        .label_style(("sans-serif", metrics.px(11), &metrics.ink))
210
4533
        .draw()
211
4533
}
212

            
213
/// The union of x labels in the order they first appear.
214
6206
fn x_labels(spec: &ChartSpec) -> Vec<String> {
215
6206
    let mut labels: Vec<String> = Vec::new();
216
16903
    for point in spec.series.iter().flat_map(|series| &series.points) {
217
17577
        if !labels.contains(&point.x) {
218
15394
            labels.push(point.x.clone());
219
2183
        }
220
    }
221
6206
    labels
222
6206
}
223

            
224
/// Bars with one point each at their own x: the axis labels already name them.
225
4533
fn bars_name_themselves(spec: &ChartSpec) -> bool {
226
4533
    let mut seen: Vec<&str> = Vec::new();
227
4533
    for series in &spec.series {
228
12741
        let [point] = series.points.as_slice() else {
229
31
            return false;
230
        };
231
12710
        if seen.contains(&point.x.as_str()) {
232
830
            return false;
233
11880
        }
234
11880
        seen.push(&point.x);
235
    }
236
3672
    matches!(spec.kind, ChartKind::Bar | ChartKind::HBar)
237
4533
}
238

            
239
/// The decimals a y tick needs over an axis `range` long: one more than the digit the tick
240
/// step (about a fifth of the range, in 1, 2 or 5 units) reaches down to.
241
4537
fn y_decimals(range: f64) -> usize {
242
4537
    let step = range / 5.0;
243
4537
    if !(step.is_finite() && step > 0.0) {
244
1
        return 0;
245
4536
    }
246
4536
    let digits = (0..8i32)
247
6722
        .find(|digits| step * 10f64.powi(digits - 1) >= 1.0)
248
4536
        .unwrap_or(8);
249
4536
    usize::try_from(digits).unwrap_or(0)
250
4537
}
251

            
252
/// A y tick with up to `decimals` decimals, no trailing zeros, thousands grouped by a comma.
253
20857
fn format_y_label(y: f64, decimals: usize) -> String {
254
20857
    let text = format!("{:.*}", decimals, y.abs());
255
20857
    let trimmed = if text.contains('.') {
256
10862
        text.trim_end_matches('0').trim_end_matches('.')
257
    } else {
258
9995
        text.as_str()
259
    };
260
20857
    let (whole, fraction) = trimmed.split_once('.').unwrap_or((trimmed, ""));
261
20857
    let mut grouped = String::new();
262
20857
    for (i, digit) in whole.chars().enumerate() {
263
32515
        if i > 0 && (whole.len() - i) % 3 == 0 {
264
2048
            grouped.push(',');
265
30467
        }
266
32515
        grouped.push(digit);
267
    }
268
20857
    if !fraction.is_empty() {
269
21
        grouped.push('.');
270
21
        grouped.push_str(fraction);
271
20836
    }
272
20857
    match (y < 0.0, grouped.as_str()) {
273
15209
        (_, "0") | (false, _) => grouped,
274
5648
        (true, _) => format!("-{grouped}"),
275
    }
276
20857
}
277

            
278
4536
fn y_range(spec: &ChartSpec) -> (f64, f64) {
279
4536
    let (mut min, mut max) = (0.0_f64, 0.0_f64);
280
4536
    if matches!(spec.kind, ChartKind::StackedBar) {
281
        // Per-x-slot: sum positive and negative stacks separately.
282
        let mut slots: std::collections::BTreeMap<&str, (f64, f64)> =
283
169
            std::collections::BTreeMap::new();
284
169
        for series in &spec.series {
285
335
            for point in &series.points {
286
337
                let y = point.y_f64();
287
337
                let (neg, pos) = slots.entry(point.x.as_str()).or_insert((0.0, 0.0));
288
337
                if y >= 0.0 {
289
171
                    *pos += y;
290
                } else {
291
166
                    *neg += y;
292
                }
293
            }
294
        }
295
169
        for (_, (neg, pos)) in slots {
296
337
            if neg < min {
297
166
                min = neg;
298
171
            }
299
337
            if pos > max {
300
169
                max = pos;
301
168
            }
302
        }
303
    } else {
304
4367
        for series in &spec.series {
305
13144
            for point in &series.points {
306
13517
                let y = point.y_f64();
307
13517
                if y < min {
308
2990
                    min = y;
309
10527
                }
310
13517
                if y > max {
311
4254
                    max = y;
312
9263
                }
313
            }
314
        }
315
    }
316

            
317
4536
    let span = match (max - min).abs() {
318
2
        0.0 => 1.0,
319
4534
        span => span,
320
    };
321
4536
    let pad = span * 0.05;
322
    // An axis that has nothing on one side of zero stops at zero; a chart of zeros keeps a
323
    // span so its ticks have somewhere to land.
324
4536
    let low = if min < 0.0 { min - pad } else { 0.0 };
325
4536
    let high = match (max > 0.0, min < 0.0) {
326
4367
        (true, _) => max + pad,
327
167
        (false, true) => 0.0,
328
2
        (false, false) => span,
329
    };
330
4536
    (low, high)
331
4536
}
332

            
333
/// The x labels centred under their slots, below the axis.
334
3861
fn draw_x_labels<DB, CT>(
335
3861
    chart: &ChartContext<'_, DB, CT>,
336
3861
    area: &DrawingArea<DB, Shift>,
337
3861
    x_labels: &[String],
338
3861
    y_min: f64,
339
3861
    metrics: Metrics,
340
3861
) -> DrawResult<DB>
341
3861
where
342
3861
    DB: DrawingBackend,
343
3861
    CT: plotters::coord::CoordTranslate<From = (f64, f64)>,
344
{
345
3861
    let style = ("sans-serif", metrics.px(11), &metrics.ink)
346
3861
        .into_text_style(area)
347
3861
        .pos(Pos::new(HPos::Center, VPos::Top));
348
3861
    for (idx, label) in x_labels.iter().enumerate() {
349
8587
        let (x, y) = chart
350
8587
            .plotting_area()
351
8587
            .map_coordinate(&(Slots::centre(idx), y_min));
352
8587
        area.draw_text(label, &style, (x, y + metrics.gap()))?;
353
    }
354
3861
    Ok(())
355
3861
}
356

            
357
838
fn draw_line<DB, CT>(
358
838
    chart: &mut ChartContext<'_, DB, CT>,
359
838
    spec: &ChartSpec,
360
838
    x_labels: &[String],
361
838
    metrics: Metrics,
362
838
) -> DrawResult<DB>
363
838
where
364
838
    DB: DrawingBackend,
365
838
    CT: plotters::coord::CoordTranslate<From = (f64, f64)>,
366
{
367
838
    let (stroke, dot) = (metrics.px(2), metrics.px_i32(3));
368
838
    for (i, series) in spec.series.iter().enumerate() {
369
1670
        let color = color_for(i);
370
1670
        let points: Vec<(f64, f64)> = x_labels
371
1670
            .iter()
372
1670
            .enumerate()
373
3339
            .map(|(idx, label)| {
374
3339
                let y = series
375
3339
                    .points
376
3339
                    .iter()
377
3348
                    .find(|p| &p.x == label)
378
3339
                    .map_or(0.0, SeriesPoint::y_f64);
379
3339
                (Slots::centre(idx), y)
380
3339
            })
381
            .collect();
382

            
383
1670
        chart.draw_series(LineSeries::new(points.clone(), color.stroke_width(stroke)))?;
384
1670
        chart.draw_series(
385
1670
            points
386
1670
                .into_iter()
387
3339
                .map(|p| Circle::new(p, dot, color.filled())),
388
        )?;
389
    }
390
838
    Ok(())
391
838
}
392

            
393
3695
fn draw_bars<DB, CT>(
394
3695
    chart: &mut ChartContext<'_, DB, CT>,
395
3695
    spec: &ChartSpec,
396
3695
    x_labels: &[String],
397
3695
    stacked: bool,
398
3695
    slots: &Slots,
399
3695
) -> DrawResult<DB>
400
3695
where
401
3695
    DB: DrawingBackend,
402
3695
    CT: plotters::coord::CoordTranslate<From = (f64, f64)>,
403
{
404
    // Stacked-bar accumulators per x-slot and sign.
405
3695
    let mut pos_acc: Vec<f64> = vec![0.0; x_labels.len()];
406
3695
    let mut neg_acc: Vec<f64> = vec![0.0; x_labels.len()];
407
    // Bars already placed in each x slot: the next one sits right of them.
408
3695
    let mut placed: Vec<usize> = vec![0; x_labels.len()];
409

            
410
3695
    for (s_idx, series) in spec.series.iter().enumerate() {
411
11804
        let color = color_for(s_idx);
412
11804
        for (x_idx, label) in x_labels.iter().enumerate() {
413
43917
            let Some(point) = series.points.iter().find(|p| &p.x == label) else {
414
26783
                continue;
415
            };
416
12169
            let rank = if stacked { 0 } else { placed[x_idx] };
417
12169
            placed[x_idx] += 1;
418
12169
            let y = point.y_f64();
419
12169
            if y == 0.0 {
420
4318
                continue;
421
7851
            }
422

            
423
7851
            let (base, top) = if stacked {
424
337
                let acc = if y >= 0.0 {
425
171
                    &mut pos_acc[x_idx]
426
                } else {
427
166
                    &mut neg_acc[x_idx]
428
                };
429
337
                let start = *acc;
430
337
                *acc += y;
431
337
                (start, *acc)
432
            } else {
433
7514
                (0.0, y)
434
            };
435

            
436
7851
            let (left, right) = slots.span(x_idx, rank);
437
7851
            let corners = match spec.kind {
438
722
                ChartKind::HBar => [(base, left), (top, right)],
439
7129
                _ => [(left, base), (right, top)],
440
            };
441
7851
            chart.draw_series(std::iter::once(Rectangle::new(corners, color.filled())))?;
442
        }
443
    }
444

            
445
3695
    Ok(())
446
3695
}
447

            
448
5533
fn draw_notes<DB>(
449
5533
    area: &DrawingArea<DB, Shift>,
450
5533
    spec: &ChartSpec,
451
5533
    metrics: Metrics,
452
5533
) -> DrawResult<DB>
453
5533
where
454
5533
    DB: DrawingBackend,
455
{
456
5533
    if spec.notes.is_empty() || area.dim_in_pixel().1 == 0 {
457
2542
        return Ok(());
458
2991
    }
459
2991
    let style = ("sans-serif", metrics.px(11), &metrics.ink).into_text_style(area);
460
2991
    for (i, note) in spec.notes.iter().enumerate() {
461
2992
        let y = metrics.px_i32(2) + i32::try_from(i).unwrap_or(0) * metrics.px_i32(14);
462
2992
        area.draw_text(note, &style, (metrics.px_i32(8), y))?;
463
    }
464
2991
    Ok(())
465
5533
}
466

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