Skip to main content

ferric_alpha_render/charts/
common.rs

1use plotters::coord::Shift;
2use plotters::prelude::{DrawingArea, DrawingBackend, IntoFont, Text, TextStyle};
3use plotters::style::text_anchor::{HPos, Pos, VPos};
4
5use crate::{FONT_FAMILY, RenderError, RenderResult, ensure_font_registered};
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct TextAllocation {
9    pub id: String,
10    pub x: u32,
11    pub y: u32,
12    pub width: u32,
13    pub height: u32,
14    pub raw_width: u32,
15    pub measured_width: u32,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct Rect {
20    pub x: u32,
21    pub y: u32,
22    pub width: u32,
23    pub height: u32,
24}
25
26pub fn checked_padded_range(
27    values: impl Iterator<Item = Option<f64>>,
28    include_zero: bool,
29) -> RenderResult<Option<(f64, f64)>> {
30    let mut min = f64::INFINITY;
31    let mut max = f64::NEG_INFINITY;
32    let mut found = false;
33    for value in values.flatten() {
34        checked_visual(value, "padded_range")?;
35        min = min.min(value);
36        max = max.max(value);
37        found = true;
38    }
39    if !found {
40        return Ok(None);
41    }
42    if include_zero {
43        min = min.min(0.0);
44        max = max.max(0.0);
45    }
46    let (low, high) = if min == max {
47        let pad = if min == 0.0 {
48            1.0
49        } else {
50            min.abs().max(1.0) * 0.1
51        };
52        (min - pad, max + pad)
53    } else {
54        let pad = (max - min) * 0.1;
55        (min - pad, max + pad)
56    };
57    checked_visual(low, "padded_range")?;
58    checked_visual(high, "padded_range")?;
59    Ok(Some((round_for_stability(low), round_for_stability(high))))
60}
61
62pub fn date_tick_indices(length: usize, maximum: usize) -> Vec<usize> {
63    if length == 0 || maximum == 0 {
64        return Vec::new();
65    }
66    if length <= maximum {
67        return (0..length).collect();
68    }
69    let last = length - 1;
70    (0..maximum)
71        .map(|index| ((index * last) + (maximum - 1) / 2) / (maximum - 1))
72        .collect()
73}
74
75pub fn escape_xml(value: &str) -> String {
76    value
77        .replace('&', "&amp;")
78        .replace('<', "&lt;")
79        .replace('>', "&gt;")
80        .replace('"', "&quot;")
81        .replace('\'', "&apos;")
82}
83
84pub fn measure_and_fit(value: &str, width: u32, font_size: u32) -> String {
85    if width == 0 {
86        return String::new();
87    }
88    if measured_width(value, font_size) <= width {
89        return value.to_string();
90    }
91    let ellipsis = "…";
92    let ellipsis_width = measured_width(ellipsis, font_size);
93    if ellipsis_width >= width {
94        return ellipsis.to_string();
95    }
96    let mut out = String::new();
97    for character in value.chars() {
98        let mut candidate = out.clone();
99        candidate.push(character);
100        candidate.push_str(ellipsis);
101        if measured_width(&candidate, font_size) > width {
102            break;
103        }
104        out.push(character);
105    }
106    out.push_str(ellipsis);
107    out
108}
109
110pub fn draw_text_in_rect<DB: DrawingBackend>(
111    area: &DrawingArea<DB, Shift>,
112    allocation: TextAllocation,
113    value: &str,
114    style: &TextStyle<'_>,
115    manifest: &mut Vec<TextAllocation>,
116) -> RenderResult<()>
117where
118    DB::ErrorType: std::error::Error + Send + Sync + 'static,
119{
120    let font_size = style.font.get_size().round() as u32;
121    let fitted = measure_and_fit(value, allocation.width.saturating_sub(4), font_size);
122    manifest.push(allocation.clone());
123    let style = style.clone().pos(Pos::new(HPos::Left, VPos::Center));
124    let x =
125        i32::try_from(allocation.x.saturating_add(2)).map_err(|_| RenderError::LayoutOverflow)?;
126    let y = i32::try_from(allocation.y + allocation.height / 2)
127        .map_err(|_| RenderError::LayoutOverflow)?;
128    area.draw(&Text::new(fitted, (x, y), style))
129        .map_err(|error| RenderError::Backend {
130            format: "SVG",
131            message: error.to_string(),
132        })?;
133    Ok(())
134}
135
136pub fn checked_visual(value: f64, operation: &'static str) -> RenderResult<f64> {
137    if value.is_finite() {
138        Ok(value)
139    } else {
140        Err(RenderError::InvalidContract {
141            reason: format!("{operation} produced non-finite visual value"),
142        })
143    }
144}
145
146pub(crate) fn text_allocation(
147    id: String,
148    rect: Rect,
149    value: &str,
150    font_size: u32,
151) -> TextAllocation {
152    let raw_width = measured_width(value, font_size);
153    let measured_width = raw_width.saturating_mul(5) / 4 + 4;
154    TextAllocation {
155        id,
156        x: rect.x,
157        y: rect.y,
158        width: rect.width,
159        height: rect.height,
160        raw_width,
161        measured_width,
162    }
163}
164
165pub(crate) fn text_style(color: crate::Color, size: u32) -> RenderResult<TextStyle<'static>> {
166    ensure_font_registered()?;
167    Ok((FONT_FAMILY, size).into_font().color(&color.rgb()))
168}
169
170fn measured_width(value: &str, font_size: u32) -> u32 {
171    if ensure_font_registered().is_ok()
172        && let Ok((width, _)) = (FONT_FAMILY, font_size).into_font().box_size(value)
173    {
174        return width;
175    }
176    value
177        .chars()
178        .map(|ch| if ch.is_ascii() { 7 } else { 14 })
179        .sum()
180}
181
182fn round_for_stability(value: f64) -> f64 {
183    (value * 1_000_000_000_000.0).round() / 1_000_000_000_000.0
184}