outputs.rs

  1use std::sync::Arc;
  2use std::time::Duration;
  3
  4use crate::stdio::TerminalOutput;
  5use anyhow::Result;
  6use gpui::{
  7    img, percentage, Animation, AnimationExt, AnyElement, FontWeight, ImageData, Render, TextRun,
  8    Transformation, View,
  9};
 10use runtimelib::datatable::TableSchema;
 11use runtimelib::media::datatable::TabularDataResource;
 12use runtimelib::{ExecutionState, JupyterMessageContent, MimeBundle, MimeType};
 13use serde_json::Value;
 14use settings::Settings;
 15use theme::ThemeSettings;
 16use ui::{div, prelude::*, v_flex, IntoElement, Styled, ViewContext};
 17
 18/// Given these outputs are destined for the editor with the block decorations API, all of them must report
 19/// how many lines they will take up in the editor.
 20pub trait LineHeight: Sized {
 21    fn num_lines(&self, cx: &mut WindowContext) -> u8;
 22}
 23
 24/// When deciding what to render from a collection of mediatypes, we need to rank them in order of importance
 25fn rank_mime_type(mimetype: &MimeType) -> usize {
 26    match mimetype {
 27        MimeType::DataTable(_) => 6,
 28        MimeType::Png(_) => 4,
 29        MimeType::Jpeg(_) => 3,
 30        MimeType::Markdown(_) => 2,
 31        MimeType::Plain(_) => 1,
 32        // All other media types are not supported in Zed at this time
 33        _ => 0,
 34    }
 35}
 36
 37/// ImageView renders an image inline in an editor, adapting to the line height to fit the image.
 38pub struct ImageView {
 39    height: u32,
 40    width: u32,
 41    image: Arc<ImageData>,
 42}
 43
 44impl ImageView {
 45    fn render(&self, cx: &ViewContext<ExecutionView>) -> AnyElement {
 46        let line_height = cx.line_height();
 47
 48        let (height, width) = if self.height as f32 / line_height.0 == u8::MAX as f32 {
 49            let height = u8::MAX as f32 * line_height.0;
 50            let width = self.width as f32 * height / self.height as f32;
 51            (height, width)
 52        } else {
 53            (self.height as f32, self.width as f32)
 54        };
 55
 56        let image = self.image.clone();
 57
 58        div()
 59            .h(Pixels(height))
 60            .w(Pixels(width))
 61            .child(img(image))
 62            .into_any_element()
 63    }
 64
 65    fn from(base64_encoded_data: &str) -> Result<Self> {
 66        let bytes = base64::decode(base64_encoded_data)?;
 67
 68        let format = image::guess_format(&bytes)?;
 69        let mut data = image::load_from_memory_with_format(&bytes, format)?.into_rgba8();
 70
 71        // Convert from RGBA to BGRA.
 72        for pixel in data.chunks_exact_mut(4) {
 73            pixel.swap(0, 2);
 74        }
 75
 76        let height = data.height();
 77        let width = data.width();
 78
 79        let gpui_image_data = ImageData::new(data);
 80
 81        return Ok(ImageView {
 82            height,
 83            width,
 84            image: Arc::new(gpui_image_data),
 85        });
 86    }
 87}
 88
 89impl LineHeight for ImageView {
 90    fn num_lines(&self, cx: &mut WindowContext) -> u8 {
 91        let line_height = cx.line_height();
 92
 93        let lines = self.height as f32 / line_height.0;
 94
 95        if lines > u8::MAX as f32 {
 96            return u8::MAX;
 97        }
 98        lines as u8
 99    }
100}
101
102/// TableView renders a static table inline in a buffer.
103/// It uses the https://specs.frictionlessdata.io/tabular-data-resource/ specification for data interchange.
104pub struct TableView {
105    pub table: TabularDataResource,
106    pub widths: Vec<Pixels>,
107}
108
109fn cell_content(row: &Value, field: &str) -> String {
110    match row.get(&field) {
111        Some(Value::String(s)) => s.clone(),
112        Some(Value::Number(n)) => n.to_string(),
113        Some(Value::Bool(b)) => b.to_string(),
114        Some(Value::Array(arr)) => format!("{:?}", arr),
115        Some(Value::Object(obj)) => format!("{:?}", obj),
116        Some(Value::Null) | None => String::new(),
117    }
118}
119
120impl TableView {
121    pub fn new(table: TabularDataResource, cx: &mut WindowContext) -> Self {
122        let mut widths = Vec::with_capacity(table.schema.fields.len());
123
124        let text_system = cx.text_system();
125        let text_style = cx.text_style();
126        let text_font = ThemeSettings::get_global(cx).buffer_font.clone();
127        let font_size = ThemeSettings::get_global(cx).buffer_font_size;
128        let mut runs = [TextRun {
129            len: 0,
130            font: text_font,
131            color: text_style.color,
132            background_color: None,
133            underline: None,
134            strikethrough: None,
135        }];
136
137        for field in table.schema.fields.iter() {
138            runs[0].len = field.name.len();
139            let mut width = text_system
140                .layout_line(&field.name, font_size, &runs)
141                .map(|layout| layout.width)
142                .unwrap_or(px(0.));
143
144            let Some(data) = table.data.as_ref() else {
145                widths.push(width);
146                continue;
147            };
148
149            for row in data {
150                let content = cell_content(&row, &field.name);
151                runs[0].len = content.len();
152                let cell_width = cx
153                    .text_system()
154                    .layout_line(&content, font_size, &runs)
155                    .map(|layout| layout.width)
156                    .unwrap_or(px(0.));
157
158                width = width.max(cell_width)
159            }
160
161            widths.push(width)
162        }
163
164        Self { table, widths }
165    }
166
167    pub fn render(&self, cx: &ViewContext<ExecutionView>) -> AnyElement {
168        let data = match &self.table.data {
169            Some(data) => data,
170            None => return div().into_any_element(),
171        };
172
173        // todo!(): compute the width of each column by finding the widest cell in each column
174
175        let mut headings = serde_json::Map::new();
176        for field in &self.table.schema.fields {
177            headings.insert(field.name.clone(), Value::String(field.name.clone()));
178        }
179        let header = self.render_row(&self.table.schema, true, &Value::Object(headings), cx);
180
181        let body = data
182            .iter()
183            .map(|row| self.render_row(&self.table.schema, false, &row, cx));
184
185        v_flex()
186            .id("table")
187            .overflow_x_scroll()
188            .w_full()
189            .child(header)
190            .children(body)
191            .into_any_element()
192    }
193
194    pub fn render_row(
195        &self,
196        schema: &TableSchema,
197        is_header: bool,
198        row: &Value,
199        cx: &ViewContext<ExecutionView>,
200    ) -> AnyElement {
201        let theme = cx.theme();
202
203        let row_cells = schema
204            .fields
205            .iter()
206            .zip(self.widths.iter())
207            .map(|(field, width)| {
208                let container = match field.field_type {
209                    runtimelib::datatable::FieldType::String => div(),
210
211                    runtimelib::datatable::FieldType::Number
212                    | runtimelib::datatable::FieldType::Integer
213                    | runtimelib::datatable::FieldType::Date
214                    | runtimelib::datatable::FieldType::Time
215                    | runtimelib::datatable::FieldType::Datetime
216                    | runtimelib::datatable::FieldType::Year
217                    | runtimelib::datatable::FieldType::Duration
218                    | runtimelib::datatable::FieldType::Yearmonth => v_flex().items_end(),
219
220                    _ => div(),
221                };
222
223                let value = cell_content(row, &field.name);
224
225                let mut cell = container
226                    .min_w(*width + px(22.))
227                    .w(*width + px(22.))
228                    .child(value)
229                    .px_2()
230                    .py_1()
231                    .border_color(theme.colors().border);
232
233                if is_header {
234                    cell = cell.border_2().bg(theme.colors().border_focused)
235                } else {
236                    cell = cell.border_1()
237                }
238                cell
239            })
240            .collect::<Vec<_>>();
241
242        let mut total_width = px(0.);
243        for width in self.widths.iter() {
244            // Width fudge factor: border + 2 (heading), padding
245            total_width += *width + px(22.);
246        }
247
248        h_flex()
249            .w(total_width)
250            .children(row_cells)
251            .into_any_element()
252    }
253}
254
255impl LineHeight for TableView {
256    fn num_lines(&self, _cx: &mut WindowContext) -> u8 {
257        let num_rows = match &self.table.data {
258            Some(data) => data.len(),
259            // We don't support Path based data sources
260            None => 0,
261        };
262
263        // Given that each cell has both `py_1` and a border, we have to estimate
264        // a reasonable size to add on, then round up.
265        let row_heights = (num_rows as f32 * 1.2) + 1.0;
266
267        (row_heights as u8).saturating_add(2) // Header + spacing
268    }
269}
270
271/// Userspace error from the kernel
272pub struct ErrorView {
273    pub ename: String,
274    pub evalue: String,
275    pub traceback: TerminalOutput,
276}
277
278impl ErrorView {
279    fn render(&self, cx: &ViewContext<ExecutionView>) -> Option<AnyElement> {
280        let theme = cx.theme();
281
282        let colors = cx.theme().colors();
283
284        Some(
285            v_flex()
286                .w_full()
287                .bg(colors.background)
288                .py(cx.line_height() / 2.)
289                .border_l_1()
290                .border_color(theme.status().error_border)
291                .child(
292                    h_flex()
293                        .font_weight(FontWeight::BOLD)
294                        .child(format!("{}: {}", self.ename, self.evalue)),
295                )
296                .child(self.traceback.render(cx))
297                .into_any_element(),
298        )
299    }
300}
301
302impl LineHeight for ErrorView {
303    fn num_lines(&self, cx: &mut WindowContext) -> u8 {
304        let mut height: u8 = 1; // Start at 1 to account for the y padding
305        height = height.saturating_add(self.ename.lines().count() as u8);
306        height = height.saturating_add(self.evalue.lines().count() as u8);
307        height = height.saturating_add(self.traceback.num_lines(cx));
308        height
309    }
310}
311
312pub enum OutputType {
313    Plain(TerminalOutput),
314    Stream(TerminalOutput),
315    Image(ImageView),
316    ErrorOutput(ErrorView),
317    Message(String),
318    Table(TableView),
319    ClearOutputWaitMarker,
320}
321
322impl OutputType {
323    fn render(&self, cx: &ViewContext<ExecutionView>) -> Option<AnyElement> {
324        let el = match self {
325            // Note: in typical frontends we would show the execute_result.execution_count
326            // Here we can just handle either
327            Self::Plain(stdio) => Some(stdio.render(cx)),
328            // Self::Markdown(markdown) => Some(markdown.render(theme)),
329            Self::Stream(stdio) => Some(stdio.render(cx)),
330            Self::Image(image) => Some(image.render(cx)),
331            Self::Message(message) => Some(div().child(message.clone()).into_any_element()),
332            Self::Table(table) => Some(table.render(cx)),
333            Self::ErrorOutput(error_view) => error_view.render(cx),
334            Self::ClearOutputWaitMarker => None,
335        };
336
337        el
338    }
339
340    pub fn new(data: &MimeBundle, cx: &mut WindowContext) -> Self {
341        match data.richest(rank_mime_type) {
342            Some(MimeType::Plain(text)) => OutputType::Plain(TerminalOutput::from(text)),
343            Some(MimeType::Markdown(text)) => OutputType::Plain(TerminalOutput::from(text)),
344            Some(MimeType::Png(data)) | Some(MimeType::Jpeg(data)) => match ImageView::from(data) {
345                Ok(view) => OutputType::Image(view),
346                Err(error) => OutputType::Message(format!("Failed to load image: {}", error)),
347            },
348            Some(MimeType::DataTable(data)) => OutputType::Table(TableView::new(data.clone(), cx)),
349            // Any other media types are not supported
350            _ => OutputType::Message("Unsupported media type".to_string()),
351        }
352    }
353}
354
355impl LineHeight for OutputType {
356    /// Calculates the expected number of lines
357    fn num_lines(&self, cx: &mut WindowContext) -> u8 {
358        match self {
359            Self::Plain(stdio) => stdio.num_lines(cx),
360            Self::Stream(stdio) => stdio.num_lines(cx),
361            Self::Image(image) => image.num_lines(cx),
362            Self::Message(message) => message.lines().count() as u8,
363            Self::Table(table) => table.num_lines(cx),
364            Self::ErrorOutput(error_view) => error_view.num_lines(cx),
365            Self::ClearOutputWaitMarker => 0,
366        }
367    }
368}
369
370#[derive(Default, Clone, Debug)]
371pub enum ExecutionStatus {
372    #[default]
373    Unknown,
374    ConnectingToKernel,
375    Queued,
376    Executing,
377    Finished,
378    ShuttingDown,
379    Shutdown,
380    KernelErrored(String),
381}
382
383pub struct ExecutionView {
384    pub outputs: Vec<OutputType>,
385    pub status: ExecutionStatus,
386}
387
388impl ExecutionView {
389    pub fn new(status: ExecutionStatus, _cx: &mut ViewContext<Self>) -> Self {
390        Self {
391            outputs: Default::default(),
392            status,
393        }
394    }
395
396    /// Accept a Jupyter message belonging to this execution
397    pub fn push_message(&mut self, message: &JupyterMessageContent, cx: &mut ViewContext<Self>) {
398        let output: OutputType = match message {
399            JupyterMessageContent::ExecuteResult(result) => OutputType::new(&result.data, cx),
400            JupyterMessageContent::DisplayData(result) => OutputType::new(&result.data, cx),
401            JupyterMessageContent::StreamContent(result) => {
402                // Previous stream data will combine together, handling colors, carriage returns, etc
403                if let Some(new_terminal) = self.apply_terminal_text(&result.text) {
404                    new_terminal
405                } else {
406                    cx.notify();
407                    return;
408                }
409            }
410            JupyterMessageContent::ErrorOutput(result) => {
411                let mut terminal = TerminalOutput::new();
412                terminal.append_text(&result.traceback.join("\n"));
413
414                OutputType::ErrorOutput(ErrorView {
415                    ename: result.ename.clone(),
416                    evalue: result.evalue.clone(),
417                    traceback: terminal,
418                })
419            }
420            JupyterMessageContent::ExecuteReply(reply) => {
421                for payload in reply.payload.iter() {
422                    match payload {
423                        // Pager data comes in via `?` at the end of a statement in Python, used for showing documentation.
424                        // Some UI will show this as a popup. For ease of implementation, it's included as an output here.
425                        runtimelib::Payload::Page { data, .. } => {
426                            let output = OutputType::new(data, cx);
427                            self.outputs.push(output);
428                        }
429
430                        // Comments from @rgbkrk, reach out with questions
431
432                        // Set next input adds text to the next cell. Not required to support.
433                        // However, this could be implemented by adding text to the buffer.
434                        // runtimelib::Payload::SetNextInput { text, replace } => {},
435
436                        // Not likely to be used in the context of Zed, where someone could just open the buffer themselves
437                        // runtimelib::Payload::EditMagic { filename, line_number } => {},
438
439                        // Ask the user if they want to exit the kernel. Not required to support.
440                        // runtimelib::Payload::AskExit { keepkernel } => {},
441                        _ => {}
442                    }
443                }
444                cx.notify();
445                return;
446            }
447            JupyterMessageContent::ClearOutput(options) => {
448                if !options.wait {
449                    self.outputs.clear();
450                    cx.notify();
451                    return;
452                }
453
454                // Create a marker to clear the output after we get in a new output
455                OutputType::ClearOutputWaitMarker
456            }
457            JupyterMessageContent::Status(status) => {
458                match status.execution_state {
459                    ExecutionState::Busy => {
460                        self.status = ExecutionStatus::Executing;
461                    }
462                    ExecutionState::Idle => self.status = ExecutionStatus::Finished,
463                }
464                cx.notify();
465                return;
466            }
467            _msg => {
468                return;
469            }
470        };
471
472        // Check for a clear output marker as the previous output, so we can clear it out
473        if let Some(OutputType::ClearOutputWaitMarker) = self.outputs.last() {
474            self.outputs.clear();
475        }
476
477        self.outputs.push(output);
478
479        cx.notify();
480    }
481
482    fn apply_terminal_text(&mut self, text: &str) -> Option<OutputType> {
483        if let Some(last_output) = self.outputs.last_mut() {
484            match last_output {
485                OutputType::Stream(last_stream) => {
486                    last_stream.append_text(text);
487                    // Don't need to add a new output, we already have a terminal output
488                    return None;
489                }
490                // Edge case note: a clear output marker
491                OutputType::ClearOutputWaitMarker => {
492                    // Edge case note: a clear output marker is handled by the caller
493                    // since we will return a new output at the end here as a new terminal output
494                }
495                // A different output type is "in the way", so we need to create a new output,
496                // which is the same as having no prior output
497                _ => {}
498            }
499        }
500
501        let mut new_terminal = TerminalOutput::new();
502        new_terminal.append_text(text);
503        Some(OutputType::Stream(new_terminal))
504    }
505}
506
507impl Render for ExecutionView {
508    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
509        if self.outputs.len() == 0 {
510            return v_flex()
511                .min_h(cx.line_height())
512                .justify_center()
513                .child(match &self.status {
514                    ExecutionStatus::ConnectingToKernel => Label::new("Connecting to kernel...")
515                        .color(Color::Muted)
516                        .into_any_element(),
517                    ExecutionStatus::Executing => h_flex()
518                        .gap_2()
519                        .child(
520                            Icon::new(IconName::ArrowCircle)
521                                .size(IconSize::Small)
522                                .color(Color::Muted)
523                                .with_animation(
524                                    "arrow-circle",
525                                    Animation::new(Duration::from_secs(3)).repeat(),
526                                    |icon, delta| {
527                                        icon.transform(Transformation::rotate(percentage(delta)))
528                                    },
529                                ),
530                        )
531                        .child(Label::new("Executing...").color(Color::Muted))
532                        .into_any_element(),
533                    ExecutionStatus::Finished => Icon::new(IconName::Check)
534                        .size(IconSize::Small)
535                        .into_any_element(),
536                    ExecutionStatus::Unknown => Label::new("Unknown status")
537                        .color(Color::Muted)
538                        .into_any_element(),
539                    ExecutionStatus::ShuttingDown => Label::new("Kernel shutting down...")
540                        .color(Color::Muted)
541                        .into_any_element(),
542                    ExecutionStatus::Shutdown => Label::new("Kernel shutdown")
543                        .color(Color::Muted)
544                        .into_any_element(),
545                    ExecutionStatus::Queued => Label::new("Queued...")
546                        .color(Color::Muted)
547                        .into_any_element(),
548                    ExecutionStatus::KernelErrored(error) => {
549                        Label::new(format!("Kernel error: {}", error))
550                            .color(Color::Error)
551                            .into_any_element()
552                    }
553                })
554                .into_any_element();
555        }
556
557        div()
558            .w_full()
559            .children(self.outputs.iter().filter_map(|output| output.render(cx)))
560            .into_any_element()
561    }
562}
563
564impl LineHeight for ExecutionView {
565    fn num_lines(&self, cx: &mut WindowContext) -> u8 {
566        if self.outputs.is_empty() {
567            return 1; // For the status message if outputs are not there
568        }
569
570        self.outputs
571            .iter()
572            .map(|output| output.num_lines(cx))
573            .fold(0_u8, |acc, additional_height| {
574                acc.saturating_add(additional_height)
575            })
576            .max(1)
577    }
578}
579
580impl LineHeight for View<ExecutionView> {
581    fn num_lines(&self, cx: &mut WindowContext) -> u8 {
582        self.update(cx, |execution_view, cx| execution_view.num_lines(cx))
583    }
584}