Skip to main content

egui_pop_viewport/graph/
export.rs

1//! A graph exported as an image: SVG drawn from the model and its
2//! layout (not from the screen), so it is crisp at any size and the same
3//! graph gives the same text.
4//!
5//! [`GraphExport`] is a copy of what the editor would draw: the nodes,
6//! wires and groups, the state's selection, collapsed nodes and folded
7//! groups, the wire style, and the theme's colours ([`ExportTheme`]).
8//! [`GraphExport::svg`] lays it out at a level ([`ExportOptions`]) and
9//! writes the SVG: group frames, then wires, then nodes and stacks, as
10//! the editor draws them; what only an interactive canvas shows (the
11//! grid, the selection's outline, the focus ring, the chevrons, the
12//! application's slot in title bars) is left out.
13//!
14//! [`GraphExport::png`] (feature `graph-png`) and [`GraphExport::pdf`]
15//! (feature `graph-pdf`) render that SVG, with the theme's installed
16//! faces ([`GraphExport::faces`]) so the labels match the screen.
17
18use std::collections::{BTreeMap, BTreeSet};
19use std::fmt::Write as _;
20
21use egui::{Color32, Pos2, Rect, pos2, vec2};
22use egui_pop_core::fonts::{self, InstalledFace, Role};
23use egui_pop_core::theme::Tokens;
24
25use super::model::{Edge, GraphModel, Group, Level, Node, Param, PortType, Side};
26use super::state::GraphState;
27use super::wires::{RouteCache, WireStyle};
28use super::{
29    GROUP_LABEL, GraphTokens, HEADER, LayoutIn, PAD, PORT_R, Placed, ROW, lay_out, overview_height,
30    param_h, wires_drawn,
31};
32
33/// What an export draws with: the theme's colours and text sizes,
34/// resolved, so that an export needs no `egui::Context`.
35#[derive(Clone, Debug, PartialEq)]
36pub struct ExportTheme {
37    /// The graph's colours (`graph.*`).
38    pub colors: GraphTokens,
39    /// The port types' colours, by token path ([`PortType::color`]); a
40    /// type missing here is drawn in the plain wire's colour.
41    pub types: BTreeMap<String, Color32>,
42    /// The CSS font family of the text (the theme's `font.family.ui`,
43    /// then `sans-serif`).
44    pub font_family: String,
45    /// The titles' size, in points.
46    pub body: f32,
47    /// The ports', parameters' and groups' labels' size, in points.
48    pub small: f32,
49    /// A parameter row's height, in graph units (the detail level).
50    pub param_h: f32,
51}
52
53impl ExportTheme {
54    /// The theme of a context, with the colours of a model's port types.
55    pub fn of(ctx: &egui::Context, model: &dyn GraphModel) -> ExportTheme {
56        ExportTheme::of_nodes(ctx, &model.nodes())
57    }
58
59    pub(super) fn of_nodes(ctx: &egui::Context, nodes: &[Node]) -> ExportTheme {
60        let t = Tokens::of(ctx);
61        let colors = GraphTokens::of(ctx);
62        let mut types = BTreeMap::new();
63        for n in nodes {
64            for p in n.inputs.iter().chain(&n.outputs) {
65                types
66                    .entry(p.ty.color.clone())
67                    .or_insert_with(|| colors.type_color(ctx, &p.ty));
68            }
69        }
70        let mut family: Vec<String> = t
71            .font
72            .family_ui
73            .iter()
74            .map(|f| {
75                if f.contains(|c: char| !c.is_ascii_alphanumeric() && c != '-') {
76                    format!("'{}'", f.replace(['\'', '"'], ""))
77                } else {
78                    f.clone()
79                }
80            })
81            .collect();
82        family.push("sans-serif".into());
83        ExportTheme {
84            colors,
85            types,
86            font_family: family.join(", "),
87            body: t.font.body,
88            small: t.font.small,
89            param_h: param_h(ctx),
90        }
91    }
92
93    fn type_color(&self, ty: &PortType) -> Color32 {
94        self.types
95            .get(&ty.color)
96            .copied()
97            .unwrap_or(self.colors.wire)
98    }
99}
100
101/// What an export draws.
102#[derive(Clone, Debug, PartialEq)]
103#[non_exhaustive]
104pub struct ExportOptions {
105    /// Only the selected nodes, the wires between them and the frames
106    /// of their groups (default `false`: the whole graph). An empty
107    /// selection gives an empty image.
108    pub selection: bool,
109    /// The level drawn (default [`Level::Ports`]): the overview's
110    /// compact nodes and stacks, the ports, or the detail with each
111    /// node's parameters and their values.
112    pub level: Level,
113    /// Fills the image with the graph's background (default `true`).
114    pub background: bool,
115    /// Around the drawing, in graph units (default 24).
116    pub margin: f32,
117    /// The image's title, for screen readers (default "Node graph").
118    pub title: Option<String>,
119}
120
121impl Default for ExportOptions {
122    fn default() -> Self {
123        ExportOptions {
124            selection: false,
125            level: Level::Ports,
126            background: true,
127            margin: 24.0,
128            title: None,
129        }
130    }
131}
132
133impl ExportOptions {
134    pub fn selection(mut self, on: bool) -> Self {
135        self.selection = on;
136        self
137    }
138
139    pub fn level(mut self, level: Level) -> Self {
140        self.level = level;
141        self
142    }
143
144    pub fn background(mut self, on: bool) -> Self {
145        self.background = on;
146        self
147    }
148
149    pub fn margin(mut self, margin: f32) -> Self {
150        self.margin = margin.max(0.0);
151        self
152    }
153
154    pub fn title(mut self, title: impl Into<String>) -> Self {
155        self.title = Some(title.into());
156        self
157    }
158}
159
160/// Why a PNG or PDF export failed.
161#[derive(Clone, Debug, PartialEq)]
162#[non_exhaustive]
163pub enum ExportError {
164    /// The image would be empty (an empty graph without a margin), the
165    /// scale is not a positive number, or a side would pass
166    /// [`GraphExport::MAX_SIDE`] pixels.
167    Size(String),
168    /// The SVG could not be read back to render it.
169    Svg(String),
170    /// The PDF could not be written.
171    Pdf(String),
172}
173
174impl std::fmt::Display for ExportError {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        match self {
177            ExportError::Size(e) => write!(f, "image size: {e}"),
178            ExportError::Svg(e) => write!(f, "SVG: {e}"),
179            ExportError::Pdf(e) => write!(f, "PDF: {e}"),
180        }
181    }
182}
183
184impl std::error::Error for ExportError {}
185
186#[cfg(any(feature = "graph-png", feature = "graph-pdf"))]
187mod fonts_db;
188#[cfg(feature = "graph-pdf")]
189mod pdf;
190
191/// A graph ready to export: an owned copy of what the editor draws,
192/// kept as long as needed (an agent's `graph.export` reads the copy the
193/// editor kept at its last frame).
194#[derive(Clone, Debug, PartialEq)]
195pub struct GraphExport {
196    nodes: Vec<Node>,
197    /// Each node's parameters, by index.
198    params: Vec<Vec<Param>>,
199    edges: Vec<Edge>,
200    groups: Vec<Group>,
201    selection: BTreeSet<String>,
202    collapsed: BTreeSet<String>,
203    folded: BTreeSet<String>,
204    unfolded: BTreeSet<String>,
205    wires: WireStyle,
206    node_width: f32,
207    theme: ExportTheme,
208    /// The faces the PNG and PDF exports draw text with.
209    faces: Vec<InstalledFace>,
210}
211
212impl GraphExport {
213    /// A model with an editor's state (the wire style and node width it
214    /// drew last), in a context's theme.
215    pub fn capture(ctx: &egui::Context, model: &dyn GraphModel, state: &GraphState) -> GraphExport {
216        let nodes = model.nodes();
217        let theme = ExportTheme::of_nodes(ctx, &nodes);
218        GraphExport::from_parts(model, nodes, model.edges(), model.groups(), state, theme)
219            .faces(fonts::installed_faces(ctx, Role::Ui).unwrap_or_default())
220    }
221
222    /// A model with an editor's state, in a theme of the caller's (a
223    /// light export of a dark interface, a test's fixed colours). Its
224    /// text is drawn in egui's bundled faces unless [`GraphExport::faces`]
225    /// gives others.
226    pub fn with_theme(
227        model: &dyn GraphModel,
228        state: &GraphState,
229        theme: ExportTheme,
230    ) -> GraphExport {
231        GraphExport::from_parts(
232            model,
233            model.nodes(),
234            model.edges(),
235            model.groups(),
236            state,
237            theme,
238        )
239    }
240
241    pub(super) fn from_parts(
242        model: &dyn GraphModel,
243        nodes: Vec<Node>,
244        edges: Vec<Edge>,
245        groups: Vec<Group>,
246        state: &GraphState,
247        theme: ExportTheme,
248    ) -> GraphExport {
249        let params = nodes.iter().map(|n| model.params(&n.id)).collect();
250        GraphExport {
251            nodes,
252            params,
253            edges,
254            groups,
255            selection: state.selection.clone(),
256            collapsed: state.collapsed.clone(),
257            folded: state.folded.clone(),
258            unfolded: state.unfolded.clone(),
259            wires: state.wire_style,
260            node_width: state.node_width,
261            theme,
262            faces: Vec::new(),
263        }
264    }
265
266    /// How wires are drawn (by default the style the editor drew last).
267    pub fn wires(mut self, style: WireStyle) -> Self {
268        self.wires = style;
269        self
270    }
271
272    /// A node's width in graph units (by default the editor's last).
273    pub fn node_width(mut self, width: f32) -> Self {
274        self.node_width = width.max(80.0);
275        self
276    }
277
278    /// The faces the PNG and PDF exports draw text with, in order (the
279    /// first found for a family wins, the others fill in missing
280    /// characters); by default the theme's installed faces
281    /// ([`fonts::installed_faces`]) when captured from a context. egui's
282    /// bundled faces always come after them, so text never vanishes.
283    /// The SVG names the theme's families and leaves fonts to its reader.
284    pub fn faces(mut self, faces: Vec<InstalledFace>) -> Self {
285        self.faces = faces;
286        self
287    }
288
289    /// The theme it is drawn in.
290    pub fn theme(&self) -> &ExportTheme {
291        &self.theme
292    }
293
294    /// The selected nodes, as captured.
295    pub fn selection(&self) -> &BTreeSet<String> {
296        &self.selection
297    }
298
299    /// The graph as an SVG document, in graph units (a point at 100 %
300    /// is one unit): `<svg>` with a `viewBox` around what is drawn and
301    /// the margin. Every node is a `<g data-node="id">`, every wire a
302    /// `<path data-edge="node.port->node.port">`, every group frame a
303    /// `<g data-group="id">`, every stack a `<g data-stack="id">`.
304    pub fn svg(&self, options: &ExportOptions) -> String {
305        let keep: Vec<usize> = (0..self.nodes.len())
306            .filter(|&i| !options.selection || self.selection.contains(&self.nodes[i].id))
307            .collect();
308        let nodes: Vec<Node> = keep.iter().map(|&i| self.nodes[i].clone()).collect();
309        let params: Vec<&[Param]> = keep.iter().map(|&i| self.params[i].as_slice()).collect();
310        let ids: BTreeSet<&str> = nodes.iter().map(|n| n.id.as_str()).collect();
311        let edges: Vec<Edge> = self
312            .edges
313            .iter()
314            .filter(|e| ids.contains(e.from.node.as_str()) && ids.contains(e.to.node.as_str()))
315            .cloned()
316            .collect();
317        let level = options.level;
318        let folded: Vec<bool> = self
319            .groups
320            .iter()
321            .map(|g| {
322                if level == Level::Overview {
323                    !self.unfolded.contains(&g.id)
324                } else {
325                    self.folded.contains(&g.id)
326                }
327            })
328            .collect();
329        let theme = &self.theme;
330        let overview_h = overview_height(theme.body, 1.0);
331        let lay = lay_out(&LayoutIn {
332            nodes: &nodes,
333            groups: &self.groups,
334            folded: &folded,
335            collapsed: &self.collapsed,
336            level,
337            node_width: self.node_width,
338            overview_h,
339            param_h: theme.param_h,
340            params: &|i| params[i].len(),
341            pos: &|n| pos2(n.pos[0], n.pos[1]),
342        });
343
344        // The wires, as polylines or curves.
345        let drawn = wires_drawn(&nodes, &edges, &lay, None);
346        let routes: Vec<Vec<Pos2>> = match self.wires {
347            WireStyle::Orthogonal => {
348                let boxes: Vec<Rect> = lay.boxes.iter().map(|b| b.rect).collect();
349                let ends: Vec<(Pos2, Pos2)> = drawn.iter().map(|&(_, a, b)| (a, b)).collect();
350                RouteCache::default().routes(&boxes, &ends).to_vec()
351            }
352            WireStyle::Straight => drawn.iter().map(|&(_, a, b)| vec![a, b]).collect(),
353            WireStyle::Curves => drawn
354                .iter()
355                .map(|&(_, a, b)| {
356                    let [_, c1, c2, _] = curve(a, b);
357                    vec![a, c1, c2, b]
358                })
359                .collect(),
360        };
361
362        // What the image covers.
363        let mut bounds = Rect::NOTHING;
364        for b in &lay.boxes {
365            let mut r = b.rect;
366            if b.node.is_none() {
367                // A stack's edges behind.
368                r.max += vec2(12.0, 12.0);
369            }
370            bounds = bounds.union(r);
371        }
372        for (_, r) in &lay.frames {
373            bounds = bounds.union(*r);
374        }
375        for points in &routes {
376            for p in points {
377                bounds.extend_with(*p);
378            }
379        }
380        if !bounds.is_positive() {
381            bounds = Rect::from_min_size(Pos2::ZERO, vec2(0.0, 0.0));
382        }
383        let bounds = bounds.expand(options.margin);
384
385        let mut w = Svg::default();
386        let title = options.title.as_deref().unwrap_or("Node graph");
387        let _ = write!(
388            w.out,
389            "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{}\" height=\"{}\" viewBox=\"{} {} {} {}\" role=\"img\" font-family=\"{}\">\n<title>{}</title>\n",
390            num(bounds.width()),
391            num(bounds.height()),
392            num(bounds.min.x),
393            num(bounds.min.y),
394            num(bounds.width()),
395            num(bounds.height()),
396            escape(&theme.font_family),
397            escape(title),
398        );
399        if options.background {
400            let _ = writeln!(
401                w.out,
402                "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"{}/>",
403                num(bounds.min.x),
404                num(bounds.min.y),
405                num(bounds.width()),
406                num(bounds.height()),
407                paint("fill", theme.colors.background),
408            );
409        }
410
411        let members = |g: usize| -> usize {
412            let id = self.groups[g].id.as_str();
413            nodes
414                .iter()
415                .filter(|n| n.group.as_deref() == Some(id))
416                .count()
417        };
418
419        // Group frames.
420        for &(g, r) in &lay.frames {
421            let group = &self.groups[g];
422            let _ = writeln!(w.out, "<g data-group=\"{}\">", escape(&group.id));
423            w.rect(
424                r,
425                6.0,
426                &paint("fill", theme.colors.group.gamma_multiply(0.45)),
427            );
428            w.border(r, 6.0, 1.0, theme.colors.group_border);
429            let band = Rect::from_min_size(r.min, vec2(r.width(), GROUP_LABEL));
430            w.text(
431                band.left_center() + vec2(PAD + 2.0, 0.0),
432                Anchor::Start,
433                &group.label,
434                theme.small,
435                theme.colors.text_muted,
436                None,
437            );
438            w.out.push_str("</g>\n");
439        }
440
441        // Wires.
442        if !drawn.is_empty() {
443            w.out.push_str(
444                "<g fill=\"none\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n",
445            );
446            for ((e, _, _), points) in drawn.iter().zip(&routes) {
447                let color = nodes
448                    .iter()
449                    .find(|n| n.id == e.from.node)
450                    .and_then(|n| n.port(Side::Output, &e.from.port))
451                    .map_or(theme.colors.wire, |p| theme.type_color(&p.ty));
452                let mut d = String::new();
453                match (self.wires, points.as_slice()) {
454                    (WireStyle::Curves, [a, c1, c2, b]) => {
455                        let _ = write!(
456                            d,
457                            "M{} {}C{} {} {} {} {} {}",
458                            num(a.x),
459                            num(a.y),
460                            num(c1.x),
461                            num(c1.y),
462                            num(c2.x),
463                            num(c2.y),
464                            num(b.x),
465                            num(b.y)
466                        );
467                    }
468                    _ => {
469                        for (k, p) in points.iter().enumerate() {
470                            let _ = write!(
471                                d,
472                                "{}{} {}",
473                                if k == 0 { "M" } else { "L" },
474                                num(p.x),
475                                num(p.y)
476                            );
477                        }
478                    }
479                }
480                let _ = writeln!(
481                    w.out,
482                    "<path data-edge=\"{}.{}-&gt;{}.{}\" d=\"{}\"{}/>",
483                    escape(&e.from.node),
484                    escape(&e.from.port),
485                    escape(&e.to.node),
486                    escape(&e.to.port),
487                    d,
488                    paint("stroke", color),
489                );
490            }
491            w.out.push_str("</g>\n");
492        }
493
494        // Nodes and stacks.
495        let title_size = if level == Level::Overview {
496            (overview_h * 0.45).round()
497        } else {
498            theme.body
499        };
500        for b in &lay.boxes {
501            match b.node {
502                Some(i) => self.node(&mut w, &lay, b, i, &nodes[i], params[i], level, title_size),
503                None => {
504                    if let Some(g) = b.group {
505                        self.stack(&mut w, b, g, members(g), title_size);
506                    }
507                }
508            }
509        }
510        w.out.push_str("</svg>\n");
511        w.out
512    }
513
514    /// The longest side of a PNG export, in pixels.
515    pub const MAX_SIDE: u32 = 16_384;
516
517    /// The graph as a PNG image (feature `graph-png`): [`GraphExport::svg`]
518    /// rendered by resvg at `scale` pixels per graph unit (1 for a point
519    /// at 100 %, 2 for a high density screen), its text in
520    /// [`GraphExport::faces`] then egui's bundled faces. Transparent
521    /// without the background. The same graph, options and scale give
522    /// the same bytes.
523    #[cfg(feature = "graph-png")]
524    pub fn png(&self, options: &ExportOptions, scale: f32) -> Result<Vec<u8>, ExportError> {
525        use resvg::{tiny_skia, usvg};
526        if !(scale.is_finite() && scale > 0.0) {
527            return Err(ExportError::Size(format!("scale {scale} is not positive")));
528        }
529        let svg = self.svg(options);
530        let (db, family) = fonts_db::database(&self.faces);
531        let opts = usvg::Options {
532            font_family: family,
533            fontdb: std::sync::Arc::new(db),
534            ..usvg::Options::default()
535        };
536        let tree = usvg::Tree::from_str(&svg, &opts).map_err(|e| match e {
537            usvg::Error::InvalidSize => ExportError::Size("the image is empty".into()),
538            e => ExportError::Svg(e.to_string()),
539        })?;
540        let size = tree.size();
541        let side = |v: f32| (v * scale).ceil();
542        let (w, h) = (side(size.width()), side(size.height()));
543        let max = Self::MAX_SIDE as f32;
544        if !(w <= max && h <= max) {
545            return Err(ExportError::Size(format!(
546                "{w} × {h} pixels, more than {} on a side",
547                Self::MAX_SIDE
548            )));
549        }
550        let mut pixmap = tiny_skia::Pixmap::new(w as u32, h as u32)
551            .ok_or_else(|| ExportError::Size("the image is empty".into()))?;
552        resvg::render(
553            &tree,
554            tiny_skia::Transform::from_scale(scale, scale),
555            &mut pixmap.as_mut(),
556        );
557        pixmap
558            .encode_png()
559            .map_err(|e| ExportError::Svg(e.to_string()))
560    }
561
562    /// The graph as a one-page PDF (feature `graph-pdf`):
563    /// [`GraphExport::svg`] converted by svg2pdf, a graph unit a PDF
564    /// point, its text kept as text in [`GraphExport::faces`] then
565    /// egui's bundled faces, each embedded as a subset. The metadata is
566    /// fixed (the title, `egui-pop` as producer, no date), and the
567    /// objects are written in a canonical order, so the same graph and
568    /// options give the same bytes.
569    #[cfg(feature = "graph-pdf")]
570    pub fn pdf(&self, options: &ExportOptions) -> Result<Vec<u8>, ExportError> {
571        use svg2pdf::usvg;
572        let svg = self.svg(options);
573        let (db, family) = fonts_db::database(&self.faces);
574        let opts = usvg::Options {
575            font_family: family,
576            fontdb: std::sync::Arc::new(db),
577            ..usvg::Options::default()
578        };
579        let tree = usvg::Tree::from_str(&svg, &opts).map_err(|e| match e {
580            usvg::Error::InvalidSize => ExportError::Size("the image is empty".into()),
581            e => ExportError::Svg(e.to_string()),
582        })?;
583        let bytes = svg2pdf::to_pdf(
584            &tree,
585            svg2pdf::ConversionOptions::default(),
586            svg2pdf::PageOptions::default(),
587        )
588        .map_err(|e| ExportError::Pdf(e.to_string()))?;
589        let title = options.title.as_deref().unwrap_or("Node graph");
590        pdf::canonical(&bytes, title)
591            .ok_or_else(|| ExportError::Pdf("svg2pdf's output could not be read back".into()))
592    }
593
594    fn stack(&self, w: &mut Svg, b: &Placed, g: usize, count: usize, size: f32) {
595        let t = &self.theme.colors;
596        let r = b.rect;
597        let group = &self.groups[g];
598        let _ = writeln!(w.out, "<g data-stack=\"{}\">", escape(&group.id));
599        for k in [2.0, 1.0] {
600            let back = r.translate(vec2(6.0, 6.0) * k);
601            w.rect(back, 6.0, &paint("fill", t.node_header));
602            w.border(back, 6.0, 1.0, t.node_border);
603        }
604        w.rect(r, 6.0, &paint("fill", t.node));
605        w.border(r, 6.0, 1.0, t.node_border);
606        let text_r = Rect::from_min_max(
607            r.min + vec2(PAD * 2.0, 0.0),
608            pos2(r.right() - PAD * 2.0 - size * 2.0, r.max.y),
609        );
610        w.text(
611            text_r.left_center(),
612            Anchor::Start,
613            &group.label,
614            size,
615            t.text,
616            Some(text_r),
617        );
618        w.text(
619            r.right_center() - vec2(PAD * 2.0, 0.0),
620            Anchor::End,
621            &format!("+{count}"),
622            size * 0.85,
623            t.text_muted,
624            None,
625        );
626        w.out.push_str("</g>\n");
627    }
628
629    #[allow(
630        clippy::too_many_arguments,
631        reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
632    )]
633    fn node(
634        &self,
635        w: &mut Svg,
636        lay: &super::Layout,
637        b: &Placed,
638        i: usize,
639        n: &Node,
640        params: &[Param],
641        level: Level,
642        title_size: f32,
643    ) {
644        let theme = &self.theme;
645        let t = &theme.colors;
646        let r = b.rect;
647        let overview = level == Level::Overview;
648        let header_h = if overview { r.height() } else { HEADER };
649        let header = Rect::from_min_size(r.min, vec2(r.width(), header_h));
650        let _ = writeln!(w.out, "<g data-node=\"{}\">", escape(&n.id));
651        w.rect(r, 6.0, &paint("fill", t.node));
652        if !overview {
653            let low = if b.collapsed { 6.0 } else { 0.0 };
654            w.path(header, [6.0, 6.0, low, low], &paint("fill", t.node_header));
655        }
656        // The colour of what it gives, as a band on the left.
657        if let Some(p) = n.outputs.first().or(n.inputs.first()) {
658            let band = Rect::from_min_size(r.min, vec2(4.0, header.height()));
659            let low = if overview || b.collapsed { 6.0 } else { 0.0 };
660            w.path(
661                band,
662                [6.0, 0.0, 0.0, low],
663                &paint("fill", theme.type_color(&p.ty)),
664            );
665        }
666        w.border(r, 6.0, 1.0, t.node_border);
667        let text_r = Rect::from_min_max(
668            pos2(r.left() + PAD * 2.0, header.top()),
669            pos2(header.right() - PAD, header.bottom()),
670        );
671        w.text(
672            text_r.left_center(),
673            Anchor::Start,
674            &n.title,
675            title_size,
676            t.text,
677            Some(text_r),
678        );
679        if overview || b.collapsed {
680            w.out.push_str("</g>\n");
681            return;
682        }
683        // Ports.
684        for (side, list) in [(Side::Input, &n.inputs), (Side::Output, &n.outputs)] {
685            for (k, port) in list.iter().enumerate() {
686                let Some(&at) = lay.ports.get(&(i, side, k)) else {
687                    continue;
688                };
689                let color = theme.type_color(&port.ty);
690                let wired = self.edges.iter().any(|e| match side {
691                    Side::Input => e.to.node == n.id && e.to.port == port.id,
692                    Side::Output => e.from.node == n.id && e.from.port == port.id,
693                });
694                let _ = writeln!(
695                    w.out,
696                    "<circle data-port=\"{}\" data-side=\"{}\" cx=\"{}\" cy=\"{}\" r=\"{}\"{}{} stroke-width=\"1.5\"/>",
697                    escape(&port.id),
698                    side.name(),
699                    num(at.x),
700                    num(at.y),
701                    num(PORT_R),
702                    paint("fill", if wired { color } else { t.node }),
703                    paint("stroke", color),
704                );
705                let (text_at, anchor) = match side {
706                    Side::Input => (at + vec2(PORT_R + 5.0, 0.0), Anchor::Start),
707                    Side::Output => (at - vec2(PORT_R + 5.0, 0.0), Anchor::End),
708                };
709                w.text(
710                    text_at,
711                    anchor,
712                    &port.label,
713                    theme.small,
714                    t.text_muted,
715                    None,
716                );
717            }
718        }
719        if level != Level::Detail {
720            w.out.push_str("</g>\n");
721            return;
722        }
723        // Parameters: each a row with its label, its value and how far
724        // along its range it is.
725        let rows = n.inputs.len().max(n.outputs.len());
726        let h = theme.param_h;
727        let mut y = r.top() + HEADER + rows as f32 * ROW;
728        for p in params {
729            let row = Rect::from_min_size(
730                pos2(r.left() + PAD * 2.0, y + 2.0),
731                vec2(r.width() - PAD * 4.0, h - 4.0),
732            );
733            y += h;
734            let _ = writeln!(w.out, "<g data-param=\"{}\">", escape(&p.id));
735            w.rect(row, 4.0, &paint("fill", t.node_header));
736            let span = p.range.end() - p.range.start();
737            let along = if span > 0.0 {
738                ((p.value - p.range.start()) / span).clamp(0.0, 1.0) as f32
739            } else {
740                0.0
741            };
742            if along > 0.0 {
743                let fill = Rect::from_min_size(row.min, vec2(row.width() * along, row.height()));
744                w.rect(
745                    fill,
746                    4.0,
747                    &paint("fill", t.node_selected.gamma_multiply(0.35)),
748                );
749            }
750            w.text(
751                row.left_center() + vec2(PAD, 0.0),
752                Anchor::Start,
753                &p.label,
754                theme.small,
755                t.text_muted,
756                None,
757            );
758            w.text(
759                row.right_center() - vec2(PAD, 0.0),
760                Anchor::End,
761                &value_text(p),
762                theme.small,
763                t.text,
764                None,
765            );
766            w.out.push_str("</g>\n");
767        }
768        w.out.push_str("</g>\n");
769    }
770}
771
772/// A wire's curve from an output at `a` to an input at `b`: its four
773/// control points, as the editor draws it.
774pub(super) fn curve(a: Pos2, b: Pos2) -> [Pos2; 4] {
775    let dx = ((b.x - a.x).abs() * 0.5).max(40.0);
776    [a, a + vec2(dx, 0.0), b - vec2(dx, 0.0), b]
777}
778
779/// A parameter's value as text: as many decimals as its step has (two
780/// without a step), then its unit.
781fn value_text(p: &Param) -> String {
782    let decimals = match p.step {
783        Some(step) if step > 0.0 => {
784            let mut d = 0;
785            while d < 6 && ((step * 10f64.powi(d)).round() - step * 10f64.powi(d)).abs() > 1e-9 {
786                d += 1;
787            }
788            d as usize
789        }
790        _ => 2,
791    };
792    let mut v = format!("{:.*}", decimals, p.value);
793    if v.starts_with('-') && v[1..].chars().all(|c| c == '0' || c == '.') {
794        v.remove(0);
795    }
796    match &p.unit {
797        Some(u) if !u.is_empty() => format!("{v} {u}"),
798        _ => v,
799    }
800}
801
802/// Where a text sits from its point.
803#[derive(Clone, Copy)]
804enum Anchor {
805    Start,
806    End,
807}
808
809/// The document being written.
810#[derive(Default)]
811struct Svg {
812    out: String,
813    /// Clip paths written, for their ids.
814    clips: usize,
815}
816
817impl Svg {
818    fn rect(&mut self, r: Rect, radius: f32, paint: &str) {
819        let rx = radius.min(r.width() / 2.0).min(r.height() / 2.0).max(0.0);
820        let _ = writeln!(
821            self.out,
822            "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" rx=\"{}\"{paint}/>",
823            num(r.min.x),
824            num(r.min.y),
825            num(r.width()),
826            num(r.height()),
827            num(rx),
828        );
829    }
830
831    /// A stroke inside a rectangle's edges, as egui's `StrokeKind::Inside`.
832    fn border(&mut self, r: Rect, radius: f32, width: f32, color: Color32) {
833        let inner = r.shrink(width / 2.0);
834        let rx = (radius - width / 2.0)
835            .min(inner.width() / 2.0)
836            .min(inner.height() / 2.0)
837            .max(0.0);
838        let _ = writeln!(
839            self.out,
840            "<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" rx=\"{}\" fill=\"none\"{} stroke-width=\"{}\"/>",
841            num(inner.min.x),
842            num(inner.min.y),
843            num(inner.width()),
844            num(inner.height()),
845            num(rx),
846            paint("stroke", color),
847            num(width),
848        );
849    }
850
851    /// A rectangle with its own radius at each corner: north-west,
852    /// north-east, south-east, south-west.
853    fn path(&mut self, r: Rect, radii: [f32; 4], paint: &str) {
854        let most = (r.width() / 2.0).min(r.height() / 2.0).max(0.0);
855        let [nw, ne, se, sw] = radii.map(|v| v.clamp(0.0, most));
856        let (l, t, rr, b) = (r.left(), r.top(), r.right(), r.bottom());
857        let mut d = format!("M{} {}H{}", num(l + nw), num(t), num(rr - ne));
858        let arc = |d: &mut String, radius: f32, x: f32, y: f32| {
859            if radius > 0.0 {
860                let _ = write!(
861                    d,
862                    "A{} {} 0 0 1 {} {}",
863                    num(radius),
864                    num(radius),
865                    num(x),
866                    num(y)
867                );
868            }
869        };
870        arc(&mut d, ne, rr, t + ne);
871        let _ = write!(d, "V{}", num(b - se));
872        arc(&mut d, se, rr - se, b);
873        let _ = write!(d, "H{}", num(l + sw));
874        arc(&mut d, sw, l, b - sw);
875        let _ = write!(d, "V{}", num(t + nw));
876        arc(&mut d, nw, l + nw, t);
877        d.push('Z');
878        let _ = writeln!(self.out, "<path d=\"{d}\"{paint}/>");
879    }
880
881    /// A line of text centred on `at` vertically, cut to `clip` if given.
882    fn text(
883        &mut self,
884        at: Pos2,
885        anchor: Anchor,
886        text: &str,
887        size: f32,
888        color: Color32,
889        clip: Option<Rect>,
890    ) {
891        let clip_attr = match clip {
892            Some(c) => {
893                let id = format!("clip-{}", self.clips);
894                self.clips += 1;
895                let _ = writeln!(
896                    self.out,
897                    "<clipPath id=\"{id}\"><rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"/></clipPath>",
898                    num(c.min.x),
899                    num(c.min.y),
900                    num(c.width().max(0.0)),
901                    num(c.height().max(0.0)),
902                );
903                format!(" clip-path=\"url(#{id})\"")
904            }
905            None => String::new(),
906        };
907        let anchor = match anchor {
908            Anchor::Start => "",
909            Anchor::End => " text-anchor=\"end\"",
910        };
911        let _ = writeln!(
912            self.out,
913            "<text x=\"{}\" y=\"{}\" dy=\"0.35em\" font-size=\"{}\"{anchor}{}{clip_attr}>{}</text>",
914            num(at.x),
915            num(at.y),
916            num(size),
917            paint("fill", color),
918            escape(text),
919        );
920    }
921}
922
923/// A number as SVG writes it: at most two decimals, no trailing zeros,
924/// never `-0`.
925fn num(v: f32) -> String {
926    if !v.is_finite() {
927        return "0".into();
928    }
929    let s = format!("{:.2}", (v * 100.0).round() / 100.0);
930    let s = s.trim_end_matches('0').trim_end_matches('.');
931    if s == "-0" || s.is_empty() {
932        "0".into()
933    } else {
934        s.to_string()
935    }
936}
937
938/// A colour attribute (`fill`, `stroke`), with its opacity when it is
939/// not opaque.
940fn paint(attr: &str, c: Color32) -> String {
941    let [r, g, b, a] = c.to_srgba_unmultiplied();
942    let mut s = format!(" {attr}=\"#{r:02x}{g:02x}{b:02x}\"");
943    if a < 255 {
944        let _ = write!(s, " {attr}-opacity=\"{}\"", num(f32::from(a) / 255.0));
945    }
946    s
947}
948
949/// Text and attribute values, escaped for XML.
950fn escape(s: &str) -> String {
951    let mut out = String::with_capacity(s.len());
952    for c in s.chars() {
953        match c {
954            '&' => out.push_str("&amp;"),
955            '<' => out.push_str("&lt;"),
956            '>' => out.push_str("&gt;"),
957            '"' => out.push_str("&quot;"),
958            '\'' => out.push_str("&apos;"),
959            // Not allowed in XML 1.0.
960            c if (c as u32) < 0x20 && !matches!(c, '\t' | '\n' | '\r') => {}
961            c => out.push(c),
962        }
963    }
964    out
965}
966
967#[cfg(test)]
968mod tests {
969    use super::*;
970
971    #[test]
972    fn numbers_are_short_and_never_negative_zero() {
973        assert_eq!(num(1.0), "1");
974        assert_eq!(num(1.5), "1.5");
975        assert_eq!(num(-0.001), "0");
976        assert_eq!(num(2.345_67), "2.35");
977        assert_eq!(num(f32::NAN), "0");
978    }
979
980    #[test]
981    fn colours_carry_their_opacity() {
982        assert_eq!(
983            paint("fill", Color32::from_rgb(255, 0, 16)),
984            " fill=\"#ff0010\""
985        );
986        let half = Color32::from_rgba_unmultiplied(0, 0, 0, 128);
987        assert!(paint("stroke", half).contains("stroke-opacity=\"0.5\""));
988    }
989
990    #[test]
991    fn text_is_escaped() {
992        assert_eq!(escape("a<b & \"c\"\u{1}"), "a&lt;b &amp; &quot;c&quot;");
993    }
994
995    #[test]
996    fn values_take_their_step_s_decimals() {
997        let p = Param::new("r", "Radius", 2.0, 0.0..=10.0)
998            .step(0.1)
999            .unit("px");
1000        assert_eq!(value_text(&p), "2.0 px");
1001        let p = Param::new("e", "Exposure", -0.0001, -3.0..=3.0).step(0.01);
1002        assert_eq!(value_text(&p), "0.00");
1003        let p = Param::new("n", "Count", 3.0, 0.0..=10.0).step(1.0);
1004        assert_eq!(value_text(&p), "3");
1005    }
1006}