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