stdio.rs

  1use crate::outputs::{ExecutionView, LineHeight};
  2use alacritty_terminal::vte::{
  3    ansi::{Attr, Color, NamedColor, Rgb},
  4    Params, ParamsIter, Parser, Perform,
  5};
  6use core::iter;
  7use gpui::{font, prelude::*, AnyElement, StyledText, TextRun};
  8use settings::Settings as _;
  9use theme::ThemeSettings;
 10use ui::{div, prelude::*, IntoElement, ViewContext, WindowContext};
 11
 12/// Implements the most basic of terminal output for use by Jupyter outputs
 13/// whether:
 14///
 15/// * stdout
 16/// * stderr
 17/// * text/plain
 18/// * traceback from an error output
 19///
 20/// Ideally, we would instead use alacritty::vte::Processor to collect the
 21/// output and then render up to u8::MAX lines of text. However, it's likely
 22/// overkill for 95% of outputs.
 23///
 24/// Instead, this implementation handles:
 25///
 26/// * ANSI color codes (background, foreground), including 256 color
 27/// * Carriage returns/line feeds
 28///
 29/// There is no support for cursor movement, clearing the screen, and other text styles
 30pub struct TerminalOutput {
 31    parser: Parser,
 32    handler: TerminalHandler,
 33}
 34
 35impl TerminalOutput {
 36    pub fn new() -> Self {
 37        Self {
 38            parser: Parser::new(),
 39            handler: TerminalHandler::new(),
 40        }
 41    }
 42
 43    pub fn from(text: &str) -> Self {
 44        let mut output = Self::new();
 45        output.append_text(text);
 46        output
 47    }
 48
 49    pub fn append_text(&mut self, text: &str) {
 50        for byte in text.as_bytes() {
 51            self.parser.advance(&mut self.handler, *byte);
 52        }
 53    }
 54
 55    pub fn render(&self, cx: &ViewContext<ExecutionView>) -> AnyElement {
 56        let theme = cx.theme();
 57        let buffer_font = ThemeSettings::get_global(cx).buffer_font.family.clone();
 58        let runs = self
 59            .handler
 60            .text_runs
 61            .iter()
 62            .chain(Some(&self.handler.current_text_run))
 63            .map(|ansi_run| {
 64                let color = terminal_view::terminal_element::convert_color(&ansi_run.fg, theme);
 65                let background_color = Some(terminal_view::terminal_element::convert_color(
 66                    &ansi_run.bg,
 67                    theme,
 68                ));
 69
 70                TextRun {
 71                    len: ansi_run.len,
 72                    color,
 73                    background_color,
 74                    underline: Default::default(),
 75                    font: font(buffer_font.clone()),
 76                    strikethrough: None,
 77                }
 78            })
 79            .collect::<Vec<TextRun>>();
 80
 81        let text = StyledText::new(self.handler.buffer.trim_end().to_string()).with_runs(runs);
 82        div()
 83            .font_family(buffer_font)
 84            .child(text)
 85            .into_any_element()
 86    }
 87}
 88
 89impl LineHeight for TerminalOutput {
 90    fn num_lines(&self, _cx: &mut WindowContext) -> u8 {
 91        self.handler.buffer.lines().count() as u8
 92    }
 93}
 94
 95#[derive(Clone)]
 96struct AnsiTextRun {
 97    len: usize,
 98    fg: alacritty_terminal::vte::ansi::Color,
 99    bg: alacritty_terminal::vte::ansi::Color,
100}
101
102impl AnsiTextRun {
103    fn default() -> Self {
104        Self {
105            len: 0,
106            fg: Color::Named(NamedColor::Foreground),
107            bg: Color::Named(NamedColor::Background),
108        }
109    }
110}
111
112struct TerminalHandler {
113    text_runs: Vec<AnsiTextRun>,
114    current_text_run: AnsiTextRun,
115    buffer: String,
116}
117
118impl TerminalHandler {
119    fn new() -> Self {
120        Self {
121            text_runs: Vec::new(),
122            current_text_run: AnsiTextRun {
123                len: 0,
124                fg: Color::Named(NamedColor::Foreground),
125                bg: Color::Named(NamedColor::Background),
126            },
127            buffer: String::new(),
128        }
129    }
130
131    fn add_text(&mut self, c: char) {
132        self.buffer.push(c);
133        self.current_text_run.len += 1;
134    }
135
136    fn reset(&mut self) {
137        if self.current_text_run.len > 0 {
138            self.text_runs.push(self.current_text_run.clone());
139        }
140
141        self.current_text_run = AnsiTextRun::default();
142    }
143
144    fn terminal_attribute(&mut self, attr: Attr) {
145        // println!("[terminal_attribute] attr={:?}", attr);
146        if Attr::Reset == attr {
147            self.reset();
148            return;
149        }
150
151        if self.current_text_run.len > 0 {
152            self.text_runs.push(self.current_text_run.clone());
153        }
154
155        let mut text_run = AnsiTextRun {
156            len: 0,
157            fg: self.current_text_run.fg,
158            bg: self.current_text_run.bg,
159        };
160
161        match attr {
162            Attr::Foreground(color) => text_run.fg = color,
163            Attr::Background(color) => text_run.bg = color,
164            _ => {}
165        }
166
167        self.current_text_run = text_run;
168    }
169
170    fn process_carriage_return(&mut self) {
171        // Find last carriage return's position
172        let last_cr = self.buffer.rfind('\r').unwrap_or(0);
173        self.buffer = self.buffer.chars().take(last_cr).collect();
174
175        // First work through our current text run
176        let mut total_len = self.current_text_run.len;
177        if total_len > last_cr {
178            // We are in the current text run
179            self.current_text_run.len = self.current_text_run.len - last_cr;
180        } else {
181            let mut last_cr_run = 0;
182            // Find the last run before the last carriage return
183            for (i, run) in self.text_runs.iter().enumerate() {
184                total_len += run.len;
185                if total_len > last_cr {
186                    last_cr_run = i;
187                    break;
188                }
189            }
190            self.text_runs = self.text_runs[..last_cr_run].to_vec();
191            self.current_text_run = self.text_runs.pop().unwrap_or(AnsiTextRun::default());
192        }
193
194        self.buffer.push('\r');
195        self.current_text_run.len += 1;
196    }
197}
198
199impl Perform for TerminalHandler {
200    fn print(&mut self, c: char) {
201        // println!("[print] c={:?}", c);
202        self.add_text(c);
203    }
204
205    fn execute(&mut self, byte: u8) {
206        match byte {
207            b'\n' => {
208                self.add_text('\n');
209            }
210            b'\r' => {
211                self.process_carriage_return();
212            }
213            _ => {
214                // Format as hex
215                println!("[execute] byte={:02x}", byte);
216            }
217        }
218    }
219
220    fn hook(&mut self, _params: &Params, _intermediates: &[u8], _ignore: bool, _c: char) {
221        // noop
222        // println!(
223        //     "[hook] params={:?}, intermediates={:?}, c={:?}",
224        //     _params, _intermediates, _c
225        // );
226    }
227
228    fn put(&mut self, _byte: u8) {
229        // noop
230        // println!("[put] byte={:02x}", _byte);
231    }
232
233    fn unhook(&mut self) {
234        // noop
235    }
236
237    fn osc_dispatch(&mut self, _params: &[&[u8]], _bell_terminated: bool) {
238        // noop
239        // println!("[osc_dispatch] params={:?}", _params);
240    }
241
242    fn csi_dispatch(
243        &mut self,
244        params: &alacritty_terminal::vte::Params,
245        intermediates: &[u8],
246        _ignore: bool,
247        action: char,
248    ) {
249        // println!(
250        //     "[csi_dispatch] action={:?}, params={:?}, intermediates={:?}",
251        //     action, params, intermediates
252        // );
253
254        let mut params_iter = params.iter();
255        // Collect colors
256        match (action, intermediates) {
257            ('m', []) => {
258                if params.is_empty() {
259                    self.terminal_attribute(Attr::Reset);
260                } else {
261                    for attr in attrs_from_sgr_parameters(&mut params_iter) {
262                        match attr {
263                            Some(attr) => self.terminal_attribute(attr),
264                            None => return,
265                        }
266                    }
267                }
268            }
269            _ => {}
270        }
271    }
272
273    fn esc_dispatch(&mut self, _intermediates: &[u8], _ignore: bool, _byte: u8) {
274        // noop
275        // println!(
276        //     "[esc_dispatch] intermediates={:?}, byte={:?}",
277        //     _intermediates, _byte
278        // );
279    }
280}
281
282// The following was pulled from vte::ansi
283#[inline]
284fn attrs_from_sgr_parameters(params: &mut ParamsIter<'_>) -> Vec<Option<Attr>> {
285    let mut attrs = Vec::with_capacity(params.size_hint().0);
286
287    while let Some(param) = params.next() {
288        let attr = match param {
289            [0] => Some(Attr::Reset),
290            [1] => Some(Attr::Bold),
291            [2] => Some(Attr::Dim),
292            [3] => Some(Attr::Italic),
293            [4, 0] => Some(Attr::CancelUnderline),
294            [4, 2] => Some(Attr::DoubleUnderline),
295            [4, 3] => Some(Attr::Undercurl),
296            [4, 4] => Some(Attr::DottedUnderline),
297            [4, 5] => Some(Attr::DashedUnderline),
298            [4, ..] => Some(Attr::Underline),
299            [5] => Some(Attr::BlinkSlow),
300            [6] => Some(Attr::BlinkFast),
301            [7] => Some(Attr::Reverse),
302            [8] => Some(Attr::Hidden),
303            [9] => Some(Attr::Strike),
304            [21] => Some(Attr::CancelBold),
305            [22] => Some(Attr::CancelBoldDim),
306            [23] => Some(Attr::CancelItalic),
307            [24] => Some(Attr::CancelUnderline),
308            [25] => Some(Attr::CancelBlink),
309            [27] => Some(Attr::CancelReverse),
310            [28] => Some(Attr::CancelHidden),
311            [29] => Some(Attr::CancelStrike),
312            [30] => Some(Attr::Foreground(Color::Named(NamedColor::Black))),
313            [31] => Some(Attr::Foreground(Color::Named(NamedColor::Red))),
314            [32] => Some(Attr::Foreground(Color::Named(NamedColor::Green))),
315            [33] => Some(Attr::Foreground(Color::Named(NamedColor::Yellow))),
316            [34] => Some(Attr::Foreground(Color::Named(NamedColor::Blue))),
317            [35] => Some(Attr::Foreground(Color::Named(NamedColor::Magenta))),
318            [36] => Some(Attr::Foreground(Color::Named(NamedColor::Cyan))),
319            [37] => Some(Attr::Foreground(Color::Named(NamedColor::White))),
320            [38] => {
321                let mut iter = params.map(|param| param[0]);
322                parse_sgr_color(&mut iter).map(Attr::Foreground)
323            }
324            [38, params @ ..] => handle_colon_rgb(params).map(Attr::Foreground),
325            [39] => Some(Attr::Foreground(Color::Named(NamedColor::Foreground))),
326            [40] => Some(Attr::Background(Color::Named(NamedColor::Black))),
327            [41] => Some(Attr::Background(Color::Named(NamedColor::Red))),
328            [42] => Some(Attr::Background(Color::Named(NamedColor::Green))),
329            [43] => Some(Attr::Background(Color::Named(NamedColor::Yellow))),
330            [44] => Some(Attr::Background(Color::Named(NamedColor::Blue))),
331            [45] => Some(Attr::Background(Color::Named(NamedColor::Magenta))),
332            [46] => Some(Attr::Background(Color::Named(NamedColor::Cyan))),
333            [47] => Some(Attr::Background(Color::Named(NamedColor::White))),
334            [48] => {
335                let mut iter = params.map(|param| param[0]);
336                parse_sgr_color(&mut iter).map(Attr::Background)
337            }
338            [48, params @ ..] => handle_colon_rgb(params).map(Attr::Background),
339            [49] => Some(Attr::Background(Color::Named(NamedColor::Background))),
340            [58] => {
341                let mut iter = params.map(|param| param[0]);
342                parse_sgr_color(&mut iter).map(|color| Attr::UnderlineColor(Some(color)))
343            }
344            [58, params @ ..] => {
345                handle_colon_rgb(params).map(|color| Attr::UnderlineColor(Some(color)))
346            }
347            [59] => Some(Attr::UnderlineColor(None)),
348            [90] => Some(Attr::Foreground(Color::Named(NamedColor::BrightBlack))),
349            [91] => Some(Attr::Foreground(Color::Named(NamedColor::BrightRed))),
350            [92] => Some(Attr::Foreground(Color::Named(NamedColor::BrightGreen))),
351            [93] => Some(Attr::Foreground(Color::Named(NamedColor::BrightYellow))),
352            [94] => Some(Attr::Foreground(Color::Named(NamedColor::BrightBlue))),
353            [95] => Some(Attr::Foreground(Color::Named(NamedColor::BrightMagenta))),
354            [96] => Some(Attr::Foreground(Color::Named(NamedColor::BrightCyan))),
355            [97] => Some(Attr::Foreground(Color::Named(NamedColor::BrightWhite))),
356            [100] => Some(Attr::Background(Color::Named(NamedColor::BrightBlack))),
357            [101] => Some(Attr::Background(Color::Named(NamedColor::BrightRed))),
358            [102] => Some(Attr::Background(Color::Named(NamedColor::BrightGreen))),
359            [103] => Some(Attr::Background(Color::Named(NamedColor::BrightYellow))),
360            [104] => Some(Attr::Background(Color::Named(NamedColor::BrightBlue))),
361            [105] => Some(Attr::Background(Color::Named(NamedColor::BrightMagenta))),
362            [106] => Some(Attr::Background(Color::Named(NamedColor::BrightCyan))),
363            [107] => Some(Attr::Background(Color::Named(NamedColor::BrightWhite))),
364            _ => None,
365        };
366        attrs.push(attr);
367    }
368
369    attrs
370}
371
372/// Handle colon separated rgb color escape sequence.
373#[inline]
374fn handle_colon_rgb(params: &[u16]) -> Option<Color> {
375    let rgb_start = if params.len() > 4 { 2 } else { 1 };
376    let rgb_iter = params[rgb_start..].iter().copied();
377    let mut iter = iter::once(params[0]).chain(rgb_iter);
378
379    parse_sgr_color(&mut iter)
380}
381
382/// Parse a color specifier from list of attributes.
383fn parse_sgr_color(params: &mut dyn Iterator<Item = u16>) -> Option<Color> {
384    match params.next() {
385        Some(2) => Some(Color::Spec(Rgb {
386            r: u8::try_from(params.next()?).ok()?,
387            g: u8::try_from(params.next()?).ok()?,
388            b: u8::try_from(params.next()?).ok()?,
389        })),
390        Some(5) => Some(Color::Indexed(u8::try_from(params.next()?).ok()?)),
391        _ => None,
392    }
393}