Skip to main content

renderdag/
output.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::ascii::AsciiRenderer;
11use super::ascii_large::AsciiLargeRenderer;
12use super::box_drawing::BoxDrawingRenderer;
13use super::render::GraphRow;
14use super::render::Renderer;
15use crate::pipeline::coloring::PrefixLineColor;
16use crate::pipeline::types::TextLine;
17
18#[cfg(feature = "coloring")]
19const PLAIN: PrefixLineColor = None;
20#[cfg(not(feature = "coloring"))]
21const PLAIN: PrefixLineColor = ();
22
23pub(crate) const DEFAULT_MIN_ROW_HEIGHT: usize = 2;
24
25#[derive(Clone, Copy, Debug)]
26pub struct OutputRendererOptions {
27    pub min_row_height: usize,
28    pub stagger_consecutive_disconnected_nodes: bool,
29    pub graph_row_shape_style: crate::pipeline::types::GraphRowShapeStyle,
30}
31
32/// Common stateful text line output utilities shared by ASCII and box-drawing
33/// renderers.
34#[derive(Default)]
35pub(crate) struct OutputRendererState {
36    queued_pad_line: Option<TextLine>,
37    /// If > 1, no need for an extra separator for the next row.
38    /// Separator is only needed for adjacent single-line node lines.
39    /// If there are link, pad, term, or other kinds of node lines,
40    /// no need to draw separator.
41    row_height: usize,
42}
43
44impl OutputRendererState {
45    pub(crate) fn begin_row(
46        &mut self,
47        out: &mut impl FnMut(&str, &PrefixLineColor),
48        separator_line: bool,
49    ) {
50        if let Some(line) = self.queued_pad_line.take() {
51            self.push_line_with_message(
52                out,
53                line.iter().map(|(text, color)| (text.as_str(), color)),
54                None,
55                "",
56            );
57        }
58        if separator_line && self.row_height == 1 {
59            out("\n", &PLAIN);
60        }
61        self.row_height = 0;
62    }
63
64    pub(crate) fn push_line_with_message<'a>(
65        &mut self,
66        out: &mut impl FnMut(&str, &PrefixLineColor),
67        prefix: impl ExactSizeIterator<Item = (&'a str, &'a PrefixLineColor)>
68        + DoubleEndedIterator
69        + Clone,
70        message: Option<&str>,
71        text_gap: &str,
72    ) {
73        if let Some(message) = message.map(str::trim_end).filter(|text| !text.is_empty()) {
74            for (text, color) in prefix {
75                if !text.is_empty() {
76                    out(text, color);
77                }
78            }
79            if !text_gap.is_empty() {
80                out(text_gap, &PLAIN);
81            }
82            out(message, &PLAIN);
83        } else if let Some((last, _)) = prefix
84            .clone()
85            .enumerate()
86            .rev()
87            .find(|(_, (text, _))| !text.trim_end().is_empty())
88        {
89            // Find the final visible fragment before streaming any text.
90            for (index, (text, color)) in prefix.enumerate().take(last + 1) {
91                let text = if index == last { text.trim_end() } else { text };
92                if !text.is_empty() {
93                    out(text, color);
94                }
95            }
96        }
97        out("\n", &PLAIN);
98        self.row_height = self.row_height.saturating_add(1);
99    }
100
101    pub(crate) fn push_pad_lines<'a, 'b>(
102        &mut self,
103        out: &mut impl FnMut(&str, &PrefixLineColor),
104        prefix: impl ExactSizeIterator<Item = (&'a str, &'a PrefixLineColor)>
105        + DoubleEndedIterator
106        + Clone,
107        message_lines: impl Iterator<Item = &'b str>,
108        text_gap: &str,
109    ) -> bool {
110        let mut emitted = false;
111        for message in message_lines {
112            self.push_line_with_message(out, prefix.clone(), Some(message), text_gap);
113            emitted = true;
114        }
115        emitted
116    }
117
118    pub(crate) fn queue_pad_line(&mut self, pad_line: TextLine) {
119        self.queued_pad_line = Some(pad_line);
120    }
121}
122
123/// Legacy text-renderer builder.
124/// New options since renderdag 0.2 might be ignored.
125/// Use [`crate::pipeline::GraphTextRenderer::configure`] for all options.
126pub struct OutputRendererBuilder<N, R>
127where
128    R: Renderer<N, Output = GraphRow<N>> + Sized,
129{
130    inner: R,
131    _phantom: PhantomData<N>,
132}
133
134impl Default for OutputRendererOptions {
135    fn default() -> Self {
136        Self {
137            min_row_height: DEFAULT_MIN_ROW_HEIGHT,
138            stagger_consecutive_disconnected_nodes: false,
139            graph_row_shape_style: Default::default(),
140        }
141    }
142}
143
144impl<N, R> OutputRendererBuilder<N, R>
145where
146    R: Renderer<N, Output = GraphRow<N>> + Sized,
147{
148    pub fn new(inner: R) -> Self {
149        OutputRendererBuilder {
150            inner,
151            _phantom: PhantomData,
152        }
153    }
154
155    pub fn with_options(mut self, options: OutputRendererOptions) -> Self {
156        *self.inner.output_options_mut() = options;
157        self
158    }
159
160    pub fn with_min_row_height(mut self, min_row_height: usize) -> Self {
161        self.inner.output_options_mut().min_row_height = min_row_height;
162        self
163    }
164
165    pub fn with_stagger_consecutive_disconnected_nodes(mut self, stagger: bool) -> Self {
166        self.inner
167            .output_options_mut()
168            .stagger_consecutive_disconnected_nodes = stagger;
169        self
170    }
171
172    pub fn build_ascii(self) -> AsciiRenderer<N, R> {
173        AsciiRenderer::new(self.inner)
174    }
175
176    pub fn build_ascii_large(self) -> AsciiLargeRenderer<N, R> {
177        AsciiLargeRenderer::new(self.inner)
178    }
179
180    pub fn build_box_drawing(self) -> BoxDrawingRenderer<N, R> {
181        BoxDrawingRenderer::new(self.inner)
182    }
183}