Skip to main content

source_mesh_core/export/
graphml.rs

1use std::io::Write;
2
3use anyhow::Context as _;
4use anyhow::Result;
5use anyhow::ensure;
6
7use super::edge_style::CYCLE_EDGE_WIDTH;
8use super::edge_style::TEST_EDGE_COLOR;
9use super::edge_style::edge_label;
10use super::edge_style::kind_name;
11use super::exporter::Exporter;
12use super::exporter::Options;
13use super::structure::Folder;
14use super::structure::IndexedGraph;
15use crate::cycle_presentation::group_color;
16use crate::model::DependencyKind;
17use crate::model::FolderGraph;
18
19pub(super) const GRAPHML_NAMESPACE: &str = "http://graphml.graphdrawing.org/xmlns";
20pub(super) const YWORKS_NAMESPACE: &str = "http://www.yworks.com/xml/graphml";
21
22pub struct GraphMl;
23
24struct Position {
25    horizontal: usize,
26    vertical: usize,
27}
28
29struct NodeVisual<'label> {
30    index: usize,
31    label: &'label str,
32    display_label: &'label str,
33    position: Position,
34    width: usize,
35    height: usize,
36}
37
38impl<'label> NodeVisual<'label> {
39    #[must_use]
40    fn new(index: usize, label: &'label str, position: Position) -> Self {
41        Self {
42            index,
43            label,
44            display_label: label,
45            position,
46            width: label.lines().map(|line| line.chars().count()).max().unwrap_or(0) * 8 + 40,
47            height: label.lines().count().max(1) * 20 + 20,
48        }
49    }
50
51    fn write_leaf(&self, output: &mut dyn Write) -> Result<()> {
52        let index = self.index;
53        let label = escaped_label(self.label);
54        let display_label = escaped_label(self.display_label);
55        let horizontal_position = self.position.horizontal;
56        let vertical_position = self.position.vertical;
57        let width = self.width;
58        let height = self.height;
59        writeln!(
60            output,
61            r##"    <node id="n{index}">
62      <data key="label">{label}</data>
63      <data key="ng">
64        <y:ShapeNode>
65          <y:Geometry x="{horizontal_position}" y="{vertical_position}" width="{width}" height="{height}"/>
66          <y:Fill color="#E8F0FE" transparent="false"/>
67          <y:BorderStyle color="#47699B" type="line" width="1.0"/>
68          <y:NodeLabel modelName="internal" modelPosition="c" xml:space="preserve">{display_label}</y:NodeLabel>
69          <y:Shape type="roundrectangle"/>
70        </y:ShapeNode>
71      </data>
72    </node>"##
73        )?;
74        Ok(())
75    }
76
77    fn write_group_start(&self, output: &mut dyn Write) -> Result<()> {
78        let index = self.index;
79        let label = escaped_label(self.label);
80        let display_label = escaped_label(self.display_label);
81        let horizontal_position = self.position.horizontal;
82        let vertical_position = self.position.vertical;
83        writeln!(
84            output,
85            r#"    <node id="n{index}" yfiles.foldertype="group">
86      <data key="label">{label}</data>
87      <data key="ng">
88        <y:ProxyAutoBoundsNode>
89          <y:Realizers active="0">"#
90        )?;
91        for closed in [false, true] {
92            let (width, height) = if closed { (160, 50) } else { (self.width, self.height) };
93            writeln!(
94                output,
95                r##"            <y:GroupNode>
96              <y:Geometry x="{horizontal_position}" y="{vertical_position}" width="{width}" height="{height}"/>
97              <y:Fill color="#F5F7FB" transparent="false"/>
98              <y:BorderStyle color="#47699B" type="line" width="1.0"/>
99              <y:NodeLabel modelName="internal" modelPosition="t" fontStyle="bold" backgroundColor="#DCE6F5" autoSizePolicy="node_width" xml:space="preserve">{display_label}</y:NodeLabel>
100              <y:Shape type="roundrectangle"/>
101              <y:State closed="{closed}" innerGraphDisplayEnabled="false"/>
102              <y:Insets top="20" bottom="20" left="20" right="20"/>
103              <y:BorderInsets top="0" bottom="0" left="0" right="0"/>
104            </y:GroupNode>"##
105            )?;
106        }
107        writeln!(
108            output,
109            r#"          </y:Realizers>
110        </y:ProxyAutoBoundsNode>
111      </data>
112      <graph id="n{index}:" edgedefault="directed">"#
113        )?;
114        Ok(())
115    }
116}
117
118struct LayoutNode<'label> {
119    visual: NodeVisual<'label>,
120    children: Vec<Self>,
121}
122
123impl<'label> LayoutNode<'label> {
124    #[must_use]
125    fn new(folder: &Folder<'label>, position: Position) -> Self {
126        let mut visual = NodeVisual::new(folder.index(), folder.display_label(), position);
127        visual.label = folder.label();
128        let mut children = Vec::new();
129        if !folder.children().is_empty() {
130            let mut child_vertical_position = visual.position.vertical + visual.height;
131            for child in folder.children() {
132                let child = Self::new(child, Position {
133                    horizontal: visual.position.horizontal + 20,
134                    vertical: child_vertical_position,
135                });
136                visual.width = visual.width.max(child.visual.width + 40);
137                child_vertical_position += child.visual.height + 20;
138                children.push(child);
139            }
140            visual.height = child_vertical_position - visual.position.vertical;
141        }
142        Self { visual, children }
143    }
144
145    fn write(&self, output: &mut dyn Write) -> Result<()> {
146        if self.children.is_empty() {
147            self.visual.write_leaf(output)?;
148        } else {
149            self.visual.write_group_start(output)?;
150            for child in &self.children {
151                child.write(output)?;
152            }
153            writeln!(output, "      </graph>\n    </node>")?;
154        }
155        Ok(())
156    }
157}
158
159#[must_use]
160fn escaped_label(label: &str) -> String {
161    // Preserve CR as an entity: XML readers normalize literal CR to LF.
162    quick_xml::escape::escape(label).replace('\r', "&#13;")
163}
164
165fn validate_graph(graph: &FolderGraph) -> Result<()> {
166    ensure!(graph.nodes().iter().all(|node| node.label().chars().all(|character| matches!(character,
167        '\t' | '\n' | '\r' | '\u{20}'..='\u{d7ff}' | '\u{e000}'..='\u{fffd}' | '\u{10000}'..='\u{10ffff}'
168    ))), "a folder label contains a character forbidden in XML 1.0");
169    for weight in graph.edges().values() {
170        i64::try_from(weight.value()).context("edge weight exceeds GraphML's signed long range")?;
171    }
172    Ok(())
173}
174
175fn write_header(output: &mut dyn Write, has_cycle_groups: bool) -> Result<()> {
176    writeln!(
177        output,
178        r#"<?xml version="1.0" encoding="UTF-8"?>
179<graphml xmlns="{GRAPHML_NAMESPACE}"
180         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
181         xmlns:y="{YWORKS_NAMESPACE}"
182         xsi:schemaLocation="{GRAPHML_NAMESPACE} http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
183  <key id="label" for="node" attr.name="label" attr.type="string"/>
184  <key id="weight" for="edge" attr.name="dependencies" attr.type="long"/>
185  <key id="kind" for="edge" attr.name="dependency_kind" attr.type="string"/>"#
186    )?;
187    if has_cycle_groups {
188        writeln!(output, r#"  <key id="cycle_group" for="edge" attr.name="cycle_group" attr.type="int"/>"#)?;
189    }
190    writeln!(
191        output,
192        r#"  <key id="ng" for="node" yfiles.type="nodegraphics"/>
193  <key id="eg" for="edge" yfiles.type="edgegraphics"/>
194  <graph id="folders" edgedefault="directed">"#
195    )?;
196    Ok(())
197}
198
199fn write_edges_and_close(graph: &IndexedGraph<'_>, output: &mut dyn Write) -> Result<()> {
200    for (index, edge) in graph.edges().iter().enumerate() {
201        let source = edge.source();
202        let target = edge.target();
203        let weight = edge.weight().value();
204        let label = edge_label(edge.kind(), edge.weight());
205        let kind = kind_name(edge.kind());
206        let (color, line_style) = match edge.kind() {
207            DependencyKind::Production => ("#47699B", "line"),
208            DependencyKind::Test => (TEST_EDGE_COLOR, "dashed"),
209        };
210        let cycle_color = edge.cycle_group().map(|group| group_color(group, graph.cycle_group_count()));
211        let color = cycle_color.as_deref().unwrap_or(color);
212        let width = if edge.cycle_group().is_some() { CYCLE_EDGE_WIDTH } else { "1.0" };
213        writeln!(
214            output,
215            r#"    <edge id="e{index}" source="n{source}" target="n{target}">
216      <data key="weight">{weight}</data>
217      <data key="kind">{kind}</data>"#
218        )?;
219        if let Some(group) = edge.cycle_group() {
220            writeln!(output, "      <data key=\"cycle_group\">{}</data>", group.number())?;
221        }
222        writeln!(
223            output,
224            r#"      <data key="eg">
225        <y:PolyLineEdge>
226          <y:LineStyle color="{color}" type="{line_style}" width="{width}"/>
227          <y:Arrows source="none" target="standard"/>
228          <y:EdgeLabel>{label}</y:EdgeLabel>
229          <y:BendStyle smoothed="false"/>
230        </y:PolyLineEdge>
231      </data>
232    </edge>"#
233        )?;
234    }
235    writeln!(output, "  </graph>\n</graphml>")?;
236    Ok(())
237}
238
239impl Exporter for GraphMl {
240    fn write(&self, graph: &FolderGraph, output: &mut dyn Write) -> Result<()> {
241        self.write_with_options(graph, &Options::new(false, None), output)
242    }
243
244    fn write_grouped(&self, graph: &FolderGraph, output: &mut dyn Write) -> Result<()> {
245        self.write_with_options(graph, &Options::new(true, None), output)
246    }
247
248    fn write_with_options(&self, graph: &FolderGraph, options: &Options<'_>, output: &mut dyn Write) -> Result<()> {
249        validate_graph(graph)?;
250        let indexed_graph = IndexedGraph::with_cycles(graph, options.cycles())?;
251        let hierarchy = if options.group_folders() { Folder::hierarchy(&indexed_graph)? } else { Vec::new() };
252        write_header(output, indexed_graph.cycle_group_count() != 0)?;
253        let mut vertical_position = 0;
254        if options.group_folders() {
255            for folder in hierarchy {
256                let layout = LayoutNode::new(&folder, Position {
257                    horizontal: 0,
258                    vertical: vertical_position,
259                });
260                layout.write(output)?;
261                vertical_position += layout.visual.height + 40;
262            }
263        } else {
264            for (label, &index) in indexed_graph.nodes() {
265                let visual = NodeVisual::new(index, label, Position {
266                    horizontal: 0,
267                    vertical: vertical_position,
268                });
269                visual.write_leaf(output)?;
270                vertical_position += visual.height + 40;
271            }
272        }
273        write_edges_and_close(&indexed_graph, output)
274    }
275}