plain.rs

  1//! # Plain Text Output
  2//!
  3//! This module provides functionality for rendering plain text output in a terminal-like format.
  4//! It uses the Alacritty terminal emulator backend to process and display text, supporting
  5//! ANSI escape sequences for formatting, colors, and other terminal features.
  6//!
  7//! The main component of this module is the `TerminalOutput` struct, which handles the parsing
  8//! and rendering of text input, simulating a basic terminal environment within REPL output.
  9//!
 10//! This module is used for displaying:
 11//!
 12//! - Standard output (stdout)
 13//! - Standard error (stderr)
 14//! - Plain text content
 15//! - Error tracebacks
 16//!
 17
 18use alacritty_terminal::{
 19    event::VoidListener,
 20    grid::Dimensions as _,
 21    index::{Column, Line, Point},
 22    term::Config,
 23    vte::ansi::Processor,
 24};
 25use gpui::{Bounds, ClipboardItem, Entity, FontStyle, TextStyle, WhiteSpace, canvas, size};
 26use language::Buffer;
 27use settings::Settings as _;
 28use terminal::terminal_settings::TerminalSettings;
 29use terminal_view::terminal_element::TerminalElement;
 30use theme::ThemeSettings;
 31use ui::{IntoElement, prelude::*};
 32
 33use crate::outputs::OutputContent;
 34
 35/// The `TerminalOutput` struct handles the parsing and rendering of text input,
 36/// simulating a basic terminal environment within REPL output.
 37///
 38/// `TerminalOutput` is designed to handle various types of text-based output, including:
 39///
 40/// * stdout (standard output)
 41/// * stderr (standard error)
 42/// * text/plain content
 43/// * error tracebacks
 44///
 45/// It uses the Alacritty terminal emulator backend to process and render text,
 46/// supporting ANSI escape sequences for text formatting and colors.
 47///
 48pub struct TerminalOutput {
 49    full_buffer: Option<Entity<Buffer>>,
 50    /// ANSI escape sequence processor for parsing input text.
 51    parser: Processor,
 52    /// Alacritty terminal instance that manages the terminal state and content.
 53    handler: alacritty_terminal::Term<VoidListener>,
 54}
 55
 56const DEFAULT_NUM_LINES: usize = 32;
 57const DEFAULT_NUM_COLUMNS: usize = 128;
 58
 59/// Returns the default text style for the terminal output.
 60pub fn text_style(window: &mut Window, cx: &mut App) -> TextStyle {
 61    let settings = ThemeSettings::get_global(cx).clone();
 62
 63    let font_size = settings.buffer_font_size(cx).into();
 64    let font_family = settings.buffer_font.family;
 65    let font_features = settings.buffer_font.features;
 66    let font_weight = settings.buffer_font.weight;
 67    let font_fallbacks = settings.buffer_font.fallbacks;
 68
 69    let theme = cx.theme();
 70
 71    let text_style = TextStyle {
 72        font_family,
 73        font_features,
 74        font_weight,
 75        font_fallbacks,
 76        font_size,
 77        font_style: FontStyle::Normal,
 78        line_height: window.line_height().into(),
 79        background_color: Some(theme.colors().terminal_ansi_background),
 80        white_space: WhiteSpace::Normal,
 81        // These are going to be overridden per-cell
 82        color: theme.colors().terminal_foreground,
 83        ..Default::default()
 84    };
 85
 86    text_style
 87}
 88
 89/// Returns the default terminal size for the terminal output.
 90pub fn terminal_size(window: &mut Window, cx: &mut App) -> terminal::TerminalBounds {
 91    let text_style = text_style(window, cx);
 92    let text_system = window.text_system();
 93
 94    let line_height = window.line_height();
 95
 96    let font_pixels = text_style.font_size.to_pixels(window.rem_size());
 97    let font_id = text_system.resolve_font(&text_style.font());
 98
 99    let cell_width = text_system
100        .advance(font_id, font_pixels, 'w')
101        .unwrap()
102        .width;
103
104    let num_lines = DEFAULT_NUM_LINES;
105    let columns = DEFAULT_NUM_COLUMNS;
106
107    // Reversed math from terminal::TerminalSize to get pixel width according to terminal width
108    let width = columns as f32 * cell_width;
109    let height = num_lines as f32 * window.line_height();
110
111    terminal::TerminalBounds {
112        cell_width,
113        line_height,
114        bounds: Bounds {
115            origin: gpui::Point::default(),
116            size: size(width, height),
117        },
118    }
119}
120
121impl TerminalOutput {
122    /// Creates a new `TerminalOutput` instance.
123    ///
124    /// This method initializes a new terminal emulator with default configuration
125    /// and sets up the necessary components for handling terminal events and rendering.
126    ///
127    pub fn new(window: &mut Window, cx: &mut App) -> Self {
128        let term = alacritty_terminal::Term::new(
129            Config::default(),
130            &terminal_size(window, cx),
131            VoidListener,
132        );
133
134        Self {
135            parser: Processor::new(),
136            handler: term,
137            full_buffer: None,
138        }
139    }
140
141    /// Creates a new `TerminalOutput` instance with initial content.
142    ///
143    /// Initializes a new terminal output and populates it with the provided text.
144    ///
145    /// # Arguments
146    ///
147    /// * `text` - A string slice containing the initial text for the terminal output.
148    /// * `cx` - A mutable reference to the `WindowContext` for initialization.
149    ///
150    /// # Returns
151    ///
152    /// A new instance of `TerminalOutput` containing the provided text.
153    pub fn from(text: &str, window: &mut Window, cx: &mut App) -> Self {
154        let mut output = Self::new(window, cx);
155        output.append_text(text, cx);
156        output
157    }
158
159    /// Appends text to the terminal output.
160    ///
161    /// Processes each byte of the input text, handling newline characters specially
162    /// to ensure proper cursor movement. Uses the ANSI parser to process the input
163    /// and update the terminal state.
164    ///
165    /// As an example, if the user runs the following Python code in this REPL:
166    ///
167    /// ```python
168    /// import time
169    /// print("Hello,", end="")
170    /// time.sleep(1)
171    /// print(" world!")
172    /// ```
173    ///
174    /// Then append_text will be called twice, with the following arguments:
175    ///
176    /// ```rust
177    /// terminal_output.append_text("Hello,")
178    /// terminal_output.append_text(" world!")
179    /// ```
180    /// Resulting in a single output of "Hello, world!".
181    ///
182    /// # Arguments
183    ///
184    /// * `text` - A string slice containing the text to be appended.
185    pub fn append_text(&mut self, text: &str, cx: &mut App) {
186        for byte in text.as_bytes() {
187            if *byte == b'\n' {
188                // Dirty (?) hack to move the cursor down
189                self.parser.advance(&mut self.handler, &[b'\r']);
190                self.parser.advance(&mut self.handler, &[b'\n']);
191            } else {
192                self.parser.advance(&mut self.handler, &[*byte]);
193            }
194        }
195
196        // This will keep the buffer up to date, though with some terminal codes it won't be perfect
197        if let Some(buffer) = self.full_buffer.as_ref() {
198            buffer.update(cx, |buffer, cx| {
199                buffer.edit([(buffer.len()..buffer.len(), text)], None, cx);
200            });
201        }
202    }
203
204    fn full_text(&self) -> String {
205        let mut full_text = String::new();
206
207        // Get the total number of lines, including history
208        let total_lines = self.handler.grid().total_lines();
209        let visible_lines = self.handler.screen_lines();
210        let history_lines = total_lines - visible_lines;
211
212        // Capture history lines in correct order (oldest to newest)
213        for line in (0..history_lines).rev() {
214            let line_index = Line(-(line as i32) - 1);
215            let start = Point::new(line_index, Column(0));
216            let end = Point::new(line_index, Column(self.handler.columns() - 1));
217            let line_content = self.handler.bounds_to_string(start, end);
218
219            if !line_content.trim().is_empty() {
220                full_text.push_str(&line_content);
221                full_text.push('\n');
222            }
223        }
224
225        // Capture visible lines
226        for line in 0..visible_lines {
227            let line_index = Line(line as i32);
228            let start = Point::new(line_index, Column(0));
229            let end = Point::new(line_index, Column(self.handler.columns() - 1));
230            let line_content = self.handler.bounds_to_string(start, end);
231
232            if !line_content.trim().is_empty() {
233                full_text.push_str(&line_content);
234                full_text.push('\n');
235            }
236        }
237
238        // Trim any trailing newlines
239        full_text.trim_end().to_string()
240    }
241}
242
243impl Render for TerminalOutput {
244    /// Renders the terminal output as a GPUI element.
245    ///
246    /// Converts the current terminal state into a renderable GPUI element. It handles
247    /// the layout of the terminal grid, calculates the dimensions of the output, and
248    /// creates a canvas element that paints the terminal cells and background rectangles.
249    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
250        let text_style = text_style(window, cx);
251        let text_system = window.text_system();
252
253        let grid = self
254            .handler
255            .renderable_content()
256            .display_iter
257            .map(|ic| terminal::IndexedCell {
258                point: ic.point,
259                cell: ic.cell.clone(),
260            });
261        let minimum_contrast = TerminalSettings::get_global(cx).minimum_contrast;
262        let (rects, batched_text_runs) =
263            TerminalElement::layout_grid(grid, 0, &text_style, None, minimum_contrast, cx);
264
265        // lines are 0-indexed, so we must add 1 to get the number of lines
266        let text_line_height = text_style.line_height_in_pixels(window.rem_size());
267        let num_lines = batched_text_runs
268            .iter()
269            .map(|b| b.start_point.line)
270            .max()
271            .unwrap_or(0)
272            + 1;
273        let height = num_lines as f32 * text_line_height;
274
275        let font_pixels = text_style.font_size.to_pixels(window.rem_size());
276        let font_id = text_system.resolve_font(&text_style.font());
277
278        let cell_width = text_system
279            .advance(font_id, font_pixels, 'w')
280            .map(|advance| advance.width)
281            .unwrap_or(Pixels(0.0));
282
283        canvas(
284            // prepaint
285            move |_bounds, _, _| {},
286            // paint
287            move |bounds, _, window, cx| {
288                for rect in rects {
289                    rect.paint(
290                        bounds.origin,
291                        &terminal::TerminalBounds {
292                            cell_width,
293                            line_height: text_line_height,
294                            bounds,
295                        },
296                        window,
297                    );
298                }
299
300                for batch in batched_text_runs {
301                    batch.paint(
302                        bounds.origin,
303                        &terminal::TerminalBounds {
304                            cell_width,
305                            line_height: text_line_height,
306                            bounds,
307                        },
308                        window,
309                        cx,
310                    );
311                }
312            },
313        )
314        // We must set the height explicitly for the editor block to size itself correctly
315        .h(height)
316    }
317}
318
319impl OutputContent for TerminalOutput {
320    fn clipboard_content(&self, _window: &Window, _cx: &App) -> Option<ClipboardItem> {
321        Some(ClipboardItem::new_string(self.full_text()))
322    }
323
324    fn has_clipboard_content(&self, _window: &Window, _cx: &App) -> bool {
325        true
326    }
327
328    fn has_buffer_content(&self, _window: &Window, _cx: &App) -> bool {
329        true
330    }
331
332    fn buffer_content(&mut self, _: &mut Window, cx: &mut App) -> Option<Entity<Buffer>> {
333        if self.full_buffer.as_ref().is_some() {
334            return self.full_buffer.clone();
335        }
336
337        let buffer = cx.new(|cx| {
338            let mut buffer =
339                Buffer::local(self.full_text(), cx).with_language(language::PLAIN_TEXT.clone(), cx);
340            buffer.set_capability(language::Capability::ReadOnly, cx);
341            buffer
342        });
343
344        self.full_buffer = Some(buffer.clone());
345        Some(buffer)
346    }
347}