outputs.rs

  1//! # REPL Output Module
  2//!
  3//! This module provides the core functionality for handling and displaying
  4//! various types of output from Jupyter kernels.
  5//!
  6//! ## Key Components
  7//!
  8//! - `OutputContent`: An enum that encapsulates different types of output content.
  9//! - `ExecutionView`: Manages the display of outputs for a single execution.
 10//! - `ExecutionStatus`: Represents the current status of an execution.
 11//!
 12//! ## Output Types
 13//!
 14//! The module supports several output types, including:
 15//! - Plain text
 16//! - Markdown
 17//! - Images (PNG and JPEG)
 18//! - Tables
 19//! - Error messages
 20//!
 21//! ## Clipboard Support
 22//!
 23//! Most output types implement the `SupportsClipboard` trait, allowing
 24//! users to easily copy output content to the system clipboard.
 25//!
 26//! ## Rendering
 27//!
 28//! The module provides rendering capabilities for each output type,
 29//! ensuring proper display within the REPL interface.
 30//!
 31//! ## Jupyter Integration
 32//!
 33//! This module is designed to work with Jupyter message protocols,
 34//! interpreting and displaying various types of Jupyter output.
 35
 36use std::time::Duration;
 37
 38use editor::{Editor, MultiBuffer};
 39use gpui::{
 40    Animation, AnimationExt, AnyElement, ClipboardItem, Entity, Render, Transformation, WeakEntity,
 41    percentage,
 42};
 43use language::Buffer;
 44use runtimelib::{ExecutionState, JupyterMessageContent, MimeBundle, MimeType};
 45use ui::{Context, IntoElement, Styled, Tooltip, Window, div, prelude::*, v_flex};
 46
 47mod image;
 48use image::ImageView;
 49
 50mod markdown;
 51use markdown::MarkdownView;
 52
 53mod table;
 54use table::TableView;
 55
 56pub mod plain;
 57use plain::TerminalOutput;
 58
 59pub(crate) mod user_error;
 60use user_error::ErrorView;
 61use workspace::Workspace;
 62
 63/// When deciding what to render from a collection of mediatypes, we need to rank them in order of importance
 64fn rank_mime_type(mimetype: &MimeType) -> usize {
 65    match mimetype {
 66        MimeType::DataTable(_) => 6,
 67        MimeType::Png(_) => 4,
 68        MimeType::Jpeg(_) => 3,
 69        MimeType::Markdown(_) => 2,
 70        MimeType::Plain(_) => 1,
 71        // All other media types are not supported in Zed at this time
 72        _ => 0,
 73    }
 74}
 75
 76pub(crate) trait OutputContent {
 77    fn clipboard_content(&self, window: &Window, cx: &App) -> Option<ClipboardItem>;
 78    fn has_clipboard_content(&self, _window: &Window, _cx: &App) -> bool {
 79        false
 80    }
 81    fn has_buffer_content(&self, _window: &Window, _cx: &App) -> bool {
 82        false
 83    }
 84    fn buffer_content(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Entity<Buffer>> {
 85        None
 86    }
 87}
 88
 89impl<V: OutputContent + 'static> OutputContent for Entity<V> {
 90    fn clipboard_content(&self, window: &Window, cx: &App) -> Option<ClipboardItem> {
 91        self.read(cx).clipboard_content(window, cx)
 92    }
 93
 94    fn has_clipboard_content(&self, window: &Window, cx: &App) -> bool {
 95        self.read(cx).has_clipboard_content(window, cx)
 96    }
 97
 98    fn has_buffer_content(&self, window: &Window, cx: &App) -> bool {
 99        self.read(cx).has_buffer_content(window, cx)
100    }
101
102    fn buffer_content(&mut self, window: &mut Window, cx: &mut App) -> Option<Entity<Buffer>> {
103        self.update(cx, |item, cx| item.buffer_content(window, cx))
104    }
105}
106
107pub enum Output {
108    Plain {
109        content: Entity<TerminalOutput>,
110        display_id: Option<String>,
111    },
112    Stream {
113        content: Entity<TerminalOutput>,
114    },
115    Image {
116        content: Entity<ImageView>,
117        display_id: Option<String>,
118    },
119    ErrorOutput(ErrorView),
120    Message(String),
121    Table {
122        content: Entity<TableView>,
123        display_id: Option<String>,
124    },
125    Markdown {
126        content: Entity<MarkdownView>,
127        display_id: Option<String>,
128    },
129    ClearOutputWaitMarker,
130}
131
132impl Output {
133    fn render_output_controls<V: OutputContent + 'static>(
134        v: Entity<V>,
135        workspace: WeakEntity<Workspace>,
136        window: &mut Window,
137        cx: &mut Context<ExecutionView>,
138    ) -> Option<AnyElement> {
139        if !v.has_clipboard_content(window, cx) && !v.has_buffer_content(window, cx) {
140            return None;
141        }
142
143        Some(
144            h_flex()
145                .pl_1()
146                .when(v.has_clipboard_content(window, cx), |el| {
147                    let v = v.clone();
148                    el.child(
149                        IconButton::new(ElementId::Name("copy-output".into()), IconName::Copy)
150                            .style(ButtonStyle::Transparent)
151                            .tooltip(Tooltip::text("Copy Output"))
152                            .on_click(cx.listener(move |_, _, window, cx| {
153                                let clipboard_content = v.clipboard_content(window, cx);
154
155                                if let Some(clipboard_content) = clipboard_content.as_ref() {
156                                    cx.write_to_clipboard(clipboard_content.clone());
157                                }
158                            })),
159                    )
160                })
161                .when(v.has_buffer_content(window, cx), |el| {
162                    let v = v.clone();
163                    el.child(
164                        IconButton::new(
165                            ElementId::Name("open-in-buffer".into()),
166                            IconName::FileText,
167                        )
168                        .style(ButtonStyle::Transparent)
169                        .tooltip(Tooltip::text("Open in Buffer"))
170                        .on_click(cx.listener({
171                            let workspace = workspace.clone();
172
173                            move |_, _, window, cx| {
174                                let buffer_content =
175                                    v.update(cx, |item, cx| item.buffer_content(window, cx));
176
177                                if let Some(buffer_content) = buffer_content.as_ref() {
178                                    let buffer = buffer_content.clone();
179                                    let editor = Box::new(cx.new(|cx| {
180                                        let multibuffer = cx.new(|cx| {
181                                            let mut multi_buffer =
182                                                MultiBuffer::singleton(buffer.clone(), cx);
183
184                                            multi_buffer.set_title("REPL Output".to_string(), cx);
185                                            multi_buffer
186                                        });
187
188                                        Editor::for_multibuffer(multibuffer, None, window, cx)
189                                    }));
190                                    workspace
191                                        .update(cx, |workspace, cx| {
192                                            workspace.add_item_to_active_pane(
193                                                editor, None, true, window, cx,
194                                            );
195                                        })
196                                        .ok();
197                                }
198                            }
199                        })),
200                    )
201                })
202                .into_any_element(),
203        )
204    }
205
206    pub fn render(
207        &self,
208        workspace: WeakEntity<Workspace>,
209        window: &mut Window,
210        cx: &mut Context<ExecutionView>,
211    ) -> impl IntoElement + use<> {
212        let content = match self {
213            Self::Plain { content, .. } => Some(content.clone().into_any_element()),
214            Self::Markdown { content, .. } => Some(content.clone().into_any_element()),
215            Self::Stream { content, .. } => Some(content.clone().into_any_element()),
216            Self::Image { content, .. } => Some(content.clone().into_any_element()),
217            Self::Message(message) => Some(div().child(message.clone()).into_any_element()),
218            Self::Table { content, .. } => Some(content.clone().into_any_element()),
219            Self::ErrorOutput(error_view) => error_view.render(window, cx),
220            Self::ClearOutputWaitMarker => None,
221        };
222
223        h_flex()
224            .w_full()
225            .items_start()
226            .child(div().flex_1().children(content))
227            .children(match self {
228                Self::Plain { content, .. } => {
229                    Self::render_output_controls(content.clone(), workspace.clone(), window, cx)
230                }
231                Self::Markdown { content, .. } => {
232                    Self::render_output_controls(content.clone(), workspace.clone(), window, cx)
233                }
234                Self::Stream { content, .. } => {
235                    Self::render_output_controls(content.clone(), workspace.clone(), window, cx)
236                }
237                Self::Image { content, .. } => {
238                    Self::render_output_controls(content.clone(), workspace.clone(), window, cx)
239                }
240                Self::ErrorOutput(err) => Self::render_output_controls(
241                    err.traceback.clone(),
242                    workspace.clone(),
243                    window,
244                    cx,
245                ),
246                Self::Message(_) => None,
247                Self::Table { content, .. } => {
248                    Self::render_output_controls(content.clone(), workspace.clone(), window, cx)
249                }
250                Self::ClearOutputWaitMarker => None,
251            })
252    }
253
254    pub fn display_id(&self) -> Option<String> {
255        match self {
256            Output::Plain { display_id, .. } => display_id.clone(),
257            Output::Stream { .. } => None,
258            Output::Image { display_id, .. } => display_id.clone(),
259            Output::ErrorOutput(_) => None,
260            Output::Message(_) => None,
261            Output::Table { display_id, .. } => display_id.clone(),
262            Output::Markdown { display_id, .. } => display_id.clone(),
263            Output::ClearOutputWaitMarker => None,
264        }
265    }
266
267    pub fn new(
268        data: &MimeBundle,
269        display_id: Option<String>,
270        window: &mut Window,
271        cx: &mut App,
272    ) -> Self {
273        match data.richest(rank_mime_type) {
274            Some(MimeType::Plain(text)) => Output::Plain {
275                content: cx.new(|cx| TerminalOutput::from(text, window, cx)),
276                display_id,
277            },
278            Some(MimeType::Markdown(text)) => {
279                let content = cx.new(|cx| MarkdownView::from(text.clone(), cx));
280                Output::Markdown {
281                    content,
282                    display_id,
283                }
284            }
285            Some(MimeType::Png(data)) | Some(MimeType::Jpeg(data)) => match ImageView::from(data) {
286                Ok(view) => Output::Image {
287                    content: cx.new(|_| view),
288                    display_id,
289                },
290                Err(error) => Output::Message(format!("Failed to load image: {}", error)),
291            },
292            Some(MimeType::DataTable(data)) => Output::Table {
293                content: cx.new(|cx| TableView::new(data, window, cx)),
294                display_id,
295            },
296            // Any other media types are not supported
297            _ => Output::Message("Unsupported media type".to_string()),
298        }
299    }
300}
301
302#[derive(Default, Clone, Debug)]
303pub enum ExecutionStatus {
304    #[default]
305    Unknown,
306    ConnectingToKernel,
307    Queued,
308    Executing,
309    Finished,
310    ShuttingDown,
311    Shutdown,
312    KernelErrored(String),
313    Restarting,
314}
315
316/// An ExecutionView shows the outputs of an execution.
317/// It can hold zero or more outputs, which the user
318/// sees as "the output" for a single execution.
319pub struct ExecutionView {
320    #[allow(unused)]
321    workspace: WeakEntity<Workspace>,
322    pub outputs: Vec<Output>,
323    pub status: ExecutionStatus,
324}
325
326impl ExecutionView {
327    pub fn new(
328        status: ExecutionStatus,
329        workspace: WeakEntity<Workspace>,
330        _cx: &mut Context<Self>,
331    ) -> Self {
332        Self {
333            workspace,
334            outputs: Default::default(),
335            status,
336        }
337    }
338
339    /// Accept a Jupyter message belonging to this execution
340    pub fn push_message(
341        &mut self,
342        message: &JupyterMessageContent,
343        window: &mut Window,
344        cx: &mut Context<Self>,
345    ) {
346        let output: Output = match message {
347            JupyterMessageContent::ExecuteResult(result) => Output::new(
348                &result.data,
349                result.transient.as_ref().and_then(|t| t.display_id.clone()),
350                window,
351                cx,
352            ),
353            JupyterMessageContent::DisplayData(result) => Output::new(
354                &result.data,
355                result.transient.as_ref().and_then(|t| t.display_id.clone()),
356                window,
357                cx,
358            ),
359            JupyterMessageContent::StreamContent(result) => {
360                // Previous stream data will combine together, handling colors, carriage returns, etc
361                if let Some(new_terminal) = self.apply_terminal_text(&result.text, window, cx) {
362                    new_terminal
363                } else {
364                    return;
365                }
366            }
367            JupyterMessageContent::ErrorOutput(result) => {
368                let terminal =
369                    cx.new(|cx| TerminalOutput::from(&result.traceback.join("\n"), window, cx));
370
371                Output::ErrorOutput(ErrorView {
372                    ename: result.ename.clone(),
373                    evalue: result.evalue.clone(),
374                    traceback: terminal,
375                })
376            }
377            JupyterMessageContent::ExecuteReply(reply) => {
378                for payload in reply.payload.iter() {
379                    if let runtimelib::Payload::Page { data, .. } = payload {
380                        let output = Output::new(data, None, window, cx);
381                        self.outputs.push(output);
382                    }
383                }
384                cx.notify();
385                return;
386            }
387            JupyterMessageContent::ClearOutput(options) => {
388                if !options.wait {
389                    self.outputs.clear();
390                    cx.notify();
391                    return;
392                }
393
394                // Create a marker to clear the output after we get in a new output
395                Output::ClearOutputWaitMarker
396            }
397            JupyterMessageContent::Status(status) => {
398                match status.execution_state {
399                    ExecutionState::Busy => {
400                        self.status = ExecutionStatus::Executing;
401                    }
402                    ExecutionState::Idle => self.status = ExecutionStatus::Finished,
403                }
404                cx.notify();
405                return;
406            }
407            _msg => {
408                return;
409            }
410        };
411
412        // Check for a clear output marker as the previous output, so we can clear it out
413        if let Some(output) = self.outputs.last() {
414            if let Output::ClearOutputWaitMarker = output {
415                self.outputs.clear();
416            }
417        }
418
419        self.outputs.push(output);
420
421        cx.notify();
422    }
423
424    pub fn update_display_data(
425        &mut self,
426        data: &MimeBundle,
427        display_id: &str,
428        window: &mut Window,
429        cx: &mut Context<Self>,
430    ) {
431        let mut any = false;
432
433        self.outputs.iter_mut().for_each(|output| {
434            if let Some(other_display_id) = output.display_id().as_ref() {
435                if other_display_id == display_id {
436                    *output = Output::new(data, Some(display_id.to_owned()), window, cx);
437                    any = true;
438                }
439            }
440        });
441
442        if any {
443            cx.notify();
444        }
445    }
446
447    fn apply_terminal_text(
448        &mut self,
449        text: &str,
450        window: &mut Window,
451        cx: &mut Context<Self>,
452    ) -> Option<Output> {
453        if let Some(last_output) = self.outputs.last_mut() {
454            if let Output::Stream {
455                content: last_stream,
456            } = last_output
457            {
458                // Don't need to add a new output, we already have a terminal output
459                // and can just update the most recent terminal output
460                last_stream.update(cx, |last_stream, cx| {
461                    last_stream.append_text(text, cx);
462                    cx.notify();
463                });
464                return None;
465            }
466        }
467
468        Some(Output::Stream {
469            content: cx.new(|cx| TerminalOutput::from(text, window, cx)),
470        })
471    }
472}
473
474impl Render for ExecutionView {
475    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
476        let status = match &self.status {
477            ExecutionStatus::ConnectingToKernel => Label::new("Connecting to kernel...")
478                .color(Color::Muted)
479                .into_any_element(),
480            ExecutionStatus::Executing => h_flex()
481                .gap_2()
482                .child(
483                    Icon::new(IconName::ArrowCircle)
484                        .size(IconSize::Small)
485                        .color(Color::Muted)
486                        .with_animation(
487                            "arrow-circle",
488                            Animation::new(Duration::from_secs(3)).repeat(),
489                            |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
490                        ),
491                )
492                .child(Label::new("Executing...").color(Color::Muted))
493                .into_any_element(),
494            ExecutionStatus::Finished => Icon::new(IconName::Check)
495                .size(IconSize::Small)
496                .into_any_element(),
497            ExecutionStatus::Unknown => Label::new("Unknown status")
498                .color(Color::Muted)
499                .into_any_element(),
500            ExecutionStatus::ShuttingDown => Label::new("Kernel shutting down...")
501                .color(Color::Muted)
502                .into_any_element(),
503            ExecutionStatus::Restarting => Label::new("Kernel restarting...")
504                .color(Color::Muted)
505                .into_any_element(),
506            ExecutionStatus::Shutdown => Label::new("Kernel shutdown")
507                .color(Color::Muted)
508                .into_any_element(),
509            ExecutionStatus::Queued => Label::new("Queued...")
510                .color(Color::Muted)
511                .into_any_element(),
512            ExecutionStatus::KernelErrored(error) => Label::new(format!("Kernel error: {}", error))
513                .color(Color::Error)
514                .into_any_element(),
515        };
516
517        if self.outputs.is_empty() {
518            return v_flex()
519                .min_h(window.line_height())
520                .justify_center()
521                .child(status)
522                .into_any_element();
523        }
524
525        div()
526            .w_full()
527            .children(
528                self.outputs
529                    .iter()
530                    .map(|output| output.render(self.workspace.clone(), window, cx)),
531            )
532            .children(match self.status {
533                ExecutionStatus::Executing => vec![status],
534                ExecutionStatus::Queued => vec![status],
535                _ => vec![],
536            })
537            .into_any_element()
538    }
539}