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    percentage, Animation, AnimationExt, AnyElement, ClipboardItem, Entity, Render, Transformation,
 41    WeakEntity,
 42};
 43use language::Buffer;
 44use runtimelib::{ExecutionState, JupyterMessageContent, MimeBundle, MimeType};
 45use ui::{div, prelude::*, v_flex, Context, IntoElement, Styled, Tooltip, Window};
 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
209        workspace: WeakEntity<Workspace>,
210        window: &mut Window,
211        cx: &mut Context<ExecutionView>,
212    ) -> impl IntoElement {
213        let content = match self {
214            Self::Plain { content, .. } => Some(content.clone().into_any_element()),
215            Self::Markdown { content, .. } => Some(content.clone().into_any_element()),
216            Self::Stream { content, .. } => Some(content.clone().into_any_element()),
217            Self::Image { content, .. } => Some(content.clone().into_any_element()),
218            Self::Message(message) => Some(div().child(message.clone()).into_any_element()),
219            Self::Table { content, .. } => Some(content.clone().into_any_element()),
220            Self::ErrorOutput(error_view) => error_view.render(window, cx),
221            Self::ClearOutputWaitMarker => None,
222        };
223
224        h_flex()
225            .w_full()
226            .items_start()
227            .child(div().flex_1().children(content))
228            .children(match self {
229                Self::Plain { content, .. } => {
230                    Self::render_output_controls(content.clone(), workspace.clone(), window, cx)
231                }
232                Self::Markdown { content, .. } => {
233                    Self::render_output_controls(content.clone(), workspace.clone(), window, cx)
234                }
235                Self::Stream { content, .. } => {
236                    Self::render_output_controls(content.clone(), workspace.clone(), window, cx)
237                }
238                Self::Image { content, .. } => {
239                    Self::render_output_controls(content.clone(), workspace.clone(), window, cx)
240                }
241                Self::ErrorOutput(err) => Self::render_output_controls(
242                    err.traceback.clone(),
243                    workspace.clone(),
244                    window,
245                    cx,
246                ),
247                Self::Message(_) => None,
248                Self::Table { content, .. } => {
249                    Self::render_output_controls(content.clone(), workspace.clone(), window, cx)
250                }
251                Self::ClearOutputWaitMarker => None,
252            })
253    }
254
255    pub fn display_id(&self) -> Option<String> {
256        match self {
257            Output::Plain { display_id, .. } => display_id.clone(),
258            Output::Stream { .. } => None,
259            Output::Image { display_id, .. } => display_id.clone(),
260            Output::ErrorOutput(_) => None,
261            Output::Message(_) => None,
262            Output::Table { display_id, .. } => display_id.clone(),
263            Output::Markdown { display_id, .. } => display_id.clone(),
264            Output::ClearOutputWaitMarker => None,
265        }
266    }
267
268    pub fn new(
269        data: &MimeBundle,
270        display_id: Option<String>,
271        window: &mut Window,
272        cx: &mut App,
273    ) -> Self {
274        match data.richest(rank_mime_type) {
275            Some(MimeType::Plain(text)) => Output::Plain {
276                content: cx.new(|cx| TerminalOutput::from(text, window, cx)),
277                display_id,
278            },
279            Some(MimeType::Markdown(text)) => {
280                let content = cx.new(|cx| MarkdownView::from(text.clone(), cx));
281                Output::Markdown {
282                    content,
283                    display_id,
284                }
285            }
286            Some(MimeType::Png(data)) | Some(MimeType::Jpeg(data)) => match ImageView::from(data) {
287                Ok(view) => Output::Image {
288                    content: cx.new(|_| view),
289                    display_id,
290                },
291                Err(error) => Output::Message(format!("Failed to load image: {}", error)),
292            },
293            Some(MimeType::DataTable(data)) => Output::Table {
294                content: cx.new(|cx| TableView::new(data, window, cx)),
295                display_id,
296            },
297            // Any other media types are not supported
298            _ => Output::Message("Unsupported media type".to_string()),
299        }
300    }
301}
302
303#[derive(Default, Clone, Debug)]
304pub enum ExecutionStatus {
305    #[default]
306    Unknown,
307    ConnectingToKernel,
308    Queued,
309    Executing,
310    Finished,
311    ShuttingDown,
312    Shutdown,
313    KernelErrored(String),
314    Restarting,
315}
316
317/// An ExecutionView shows the outputs of an execution.
318/// It can hold zero or more outputs, which the user
319/// sees as "the output" for a single execution.
320pub struct ExecutionView {
321    #[allow(unused)]
322    workspace: WeakEntity<Workspace>,
323    pub outputs: Vec<Output>,
324    pub status: ExecutionStatus,
325}
326
327impl ExecutionView {
328    pub fn new(
329        status: ExecutionStatus,
330        workspace: WeakEntity<Workspace>,
331        _cx: &mut Context<Self>,
332    ) -> Self {
333        Self {
334            workspace,
335            outputs: Default::default(),
336            status,
337        }
338    }
339
340    /// Accept a Jupyter message belonging to this execution
341    pub fn push_message(
342        &mut self,
343        message: &JupyterMessageContent,
344        window: &mut Window,
345        cx: &mut Context<Self>,
346    ) {
347        let output: Output = match message {
348            JupyterMessageContent::ExecuteResult(result) => Output::new(
349                &result.data,
350                result.transient.as_ref().and_then(|t| t.display_id.clone()),
351                window,
352                cx,
353            ),
354            JupyterMessageContent::DisplayData(result) => Output::new(
355                &result.data,
356                result.transient.as_ref().and_then(|t| t.display_id.clone()),
357                window,
358                cx,
359            ),
360            JupyterMessageContent::StreamContent(result) => {
361                // Previous stream data will combine together, handling colors, carriage returns, etc
362                if let Some(new_terminal) = self.apply_terminal_text(&result.text, window, cx) {
363                    new_terminal
364                } else {
365                    return;
366                }
367            }
368            JupyterMessageContent::ErrorOutput(result) => {
369                let terminal =
370                    cx.new(|cx| TerminalOutput::from(&result.traceback.join("\n"), window, cx));
371
372                Output::ErrorOutput(ErrorView {
373                    ename: result.ename.clone(),
374                    evalue: result.evalue.clone(),
375                    traceback: terminal,
376                })
377            }
378            JupyterMessageContent::ExecuteReply(reply) => {
379                for payload in reply.payload.iter() {
380                    if let runtimelib::Payload::Page { data, .. } = payload {
381                        let output = Output::new(data, None, window, cx);
382                        self.outputs.push(output);
383                    }
384                }
385                cx.notify();
386                return;
387            }
388            JupyterMessageContent::ClearOutput(options) => {
389                if !options.wait {
390                    self.outputs.clear();
391                    cx.notify();
392                    return;
393                }
394
395                // Create a marker to clear the output after we get in a new output
396                Output::ClearOutputWaitMarker
397            }
398            JupyterMessageContent::Status(status) => {
399                match status.execution_state {
400                    ExecutionState::Busy => {
401                        self.status = ExecutionStatus::Executing;
402                    }
403                    ExecutionState::Idle => self.status = ExecutionStatus::Finished,
404                }
405                cx.notify();
406                return;
407            }
408            _msg => {
409                return;
410            }
411        };
412
413        // Check for a clear output marker as the previous output, so we can clear it out
414        if let Some(output) = self.outputs.last() {
415            if let Output::ClearOutputWaitMarker = output {
416                self.outputs.clear();
417            }
418        }
419
420        self.outputs.push(output);
421
422        cx.notify();
423    }
424
425    pub fn update_display_data(
426        &mut self,
427        data: &MimeBundle,
428        display_id: &str,
429        window: &mut Window,
430        cx: &mut Context<Self>,
431    ) {
432        let mut any = false;
433
434        self.outputs.iter_mut().for_each(|output| {
435            if let Some(other_display_id) = output.display_id().as_ref() {
436                if other_display_id == display_id {
437                    *output = Output::new(data, Some(display_id.to_owned()), window, cx);
438                    any = true;
439                }
440            }
441        });
442
443        if any {
444            cx.notify();
445        }
446    }
447
448    fn apply_terminal_text(
449        &mut self,
450        text: &str,
451        window: &mut Window,
452        cx: &mut Context<Self>,
453    ) -> Option<Output> {
454        if let Some(last_output) = self.outputs.last_mut() {
455            if let Output::Stream {
456                content: last_stream,
457            } = last_output
458            {
459                // Don't need to add a new output, we already have a terminal output
460                // and can just update the most recent terminal output
461                last_stream.update(cx, |last_stream, cx| {
462                    last_stream.append_text(text, cx);
463                    cx.notify();
464                });
465                return None;
466            }
467        }
468
469        Some(Output::Stream {
470            content: cx.new(|cx| TerminalOutput::from(text, window, cx)),
471        })
472    }
473}
474
475impl Render for ExecutionView {
476    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
477        let status = match &self.status {
478            ExecutionStatus::ConnectingToKernel => Label::new("Connecting to kernel...")
479                .color(Color::Muted)
480                .into_any_element(),
481            ExecutionStatus::Executing => h_flex()
482                .gap_2()
483                .child(
484                    Icon::new(IconName::ArrowCircle)
485                        .size(IconSize::Small)
486                        .color(Color::Muted)
487                        .with_animation(
488                            "arrow-circle",
489                            Animation::new(Duration::from_secs(3)).repeat(),
490                            |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
491                        ),
492                )
493                .child(Label::new("Executing...").color(Color::Muted))
494                .into_any_element(),
495            ExecutionStatus::Finished => Icon::new(IconName::Check)
496                .size(IconSize::Small)
497                .into_any_element(),
498            ExecutionStatus::Unknown => Label::new("Unknown status")
499                .color(Color::Muted)
500                .into_any_element(),
501            ExecutionStatus::ShuttingDown => Label::new("Kernel shutting down...")
502                .color(Color::Muted)
503                .into_any_element(),
504            ExecutionStatus::Restarting => Label::new("Kernel restarting...")
505                .color(Color::Muted)
506                .into_any_element(),
507            ExecutionStatus::Shutdown => Label::new("Kernel shutdown")
508                .color(Color::Muted)
509                .into_any_element(),
510            ExecutionStatus::Queued => Label::new("Queued...")
511                .color(Color::Muted)
512                .into_any_element(),
513            ExecutionStatus::KernelErrored(error) => Label::new(format!("Kernel error: {}", error))
514                .color(Color::Error)
515                .into_any_element(),
516        };
517
518        if self.outputs.is_empty() {
519            return v_flex()
520                .min_h(window.line_height())
521                .justify_center()
522                .child(status)
523                .into_any_element();
524        }
525
526        div()
527            .w_full()
528            .children(
529                self.outputs
530                    .iter()
531                    .map(|output| output.render(self.workspace.clone(), window, cx)),
532            )
533            .children(match self.status {
534                ExecutionStatus::Executing => vec![status],
535                ExecutionStatus::Queued => vec![status],
536                _ => vec![],
537            })
538            .into_any_element()
539    }
540}