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