optionstratlib-visualization 0.23.1

Backend-neutral chart models, the Graph contract and its implementations for OptionStratLib types, with optional Plotly rendering and static export. Re-exported by the optionstratlib facade under its `visualization` feature.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! The bundled font, read with skrifa (fontations): character map,
//! advances, vertical metrics and glyph outlines. Nothing here uses
//! ttf-parser (RUSTSEC-2026-0192, unmaintained), which the advisory itself
//! points to skrifa to replace.
//!
//! Labels are laid out exactly the way Plotters' `ab_glyph` text laid them
//! out for #920 and #923, so the chart layout does not move:
//!
//! * the Plotters font size is ab_glyph's `PxScale`: one font-size unit per
//!   `ascent - descent` font units, computed in `f32` as ab_glyph does;
//! * the anchor box is the advance width truncated to whole pixels, and the
//!   Plotters size divided by [`EM_RATIO`] as its height;
//! * the baseline is half the Plotters size below the top of the box.
//!
//! There is no kerning and no shaping: one glyph per character. The bundled
//! Open Sans keeps its kerning in GPOS only, which ab_glyph never applied
//! either, so this is the same text as before.
//!
//! [`EM_RATIO`]: super::render

use super::render::{EM_RATIO, FONT_BYTES};
use crate::error::GraphError;
use num_traits::ToPrimitive;
use skrifa::charmap::Charmap;
use skrifa::instance::{LocationRef, Size};
use skrifa::metrics::GlyphMetrics;
use skrifa::outline::{DrawSettings, OutlineGlyphCollection, OutlinePen};
use skrifa::{FontRef, GlyphId, MetadataProvider};
use std::sync::OnceLock;

/// Whitespace drawn as a space: Plotters lays text out on one line.
pub(crate) const LINE_WHITESPACE: [char; 3] = ['\t', '\n', '\r'];

/// The bundled font, parsed once per process.
pub(crate) struct BundledFont {
    charmap: Charmap<'static>,
    metrics: GlyphMetrics<'static>,
    outlines: OutlineGlyphCollection<'static>,
    /// Ascent minus descent, in font units: ab_glyph's unit of size.
    height: f32,
}

/// A label's horizontal anchor, as Plotters' `HPos` and SVG `text-anchor`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Horizontal {
    /// The anchor is the left edge.
    Start,
    /// The anchor is the middle.
    Middle,
    /// The anchor is the right edge.
    End,
}

/// A label's vertical anchor, as Plotters' `VPos`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Vertical {
    /// The anchor is the top of the box.
    Top,
    /// The anchor is the middle of the box.
    Center,
    /// The anchor is the bottom of the box.
    Bottom,
}

#[cold]
fn out_of_range(what: &str) -> GraphError {
    GraphError::Render(format!("{what} is out of the drawable range"))
}

/// `value` truncated toward zero, as `as i32` does, or an error outside
/// `i32`.
pub(crate) fn whole_pixels(value: f64, what: &str) -> Result<i32, GraphError> {
    value.to_i32().ok_or_else(|| out_of_range(what))
}

/// How a label treats a character the font has no glyph for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Missing {
    /// Measure it with the `.notdef` advance, as ab_glyph did. Measuring
    /// only: the viewer-font and embedded-font SVGs leave such characters
    /// to the viewer.
    Notdef,
    /// Fail with [`GraphError::MissingGlyph`]: nothing is drawn in its
    /// place.
    Error,
}

/// An axis-aligned box in pixels.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct InkBox {
    pub(crate) left: f64,
    pub(crate) top: f64,
    pub(crate) right: f64,
    pub(crate) bottom: f64,
}

impl InkBox {
    pub(crate) fn union(self, other: InkBox) -> InkBox {
        InkBox {
            left: self.left.min(other.left),
            top: self.top.min(other.top),
            right: self.right.max(other.right),
            bottom: self.bottom.max(other.bottom),
        }
    }
}

/// One piece of a glyph outline, in pixels, y down.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum Segment {
    /// Starts a contour.
    Move((f64, f64)),
    /// A straight line to the point.
    Line((f64, f64)),
    /// A quadratic curve: control point, end point.
    Quad((f64, f64), (f64, f64)),
    /// A cubic curve: two control points, end point.
    Cubic((f64, f64), (f64, f64), (f64, f64)),
    /// Closes the contour.
    Close,
}

/// A label laid out like Plotters lays it out.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct LineLayout {
    /// Width of the anchor box: the advances, truncated to whole pixels.
    pub(crate) width: i32,
    /// Height of the anchor box.
    pub(crate) height: i32,
    /// The baseline, below the top of the anchor box.
    pub(crate) baseline: f64,
    /// Each glyph with its pen position from the left of the box.
    glyphs: Vec<(GlyphId, f32)>,
    /// Pixels per font unit.
    factor: f32,
}

#[cold]
fn font_error(reason: impl std::fmt::Display) -> GraphError {
    GraphError::Render(format!("Open Sans Regular: {reason}"))
}

/// The bundled font, parsed once per process.
pub(crate) fn bundled_font() -> Result<&'static BundledFont, GraphError> {
    static FONT: OnceLock<Result<BundledFont, String>> = OnceLock::new();
    FONT.get_or_init(|| {
        let font = FontRef::new(FONT_BYTES).map_err(|error| error.to_string())?;
        let vertical = font.metrics(Size::unscaled(), LocationRef::default());
        Ok(BundledFont {
            charmap: font.charmap(),
            metrics: font.glyph_metrics(Size::unscaled(), LocationRef::default()),
            outlines: font.outline_glyphs(),
            height: vertical.ascent - vertical.descent,
        })
    })
    .as_ref()
    .map_err(font_error)
}

impl LineLayout {
    /// How far left of the anchor the box starts: nothing, half the width
    /// or the whole width, as plotters-backend's default `draw_text`
    /// computes it (`-width / 2` truncates toward zero).
    pub(crate) fn dx(&self, anchor: Horizontal) -> Result<i32, GraphError> {
        match anchor {
            Horizontal::Start => Some(0),
            Horizontal::Middle => self.width.checked_neg().and_then(|w| w.checked_div(2)),
            Horizontal::End => self.width.checked_neg(),
        }
        .ok_or_else(|| out_of_range("the label width"))
    }

    /// How far above the anchor the box starts, likewise.
    pub(crate) fn dy(&self, anchor: Vertical) -> Result<i32, GraphError> {
        match anchor {
            Vertical::Top => Some(0),
            Vertical::Center => self.height.checked_neg().and_then(|h| h.checked_div(2)),
            Vertical::Bottom => self.height.checked_neg(),
        }
        .ok_or_else(|| out_of_range("the label height"))
    }

    /// The same layout with another anchor-box height. The outline
    /// conversion takes it from the SVG `font-size` attribute, which is
    /// exactly the height Plotters computed; multiplying that attribute
    /// back by [`EM_RATIO`] and dividing again could land an ulp below a
    /// whole number and truncate differently.
    pub(crate) fn with_height(self, height: i32) -> LineLayout {
        LineLayout { height, ..self }
    }
}

impl BundledFont {
    /// The glyph `character` is drawn with, if the font has one.
    fn glyph(&self, character: char) -> Option<GlyphId> {
        let drawn = if LINE_WHITESPACE.contains(&character) {
            ' '
        } else {
            character
        };
        self.charmap.map(drawn)
    }

    fn advance(&self, glyph: GlyphId) -> f32 {
        self.metrics.advance_width(glyph).unwrap_or_default()
    }

    /// Lays `text` out at the Plotters font size `plotters_size`.
    ///
    /// # Errors
    ///
    /// [`GraphError::MissingGlyph`] for a character without a glyph when
    /// `missing` is [`Missing::Error`].
    pub(crate) fn layout(
        &self,
        text: &str,
        plotters_size: f64,
        missing: Missing,
    ) -> Result<LineLayout, GraphError> {
        // ab_glyph scales in f32, as Plotters does.
        let scale = plotters_size
            .to_f32()
            .ok_or_else(|| out_of_range("the font size"))?;
        let factor = scale / self.height;
        let mut glyphs = Vec::with_capacity(text.len());
        let mut pen = 0_f32;
        for character in text.chars() {
            let glyph = match (self.glyph(character), missing) {
                (Some(glyph), _) => glyph,
                (None, Missing::Notdef) => GlyphId::NOTDEF,
                (None, Missing::Error) => {
                    return Err(GraphError::MissingGlyph {
                        character,
                        code: u32::from(character),
                        text: text.to_string(),
                    });
                }
            };
            glyphs.push((glyph, pen));
            pen += self.advance(glyph) * factor;
        }
        Ok(LineLayout {
            width: pen
                .to_i32()
                .ok_or_else(|| out_of_range("the label width"))?,
            height: whole_pixels(plotters_size / EM_RATIO, "the label height")?,
            baseline: f64::from(scale / 2.0),
            glyphs,
            factor,
        })
    }

    /// Calls `segment` with every outline segment of `layout`, the top left
    /// of its anchor box at `origin`, and returns the ink box; `None` when
    /// no glyph has ink (an empty or all-space label).
    ///
    /// # Errors
    ///
    /// [`GraphError::Render`] if a glyph outline cannot be read.
    pub(crate) fn trace(
        &self,
        layout: &LineLayout,
        origin: (f64, f64),
        mut segment: impl FnMut(Segment),
    ) -> Result<Option<InkBox>, GraphError> {
        let factor = f64::from(layout.factor);
        let baseline = origin.1 + layout.baseline;
        let mut ink: Option<InkBox> = None;
        for (glyph, pen) in &layout.glyphs {
            // Glyphs without ink (spaces: an empty outline and box) only
            // advance the pen, as with ab_glyph.
            let bounds = self
                .metrics
                .bounds(*glyph)
                .filter(|b| b.x_min < b.x_max && b.y_min < b.y_max);
            let (Some(outline), Some(bounds)) = (self.outlines.get(*glyph), bounds) else {
                continue;
            };
            let left = origin.0 + f64::from(*pen);
            let place = |x: f32, y: f32| {
                (
                    left + f64::from(x) * factor,
                    baseline - f64::from(y) * factor,
                )
            };
            let mut pen = Pen {
                place: &place,
                current: None,
                emit: &mut segment,
            };
            outline
                .draw(
                    DrawSettings::unhinted(Size::unscaled(), LocationRef::default()),
                    &mut pen,
                )
                .map_err(font_error)?;
            let (left_top, right_bottom) = (
                place(bounds.x_min, bounds.y_max),
                place(bounds.x_max, bounds.y_min),
            );
            let glyph_box = InkBox {
                left: left_top.0,
                top: left_top.1,
                right: right_bottom.0,
                bottom: right_bottom.1,
            };
            ink = Some(ink.map_or(glyph_box, |ink| ink.union(glyph_box)));
        }
        Ok(ink)
    }
}

/// Places skrifa's unscaled outline in pixels and drops lines to the
/// current point, which have no geometry.
struct Pen<'a, P, E> {
    place: &'a P,
    current: Option<(f32, f32)>,
    emit: &'a mut E,
}

impl<P: Fn(f32, f32) -> (f64, f64), E: FnMut(Segment)> OutlinePen for Pen<'_, P, E> {
    fn move_to(&mut self, x: f32, y: f32) {
        self.current = Some((x, y));
        (self.emit)(Segment::Move((self.place)(x, y)));
    }

    fn line_to(&mut self, x: f32, y: f32) {
        if self.current == Some((x, y)) {
            return;
        }
        self.current = Some((x, y));
        (self.emit)(Segment::Line((self.place)(x, y)));
    }

    fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) {
        self.current = Some((x, y));
        (self.emit)(Segment::Quad((self.place)(cx, cy), (self.place)(x, y)));
    }

    fn curve_to(&mut self, cx0: f32, cy0: f32, cx1: f32, cy1: f32, x: f32, y: f32) {
        self.current = Some((x, y));
        (self.emit)(Segment::Cubic(
            (self.place)(cx0, cy0),
            (self.place)(cx1, cy1),
            (self.place)(x, y),
        ));
    }

    fn close(&mut self) {
        self.current = None;
        (self.emit)(Segment::Close);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bundled_font_metrics_are_open_sans() -> Result<(), GraphError> {
        let font = bundled_font()?;
        // hhea ascent 2189, descent -600.
        assert_eq!(font.height, 2789.0);
        assert!(font.glyph('A').is_some());
        assert!(font.glyph('\u{4E2D}').is_none());
        // Line whitespace is drawn with the space glyph.
        assert_eq!(font.glyph('\n'), font.glyph(' '));
        Ok(())
    }

    #[test]
    fn test_layout_measures_like_plotters() -> Result<(), GraphError> {
        let font = bundled_font()?;
        let size = 12.0 * EM_RATIO;
        let layout = font.layout("Strike", size, Missing::Error)?;
        assert!(layout.width > 20 && layout.width < 40, "{}", layout.width);
        assert_eq!(layout.height, (size / EM_RATIO) as i32);
        assert!((layout.baseline - size / 2.0).abs() < 1e-5);
        Ok(())
    }

    #[test]
    fn test_missing_glyphs_follow_the_policy() -> Result<(), GraphError> {
        let font = bundled_font()?;
        let measured = font.layout("IV 中", 14.88, Missing::Notdef)?;
        let plain = font.layout("IV ", 14.88, Missing::Notdef)?;
        assert!(measured.width > plain.width);
        assert!(matches!(
            font.layout("IV 中", 14.88, Missing::Error),
            Err(GraphError::MissingGlyph {
                character: '中',
                ..
            })
        ));
        Ok(())
    }

    #[test]
    fn test_trace_closes_every_contour_and_skips_spaces() -> Result<(), GraphError> {
        let font = bundled_font()?;
        let layout = font.layout("o o", 20.0, Missing::Error)?;
        let mut segments = Vec::new();
        let ink = font.trace(&layout, (10.0, 20.0), |segment| segments.push(segment))?;
        let moves = segments
            .iter()
            .filter(|s| matches!(s, Segment::Move(_)))
            .count();
        let closes = segments.iter().filter(|s| **s == Segment::Close).count();
        // Two `o`s, two contours each; the space has none.
        assert_eq!((moves, closes), (4, 4));
        let ink = ink
            .ok_or("ink")
            .map_err(|reason| GraphError::Render(reason.to_string()))?;
        assert!(ink.left >= 10.0 && ink.right > ink.left && ink.bottom > ink.top);
        let blank = font.layout("   ", 20.0, Missing::Error)?;
        assert_eq!(font.trace(&blank, (0.0, 0.0), |_| {})?, None);
        Ok(())
    }
}