edamame 0.1.1

A fast TUI Markdown editor and viewer
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! SVG → `DynamicImage` rasterization, shared by the SVG-file image
//! loader and the Mermaid diagram pipeline.
//!
//! Both consumers need the same core machinery — parse an SVG string with
//! `usvg`, rasterize it with `resvg`/`tiny_skia`, and decode the result
//! back into a `DynamicImage` for the image cache — but differ in two
//! policies, expressed via [`SvgSizing`]:
//!
//! * **Scale mode** ([`SvgScaleMode`]).  A user's `.svg` *file* has a
//!   meaningful natural size (a badge, an icon), so it is only ever
//!   *downscaled* to fit the cell envelope — `Resize::Fit` then displays
//!   it 1:1, which is crisp by construction.  A Mermaid *diagram* carries
//!   no meaningful natural size (the renderer picks dimensions from
//!   layout heuristics), so it is scaled *up or down* to fill the
//!   envelope.
//! * **Background** ([`rasterize_svg`]'s `background` argument).  Mermaid
//!   SVGs are transparent but meant to be read on a light page, so the
//!   diagram path fills white.  A user's SVG keeps its transparency
//!   (`None`) and composites over the document background like a
//!   transparent PNG.
//!
//! The process-wide [`shared_fontdb`] lives here because both paths parse
//! SVGs and font-database loading (`load_system_fonts`) is the dominant
//! cost — sharing one `Arc<Database>` turns every render after the first
//! into an atomic refcount bump instead of a fresh disk scan.

use std::sync::{Arc, OnceLock};

use image::DynamicImage;
use usvg::fontdb;

/// Process-global font database, loaded lazily on first SVG render.
/// `fontdb::Database::load_system_fonts` scans every OS font directory
/// (typically ~100–300 ms on a warm disk cache, slower cold), so running
/// it per-render made a 20-diagram document spawn 20 concurrent scans —
/// the dominant cost on initial document load.  Shared here as an
/// `Arc<Database>` so every SVG decode is an Arc clone plus a ref into
/// the same underlying tables.
///
/// Populated by [`warm_fontdb`] (called off the hot path at startup) and
/// [`shared_fontdb`] (the fallback on the hot path when the warmup hasn't
/// completed yet).  Never invalidated — the font install set doesn't
/// change during a session.
static SHARED_FONTDB: OnceLock<Arc<fontdb::Database>> = OnceLock::new();

/// Return the process-wide shared `fontdb::Database`, loading system
/// fonts on first call.  Safe to call from any thread; subsequent calls
/// are lock-free Arc clones.
fn shared_fontdb() -> Arc<fontdb::Database> {
    SHARED_FONTDB
        .get_or_init(|| {
            let mut db = fontdb::Database::new();
            db.load_system_fonts();
            Arc::new(db)
        })
        .clone()
}

/// Pre-populate the shared fontdb off the hot path so the first real SVG
/// render doesn't pay the disk-scan cost.  Idempotent and thread-safe.
pub fn warm_fontdb() {
    let _ = shared_fontdb();
}

/// Whether an SVG may be scaled up to fill the envelope, or only down.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SvgScaleMode {
    /// Downscale only — never balloon a small SVG to fill the envelope;
    /// its natural size is meaningful.  Used for user `.svg` files.
    Natural,
    /// Scale up or down to fill the envelope.  Used for synthetic
    /// diagrams (Mermaid), which have no meaningful natural size.
    Fill,
}

/// How an SVG's natural size maps onto the target cell envelope.  A
/// `None` envelope or font size keeps the natural size verbatim (used by
/// tests that don't care about on-screen size).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SvgSizing {
    pub envelope: Option<(u16, u16)>,
    pub font_size: Option<(u16, u16)>,
    pub mode: SvgScaleMode,
}

impl SvgSizing {
    /// The envelope in pixels, or `None` when no finite envelope applies.
    fn envelope_px(self) -> Option<(u32, u32)> {
        let (envelope, font_size) = (self.envelope?, self.font_size?);
        let max_w = u32::from(envelope.0).saturating_mul(u32::from(font_size.0));
        let max_h = u32::from(envelope.1).saturating_mul(u32::from(font_size.1));
        (max_w != 0 && max_h != 0).then_some((max_w, max_h))
    }

    /// The scale factor to apply to a `natural_w × natural_h` SVG.
    fn scale_for(self, natural_w: u32, natural_h: u32) -> f32 {
        let Some((max_w_px, max_h_px)) = self.envelope_px() else {
            return 1.0;
        };
        let fit = (max_w_px as f32 / natural_w as f32).min(max_h_px as f32 / natural_h as f32);
        let fit = if fit.is_finite() && fit > 0.0 {
            fit
        } else {
            1.0
        };
        match self.mode {
            SvgScaleMode::Natural => fit.min(1.0),
            SvgScaleMode::Fill => fit,
        }
    }
}

/// Longest side, in pixels, any rasterized SVG may occupy.  Guards the
/// degenerate aspect ratios that [`MAX_RASTER_PIXELS`] alone lets through
/// (a 1 × 10⁹ SVG has few enough pixels per row to satisfy an area budget
/// while still being unallocatable).
const MAX_RASTER_DIM: u32 = 8_192;

/// Hard ceiling on the rasterized pixmap's area, applied **whether or not
/// a cell envelope is supplied**.
///
/// The envelope clamp below bounds every on-screen path, but not every
/// caller has an envelope: `export::html::render_mermaid_png_data_uri`
/// rasterizes at natural size because the exported PNG isn't sized in
/// terminal cells.  The SVG it rasterizes is generated from a Mermaid
/// block in a document the user may not have written, and while
/// `diagram::mermaid` caps that *source* at 64 KiB, a dense diagram turns
/// a small source into arbitrarily large layout dimensions — input bound,
/// output unbound.  4 M pixels is 16 MB of RGBA, far more resolution than
/// an embedded diagram needs, and it caps what a crafted document can make
/// us allocate.
///
/// Over-budget SVGs are scaled *down* to fit rather than refused: a
/// legitimately large diagram should still export, just not at its
/// declared size.
const MAX_RASTER_PIXELS: u64 = 4_000_000;

/// The factor a `px_w × px_h` pixmap must be multiplied by to fit both
/// [`MAX_RASTER_DIM`] and [`MAX_RASTER_PIXELS`], aspect ratio preserved.
/// Returns `1.0` when it already fits — the overwhelmingly common case, so
/// the enveloped paths are unaffected — and never more than `1.0`.
///
/// Takes the *rounded* pixel dimensions rather than the natural size ×
/// scale, so that flooring the result is exactly within budget: the
/// `ceil` that derives those dimensions would otherwise push a
/// budget-fitting scale back over the line by a pixel per axis.
fn budget_shrink(px_w: u32, px_h: u32) -> f64 {
    let (w, h) = (f64::from(px_w), f64::from(px_h));
    let mut shrink = 1.0f64;
    let longest = w.max(h);
    if longest > f64::from(MAX_RASTER_DIM) {
        shrink = f64::from(MAX_RASTER_DIM) / longest;
    }
    let area = (w * shrink) * (h * shrink);
    if area > MAX_RASTER_PIXELS as f64 {
        shrink *= (MAX_RASTER_PIXELS as f64 / area).sqrt();
    }
    shrink
}

/// Errors from the SVG rasterization pipeline.  Carry owned `String`
/// messages rather than source-chained errors so the type stays
/// `Send + Sync` and can be shipped back through the App's mpsc channel.
#[derive(Debug, thiserror::Error)]
pub enum SvgError {
    #[error("svg parse failed: {0}")]
    Parse(String),
    #[error("svg raster failed: {0}")]
    Raster(String),
    #[error("svg png decode failed: {0}")]
    Decode(String),
}

/// Rasterize an SVG string into a `DynamicImage`.
///
/// * `sizing` — how the SVG's natural size maps onto the cell envelope
///   (see [`SvgSizing`]).
/// * `background` — an optional opaque RGBA fill applied before drawing.
///   `Some([r, g, b, a])` paints the pixmap with that color first (the
///   Mermaid path passes white); `None` keeps the SVG's own
///   transparency, which the image renderer composites over the document
///   background like a transparent PNG.
pub fn rasterize_svg(
    svg: &str,
    sizing: SvgSizing,
    background: Option<[u8; 4]>,
) -> Result<DynamicImage, SvgError> {
    let mut opt = usvg::Options {
        // Use the process-wide shared fontdb (see `SHARED_FONTDB`).  This
        // is an `Arc::clone` — O(1) atomic increment — instead of a fresh
        // disk scan per render.
        fontdb: shared_fontdb(),
        ..Default::default()
    };
    // Refuse to resolve a `<image href>` that is a file path or URL.
    // usvg's default string resolver *reads local files*, so an untrusted
    // SVG could pull arbitrary on-disk files into the render — render-only
    // on screen, but an exfil channel if that SVG is then inlined into an
    // HTML export.  Embedded `data:` images still resolve via the default
    // `resolve_data`; only the path/URL branch is neutralized.
    opt.image_href_resolver.resolve_string = Box::new(|_href, _opts| None);

    let tree = usvg::Tree::from_str(svg, &opt).map_err(|e| SvgError::Parse(format!("{e}")))?;
    let size = tree.size();
    let natural_w = (size.width().ceil() as u32).max(1);
    let natural_h = (size.height().ceil() as u32).max(1);

    let mut scale = sizing.scale_for(natural_w, natural_h);
    let mut px_w = ((natural_w as f32 * scale).ceil() as u32).max(1);
    let mut px_h = ((natural_h as f32 * scale).ceil() as u32).max(1);
    // Clamp to the envelope so f32 ceiling rounding can never overshoot it
    // by a pixel — keeps the loader's subsequent `pre_resize` a true
    // no-op (it only ever downscales past the envelope).
    if let Some((max_w_px, max_h_px)) = sizing.envelope_px() {
        px_w = px_w.min(max_w_px).max(1);
        px_h = px_h.min(max_h_px).max(1);
    }
    // Bound the allocation even when no envelope applies — see
    // `MAX_RASTER_PIXELS`.  The shrink is folded into `scale` as well as
    // the dimensions because `scale` is the render transform: shrinking the
    // pixmap alone would crop the drawing instead of fitting it into it.
    let shrink = budget_shrink(px_w, px_h);
    if shrink < 1.0 {
        scale = (f64::from(scale) * shrink) as f32;
        px_w = ((f64::from(px_w) * shrink).floor() as u32).max(1);
        px_h = ((f64::from(px_h) * shrink).floor() as u32).max(1);
    }

    let mut pixmap = resvg::tiny_skia::Pixmap::new(px_w, px_h)
        .ok_or_else(|| SvgError::Raster(format!("pixmap alloc failed: {px_w}x{px_h}")))?;
    // Paint an opaque background first when requested.  Terminal image
    // protocols alpha-composite over whatever is already on the cell, so
    // a transparent SVG meant for a light page (Mermaid) needs the fill
    // to avoid the document background bleeding through its text.
    if let Some([r, g, b, a]) = background {
        pixmap.fill(resvg::tiny_skia::Color::from_rgba8(r, g, b, a));
    }
    resvg::render(
        &tree,
        resvg::tiny_skia::Transform::from_scale(scale, scale),
        &mut pixmap.as_mut(),
    );

    let png_bytes = pixmap
        .encode_png()
        .map_err(|e| SvgError::Raster(format!("png encode: {e}")))?;
    // The "decode through `ImageReader` + `Limits`" invariant in
    // `docs/dev/security-invariants.md` covers *external* bytes.  These are
    // the PNG we encoded one line above, from a pixmap whose dimensions are
    // already bounded by the envelope and `MAX_RASTER_PIXELS`, so there is
    // nothing left for a decode limit to constrain.  Don't copy this call
    // to a site whose bytes came from a file, a socket, or a document.
    image::load_from_memory(&png_bytes).map_err(|e| SvgError::Decode(format!("{e}")))
}

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

    fn natural(envelope: Option<(u16, u16)>) -> SvgSizing {
        SvgSizing {
            envelope,
            font_size: Some((8, 16)),
            mode: SvgScaleMode::Natural,
        }
    }

    fn fill(envelope: Option<(u16, u16)>) -> SvgSizing {
        SvgSizing {
            envelope,
            font_size: Some((8, 16)),
            mode: SvgScaleMode::Fill,
        }
    }

    // ── Natural sizing (SVG files) ────────────────────────────────────

    #[test]
    fn natural_small_svg_is_not_upscaled() {
        // 200×150 natural, envelope 80×24 at (8,16) → 640×384 px.  Natural
        // fits comfortably, so it must stay at its own size (downscale
        // only): a small icon does not balloon to fill the terminal.
        let svg = r##"<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="150" viewBox="0 0 200 150">
  <rect width="200" height="150" fill="#eef"/>
</svg>"##;
        let image = rasterize_svg(svg, natural(Some((80, 24))), None).expect("rasterize");
        assert_eq!(image.width(), 200);
        assert_eq!(image.height(), 150);
    }

    #[test]
    fn natural_large_svg_downscales_to_fit_envelope() {
        // 1600×1200 natural > envelope 640×384.  Fit scale =
        // min(640/1600, 384/1200) = 0.32 → 512×384 (height-axis limited).
        let svg = r##"<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1200" viewBox="0 0 1600 1200">
  <rect width="1600" height="1200" fill="#eef"/>
</svg>"##;
        let image = rasterize_svg(svg, natural(Some((80, 24))), None).expect("rasterize");
        assert!(image.width() <= 640);
        assert!(image.height() <= 384);
        assert_eq!(image.height(), 384);
    }

    #[test]
    fn natural_preserves_transparency_when_no_background() {
        // A 10×10 SVG that draws nothing leaves every pixel transparent.
        let svg = r##"<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10"></svg>"##;
        let image = rasterize_svg(svg, natural(None), None).expect("rasterize");
        let rgba = image.to_rgba8();
        assert_eq!(rgba.get_pixel(0, 0)[3], 0, "corner must stay transparent");
    }

    // ── Fill sizing (diagrams) ────────────────────────────────────────

    #[test]
    fn fill_small_svg_upscales_to_envelope() {
        // Same 200×150 small SVG, but Fill must scale it up:
        // min(640/200, 384/150) = 2.56 → 512×384 (height limits).
        let svg = r##"<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="150" viewBox="0 0 200 150">
  <rect width="200" height="150" fill="#eef"/>
</svg>"##;
        let image = rasterize_svg(svg, fill(Some((80, 24))), None).expect("rasterize");
        assert_eq!(image.height(), 384, "should fill the envelope height");
        assert_eq!(image.width(), 512);
    }

    #[test]
    fn fill_with_white_background_is_opaque() {
        let svg = r##"<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10"></svg>"##;
        let image = rasterize_svg(svg, fill(None), Some([255, 255, 255, 255])).expect("rasterize");
        let rgba = image.to_rgba8();
        let px = rgba.get_pixel(0, 0);
        assert_eq!(px[3], 255, "white fill must be opaque");
        assert_eq!([px[0], px[1], px[2]], [255, 255, 255]);
    }

    #[test]
    fn no_envelope_keeps_natural_size() {
        let svg = r##"<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="37" height="23" viewBox="0 0 37 23">
  <rect width="37" height="23" fill="#fff"/>
</svg>"##;
        let image = rasterize_svg(svg, natural(None), None).expect("rasterize");
        assert_eq!(image.width(), 37);
        assert_eq!(image.height(), 23);
    }

    // ── Absolute pixmap budget ────────────────────────────────────────

    /// Apply `budget_shrink` the way `rasterize_svg` does — floored, with
    /// the same one-pixel floor — so the assertions below test the
    /// dimensions actually allocated.
    fn shrunk(px_w: u32, px_h: u32) -> (u64, u64) {
        let shrink = budget_shrink(px_w, px_h);
        if shrink >= 1.0 {
            return (u64::from(px_w), u64::from(px_h));
        }
        (
            ((f64::from(px_w) * shrink).floor() as u64).max(1),
            ((f64::from(px_h) * shrink).floor() as u64).max(1),
        )
    }

    #[test]
    fn budget_shrink_leaves_ordinary_sizes_alone() {
        // Every enveloped path lands here: a few hundred thousand pixels is
        // orders of magnitude under the ceiling, so nothing is rescaled.
        assert_eq!(budget_shrink(800, 600), 1.0);
        assert_eq!(budget_shrink(512, 384), 1.0);
    }

    #[test]
    fn budget_shrink_caps_area_with_the_aspect_ratio_intact() {
        // 4000×3000 = 12 M px, three times the 4 M budget → shrink by
        // sqrt(1/3) ≈ 0.577.
        let (w, h) = shrunk(4000, 3000);
        assert!(w * h <= MAX_RASTER_PIXELS, "area {} over budget", w * h);
        let aspect = w as f64 / h as f64;
        assert!((aspect - 4.0 / 3.0).abs() < 1e-2, "aspect {aspect} drifted");
    }

    #[test]
    fn budget_shrink_caps_the_longest_side_of_a_sliver() {
        // 100 000 × 4 = 400 K px, comfortably inside the area budget — the
        // dimension cap is the only thing that catches it.
        let (w, h) = shrunk(100_000, 4);
        assert!(w <= u64::from(MAX_RASTER_DIM), "width {w} over the dim cap");
        assert!(h >= 1, "the short axis must not floor away to zero");
        assert!(w * h <= MAX_RASTER_PIXELS);
    }

    #[test]
    fn oversized_svg_without_an_envelope_is_scaled_into_the_budget() {
        // The `export::html` Mermaid path passes no envelope, so this is
        // the only thing standing between a crafted document and an
        // unbounded pixmap allocation.  4000×3000 natural must come back
        // inside the budget, still rendered (not refused) and still 4:3.
        let svg = r##"<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="4000" height="3000" viewBox="0 0 4000 3000">
  <rect width="4000" height="3000" fill="#eef"/>
</svg>"##;
        let image = rasterize_svg(svg, natural(None), None).expect("rasterize");
        let (w, h) = (u64::from(image.width()), u64::from(image.height()));
        assert!(
            w * h <= MAX_RASTER_PIXELS,
            "{w}x{h} = {} px exceeds the {MAX_RASTER_PIXELS} px budget",
            w * h
        );
        assert!(w <= u64::from(MAX_RASTER_DIM) && h <= u64::from(MAX_RASTER_DIM));
        assert!(w > h, "the 4:3 aspect ratio must survive the clamp");
    }

    #[test]
    fn image_href_to_local_file_is_not_loaded() {
        // Write a real opaque-red PNG and reference it by absolute path
        // from an `<image>` element.  Our resolver refuses path/URL hrefs,
        // so the element is dropped and the pixel where it would have
        // drawn stays transparent — the default usvg resolver would have
        // read the file and painted it red.
        let dir = tempfile::tempdir().unwrap();
        let png = dir.path().join("secret.png");
        let buf = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255]));
        image::DynamicImage::ImageRgba8(buf).save(&png).unwrap();

        let svg = format!(
            r##"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="10" height="10" viewBox="0 0 10 10"><image x="0" y="0" width="10" height="10" xlink:href="{}"/></svg>"##,
            png.display()
        );
        let image = rasterize_svg(&svg, natural(None), None).expect("rasterize");
        let rgba = image.to_rgba8();
        assert_eq!(
            rgba.get_pixel(5, 5)[3],
            0,
            "a local-file <image href> must not be loaded into the render"
        );
    }

    #[test]
    fn malformed_svg_returns_parse_error() {
        let err = rasterize_svg("not an svg at all", natural(None), None).unwrap_err();
        assert!(matches!(err, SvgError::Parse(_)));
    }
}