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