Skip to main content

renderdag/pipeline/row_shape_to_prefix_lines/
box_drawing.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8use std::marker::PhantomData;
9
10use super::ancestry_lines;
11use crate::pipeline::types::DashStyle;
12use crate::pipeline::types::GraphRowShape;
13use crate::pipeline::types::LinkLine;
14use crate::pipeline::types::NodeLine;
15use crate::pipeline::types::PadLine;
16use crate::pipeline::types::PrefixLine;
17use crate::pipeline::types::PrefixLineKind;
18use crate::pipeline::types::PrefixLinePart;
19use crate::pipeline::types::PrefixLineRenderer;
20
21mod glyph {
22    pub(super) const SPACE: usize = 0;
23    pub(super) const HORIZONTAL: usize = 1;
24    pub(super) const PARENT: usize = 2;
25    pub(super) const ANCESTOR: usize = 3;
26    pub(super) const MERGE_LEFT: usize = 4;
27    pub(super) const MERGE_RIGHT: usize = 5;
28    pub(super) const MERGE_BOTH: usize = 6;
29    pub(super) const FORK_LEFT: usize = 7;
30    pub(super) const FORK_RIGHT: usize = 8;
31    pub(super) const FORK_BOTH: usize = 9;
32    pub(super) const JOIN_LEFT: usize = 10;
33    pub(super) const JOIN_RIGHT: usize = 11;
34    pub(super) const JOIN_BOTH: usize = 12;
35    pub(super) const TERMINATION: usize = 13;
36    pub(super) const ANCESTOR_ONCE: usize = 14;
37    pub(super) const COUNT: usize = 15;
38}
39
40const SQUARE_GLYPHS: [&str; glyph::COUNT] = [
41    "  ", "──", "│ ", "· ", "┘ ", "└─", "┴─", "┐ ", "┌─", "┬─", "┤ ", "├─", "┼─", "~ ", "┆ ",
42];
43
44const CURVED_GLYPHS: [&str; glyph::COUNT] = [
45    "  ", "──", "│ ", "╷ ", "╯ ", "╰─", "┴─", "╮ ", "╭─", "┬─", "┤ ", "├─", "┼─", "~ ", "┆ ",
46];
47
48const DEC_GLYPHS: [&str; glyph::COUNT] = [
49    "  ",
50    "\x1B(0qq\x1B(B",
51    "\x1B(0x \x1B(B",
52    "\x1B(0~ \x1B(B",
53    "\x1B(0j \x1B(B",
54    "\x1B(0mq\x1B(B",
55    "\x1B(0vq\x1B(B",
56    "\x1B(0k \x1B(B",
57    "\x1B(0lq\x1B(B",
58    "\x1B(0wq\x1B(B",
59    "\x1B(0u \x1B(B",
60    "\x1B(0tq\x1B(B",
61    "\x1B(0nq\x1B(B",
62    "~ ",
63    ": ",
64];
65
66/// Glyph table used by box-drawing prefix line renderers.
67pub trait BoxDrawingGlyphSet {
68    /// The glyph table for this box-drawing style.
69    /// The last entry draws vertical ancestor lines for `DashStyle::Once`.
70    const GLYPHS: &'static [&'static str; glyph::COUNT];
71}
72
73/// Curved box-drawing glyphs.
74pub enum Curved {}
75
76/// Square box-drawing glyphs.
77pub enum Square {}
78
79/// DEC special graphics glyphs.
80pub enum DecGraphics {}
81
82impl BoxDrawingGlyphSet for Curved {
83    const GLYPHS: &'static [&'static str; glyph::COUNT] = &CURVED_GLYPHS;
84}
85
86impl BoxDrawingGlyphSet for Square {
87    const GLYPHS: &'static [&'static str; glyph::COUNT] = &SQUARE_GLYPHS;
88}
89
90impl BoxDrawingGlyphSet for DecGraphics {
91    const GLYPHS: &'static [&'static str; glyph::COUNT] = &DEC_GLYPHS;
92}
93
94/// Converts abstract row shapes into box-drawing graph prefix lines.
95pub struct BoxDrawingPrefixLineRenderer<G = Curved> {
96    _glyphs: PhantomData<G>,
97}
98
99impl<G> BoxDrawingPrefixLineRenderer<G>
100where
101    G: BoxDrawingGlyphSet,
102{
103    /// Create a renderer that uses the glyph set from `G`.
104    pub fn new() -> Self {
105        Self {
106            _glyphs: PhantomData,
107        }
108    }
109
110    /// Use square box-drawing glyphs.
111    pub fn with_square_glyphs(self) -> BoxDrawingPrefixLineRenderer<Square> {
112        BoxDrawingPrefixLineRenderer::new()
113    }
114
115    /// Use DEC special graphics glyphs.
116    pub fn with_dec_graphics_glyphs(self) -> BoxDrawingPrefixLineRenderer<DecGraphics> {
117        BoxDrawingPrefixLineRenderer::new()
118    }
119}
120
121impl<G: BoxDrawingGlyphSet, N> PrefixLineRenderer<N> for BoxDrawingPrefixLineRenderer<G> {
122    /// Convert the next graph row shape into prefix lines.
123    fn next_prefix_lines(&mut self, line: &GraphRowShape<N>) -> Vec<PrefixLine> {
124        let glyphs = G::GLYPHS;
125        let ancestor = match line.style.dash_style {
126            DashStyle::Persistent => glyph::ANCESTOR,
127            DashStyle::Once => glyph::ANCESTOR_ONCE,
128        };
129        let mut lines = Vec::new();
130
131        lines.push(render_pad_line(
132            glyphs,
133            ancestor,
134            line.pre_node_line(),
135            PrefixLineKind::PreNode,
136        ));
137
138        // Render the nodeline
139        let mut node_line = PrefixLine {
140            parts: Vec::new(),
141            kind: PrefixLineKind::Node,
142        };
143        for entry in line.node_line.iter() {
144            match entry {
145                NodeLine::Node => {
146                    node_line.parts.push(PrefixLinePart::NodeGlyph);
147                    node_line
148                        .parts
149                        .push(PrefixLinePart::Text(String::from(" ")));
150                }
151                NodeLine::Parent => push_text(&mut node_line, glyphs[glyph::PARENT]),
152                NodeLine::Ancestor => push_text(&mut node_line, glyphs[ancestor]),
153                NodeLine::Blank => push_text(&mut node_line, glyphs[glyph::SPACE]),
154            }
155        }
156        lines.push(node_line);
157
158        lines.push(render_pad_line(
159            glyphs,
160            ancestor,
161            line.post_node_line(),
162            PrefixLineKind::PostNode,
163        ));
164
165        // Render the link line
166        #[allow(clippy::if_same_then_else)]
167        if let Some(link_row) = line.link_line.as_ref() {
168            let mut link_line = String::new();
169            for cur in link_row.iter() {
170                if cur.intersects(LinkLine::HORIZONTAL) {
171                    if cur.intersects(LinkLine::CHILD) {
172                        link_line.push_str(glyphs[glyph::JOIN_BOTH]);
173                    } else if cur.intersects(LinkLine::ANY_FORK)
174                        && cur.intersects(LinkLine::ANY_MERGE)
175                    {
176                        link_line.push_str(glyphs[glyph::JOIN_BOTH]);
177                    } else if cur.intersects(LinkLine::ANY_FORK)
178                        && cur.intersects(LinkLine::VERT_PARENT)
179                        && !line.merge
180                    {
181                        link_line.push_str(glyphs[glyph::JOIN_BOTH]);
182                    } else if cur.intersects(LinkLine::ANY_FORK) {
183                        link_line.push_str(glyphs[glyph::FORK_BOTH]);
184                    } else if cur.intersects(LinkLine::ANY_MERGE) {
185                        link_line.push_str(glyphs[glyph::MERGE_BOTH]);
186                    } else {
187                        link_line.push_str(glyphs[glyph::HORIZONTAL]);
188                    }
189                } else if cur.intersects(LinkLine::VERT_PARENT) && !line.merge {
190                    let left = cur.intersects(LinkLine::LEFT_MERGE | LinkLine::LEFT_FORK);
191                    let right = cur.intersects(LinkLine::RIGHT_MERGE | LinkLine::RIGHT_FORK);
192                    match (left, right) {
193                        (true, true) => link_line.push_str(glyphs[glyph::JOIN_BOTH]),
194                        (true, false) => link_line.push_str(glyphs[glyph::JOIN_LEFT]),
195                        (false, true) => link_line.push_str(glyphs[glyph::JOIN_RIGHT]),
196                        (false, false) => link_line.push_str(glyphs[glyph::PARENT]),
197                    }
198                } else if cur.intersects(LinkLine::VERT_PARENT | LinkLine::VERT_ANCESTOR)
199                    && !cur.intersects(LinkLine::LEFT_FORK | LinkLine::RIGHT_FORK)
200                {
201                    let left = cur.intersects(LinkLine::LEFT_MERGE);
202                    let right = cur.intersects(LinkLine::RIGHT_MERGE);
203                    match (left, right) {
204                        (true, true) => link_line.push_str(glyphs[glyph::JOIN_BOTH]),
205                        (true, false) => link_line.push_str(glyphs[glyph::JOIN_LEFT]),
206                        (false, true) => link_line.push_str(glyphs[glyph::JOIN_RIGHT]),
207                        (false, false) => {
208                            if cur.intersects(LinkLine::VERT_ANCESTOR) {
209                                link_line.push_str(glyphs[ancestor]);
210                            } else {
211                                link_line.push_str(glyphs[glyph::PARENT]);
212                            }
213                        }
214                    }
215                } else if cur.intersects(LinkLine::LEFT_FORK)
216                    && cur.intersects(LinkLine::LEFT_MERGE | LinkLine::CHILD)
217                {
218                    link_line.push_str(glyphs[glyph::JOIN_LEFT]);
219                } else if cur.intersects(LinkLine::RIGHT_FORK)
220                    && cur.intersects(LinkLine::RIGHT_MERGE | LinkLine::CHILD)
221                {
222                    link_line.push_str(glyphs[glyph::JOIN_RIGHT]);
223                } else if cur.intersects(LinkLine::LEFT_MERGE)
224                    && cur.intersects(LinkLine::RIGHT_MERGE)
225                {
226                    link_line.push_str(glyphs[glyph::MERGE_BOTH]);
227                } else if cur.intersects(LinkLine::LEFT_FORK)
228                    && cur.intersects(LinkLine::RIGHT_FORK)
229                {
230                    link_line.push_str(glyphs[glyph::FORK_BOTH]);
231                } else if cur.intersects(LinkLine::LEFT_FORK) {
232                    link_line.push_str(glyphs[glyph::FORK_LEFT]);
233                } else if cur.intersects(LinkLine::LEFT_MERGE) {
234                    link_line.push_str(glyphs[glyph::MERGE_LEFT]);
235                } else if cur.intersects(LinkLine::RIGHT_FORK) {
236                    link_line.push_str(glyphs[glyph::FORK_RIGHT]);
237                } else if cur.intersects(LinkLine::RIGHT_MERGE) {
238                    link_line.push_str(glyphs[glyph::MERGE_RIGHT]);
239                } else {
240                    link_line.push_str(glyphs[glyph::SPACE]);
241                }
242            }
243            lines.push(PrefixLine {
244                parts: vec![PrefixLinePart::Text(link_line)],
245                kind: PrefixLineKind::Link,
246            });
247        }
248
249        // Render the term line
250        if let Some(term_row) = line.term_line.as_ref() {
251            let term_strs = [glyphs[glyph::PARENT], glyphs[glyph::TERMINATION]];
252            for term_str in term_strs.iter() {
253                let mut term_line = String::new();
254                for (i, term) in term_row.iter().enumerate() {
255                    if *term {
256                        term_line.push_str(term_str);
257                    } else {
258                        term_line
259                            .push_str(glyphs[pad_line_to_glyph(line.ancestry_line[i], ancestor)]);
260                    }
261                }
262                lines.push(PrefixLine {
263                    parts: vec![PrefixLinePart::Text(term_line)],
264                    kind: PrefixLineKind::Term,
265                });
266            }
267        }
268
269        for (kind, columns) in ancestry_lines(line) {
270            lines.push(render_pad_line(glyphs, ancestor, columns, kind));
271        }
272
273        lines
274    }
275}
276
277impl<G> Default for BoxDrawingPrefixLineRenderer<G>
278where
279    G: BoxDrawingGlyphSet,
280{
281    fn default() -> Self {
282        Self::new()
283    }
284}
285
286fn push_text(line: &mut PrefixLine, text: &str) {
287    line.parts.push(PrefixLinePart::Text(text.to_owned()));
288}
289
290fn render_pad_line(
291    glyphs: &[&str; glyph::COUNT],
292    ancestor: usize,
293    line: impl IntoIterator<Item = PadLine>,
294    kind: PrefixLineKind,
295) -> PrefixLine {
296    PrefixLine {
297        parts: vec![PrefixLinePart::Text(render_pad_text(
298            glyphs, ancestor, line,
299        ))],
300        kind,
301    }
302}
303
304fn render_pad_text(
305    glyphs: &[&str; glyph::COUNT],
306    ancestor: usize,
307    line: impl IntoIterator<Item = PadLine>,
308) -> String {
309    let mut out = String::new();
310    for entry in line {
311        out.push_str(glyphs[pad_line_to_glyph(entry, ancestor)]);
312    }
313    out
314}
315
316fn pad_line_to_glyph(line: PadLine, ancestor: usize) -> usize {
317    match line {
318        PadLine::Parent => glyph::PARENT,
319        PadLine::Ancestor => ancestor,
320        PadLine::Blank => glyph::SPACE,
321    }
322}