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