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