1290 lines · 48.1 KB · Rust
RawDownload
//! # REPL Output Module//!//! This module provides the core functionality for handling and displaying//! various types of output from Jupyter kernels.//!//! ## Key Components//!//! - `OutputContent`: An enum that encapsulates different types of output content.//! - `ExecutionView`: Manages the display of outputs for a single execution.//! - `ExecutionStatus`: Represents the current status of an execution.//!//! ## Output Types//!//! The module supports several output types, including://! - Plain text//! - Markdown//! - Images (PNG and JPEG)//! - Tables//! - Error messages//!//! ## Clipboard Support//!//! Most output types implement the `SupportsClipboard` trait, allowing//! users to easily copy output content to the system clipboard.//!//! ## Rendering//!//! The module provides rendering capabilities for each output type,//! ensuring proper display within the REPL interface.//!//! ## Jupyter Integration//!//! This module is designed to work with Jupyter message protocols,//! interpreting and displaying various types of Jupyter output. use editor::{Editor, MultiBuffer};use gpui::{AnyElement, ClipboardItem, Entity, EventEmitter, Render, WeakEntity};use language::Buffer;use menu;use runtimelib::{ExecutionState, JupyterMessage, JupyterMessageContent, MimeBundle, MimeType};use ui::{CommonAnimationExt, CopyButton, IconButton, Tooltip, prelude::*}; mod image;use image::ImageView; mod markdown;use markdown::MarkdownView; mod table;use table::TableView; mod json;use json::JsonView; mod html; pub mod plain;use plain::TerminalOutput; pub(crate) mod user_error;use user_error::ErrorView;use workspace::Workspace; use crate::repl_settings::ReplSettings;use settings::Settings; /// When deciding what to render from a collection of mediatypes, we need to rank them in order of importancefn rank_mime_type(mimetype: &MimeType) -> usize {    match mimetype {        MimeType::DataTable(_) => 7,        MimeType::Html(_) => 6,        MimeType::Json(_) => 5,        MimeType::Png(_) => 4,        MimeType::Jpeg(_) => 3,        MimeType::Markdown(_) => 2,        MimeType::Plain(_) => 1,        // All other media types are not supported in Zed at this time        _ => 0,    }} pub(crate) trait OutputContent {    fn clipboard_content(&self, window: &Window, cx: &App) -> Option<ClipboardItem>;    fn has_clipboard_content(&self, _window: &Window, _cx: &App) -> bool {        false    }    fn has_buffer_content(&self, _window: &Window, _cx: &App) -> bool {        false    }    fn buffer_content(&mut self, _window: &mut Window, _cx: &mut App) -> Option<Entity<Buffer>> {        None    }} impl<V: OutputContent + 'static> OutputContent for Entity<V> {    fn clipboard_content(&self, window: &Window, cx: &App) -> Option<ClipboardItem> {        self.read(cx).clipboard_content(window, cx)    }     fn has_clipboard_content(&self, window: &Window, cx: &App) -> bool {        self.read(cx).has_clipboard_content(window, cx)    }     fn has_buffer_content(&self, window: &Window, cx: &App) -> bool {        self.read(cx).has_buffer_content(window, cx)    }     fn buffer_content(&mut self, window: &mut Window, cx: &mut App) -> Option<Entity<Buffer>> {        self.update(cx, |item, cx| item.buffer_content(window, cx))    }} pub enum Output {    Plain {        content: Entity<TerminalOutput>,        display_id: Option<String>,    },    Stream {        content: Entity<TerminalOutput>,    },    Image {        content: Entity<ImageView>,        display_id: Option<String>,    },    ErrorOutput(ErrorView),    Message(String),    Table {        content: Entity<TableView>,        display_id: Option<String>,    },    Markdown {        content: Entity<MarkdownView>,        display_id: Option<String>,    },    Json {        content: Entity<JsonView>,        display_id: Option<String>,    },    ClearOutputWaitMarker,} impl Output {    pub fn to_nbformat(&self, cx: &App) -> Option<nbformat::v4::Output> {        match self {            Output::Stream { content } => {                let text = content.read(cx).full_text();                Some(nbformat::v4::Output::Stream {                    name: "stdout".to_string(),                    text: nbformat::v4::MultilineString(text),                })            }            Output::Plain { content, .. } => {                let text = content.read(cx).full_text();                let mut data = jupyter_protocol::media::Media::default();                data.content.push(jupyter_protocol::MediaType::Plain(text));                Some(nbformat::v4::Output::DisplayData(                    nbformat::v4::DisplayData {                        data,                        metadata: serde_json::Map::new(),                    },                ))            }            Output::ErrorOutput(error_view) => {                let traceback_text = error_view.traceback.read(cx).full_text();                let traceback_lines: Vec<String> =                    traceback_text.lines().map(|s| s.to_string()).collect();                Some(nbformat::v4::Output::Error(nbformat::v4::ErrorOutput {                    ename: error_view.ename.clone(),                    evalue: error_view.evalue.clone(),                    traceback: traceback_lines,                }))            }            Output::Image { .. }            | Output::Markdown { .. }            | Output::Table { .. }            | Output::Json { .. } => None,            Output::Message(_) => None,            Output::ClearOutputWaitMarker => None,        }    }} impl Output {    fn render_output_controls<V: OutputContent + 'static>(        v: Entity<V>,        workspace: WeakEntity<Workspace>,        window: &mut Window,        cx: &mut Context<ExecutionView>,    ) -> Option<AnyElement> {        if !v.has_clipboard_content(window, cx) && !v.has_buffer_content(window, cx) {            return None;        }         Some(            h_flex()                .pl_1()                .when(v.has_clipboard_content(window, cx), |el| {                    let v = v.clone();                    el.child(                        IconButton::new(ElementId::Name("copy-output".into()), IconName::Copy)                            .style(ButtonStyle::Transparent)                            .tooltip(Tooltip::text("Copy Output"))                            .on_click(move |_, window, cx| {                                let clipboard_content = v.clipboard_content(window, cx);                                 if let Some(clipboard_content) = clipboard_content.as_ref() {                                    cx.write_to_clipboard(clipboard_content.clone());                                }                            }),                    )                })                .when(v.has_buffer_content(window, cx), |el| {                    let v = v.clone();                    el.child(                        IconButton::new(                            ElementId::Name("open-in-buffer".into()),                            IconName::FileTextOutlined,                        )                        .style(ButtonStyle::Transparent)                        .tooltip(Tooltip::text("Open in Buffer"))                        .on_click({                            let workspace = workspace.clone();                            move |_, window, cx| {                                let buffer_content =                                    v.update(cx, |item, cx| item.buffer_content(window, cx));                                 if let Some(buffer_content) = buffer_content.as_ref() {                                    let buffer = buffer_content.clone();                                    let editor = Box::new(cx.new(|cx| {                                        let multibuffer = cx.new(|cx| {                                            let mut multi_buffer =                                                MultiBuffer::singleton(buffer.clone(), cx);                                             multi_buffer.set_title("REPL Output".to_string(), cx);                                            multi_buffer                                        });                                         Editor::for_multibuffer(multibuffer, None, window, cx)                                    }));                                    workspace                                        .update(cx, |workspace, cx| {                                            workspace.add_item_to_active_pane(                                                editor, None, true, window, cx,                                            );                                        })                                        .ok();                                }                            }                        }),                    )                })                .into_any_element(),        )    }     pub fn content(&self, window: &mut Window, cx: &mut App) -> Option<AnyElement> {        match self {            Self::Plain { content, .. } => Some(content.clone().into_any_element()),            Self::Markdown { content, .. } => Some(content.clone().into_any_element()),            Self::Stream { content, .. } => Some(content.clone().into_any_element()),            Self::Image { content, .. } => Some(content.clone().into_any_element()),            Self::Message(message) => Some(div().child(message.clone()).into_any_element()),            Self::Table { content, .. } => Some(content.clone().into_any_element()),            Self::Json { content, .. } => Some(content.clone().into_any_element()),            Self::ErrorOutput(error_view) => error_view.render(window, cx),            Self::ClearOutputWaitMarker => None,        }    }     pub fn render(        &self,        workspace: WeakEntity<Workspace>,        window: &mut Window,        cx: &mut Context<ExecutionView>,    ) -> impl IntoElement + use<> {        let max_width =            plain::max_width_for_columns(ReplSettings::get_global(cx).max_columns, window, cx);        let content = self.content(window, cx);         let needs_horizontal_scroll = matches!(self, Self::Table { .. });         h_flex()            .id("output-content")            .w_full()            .when_else(                needs_horizontal_scroll,                |this| this.overflow_x_scroll(),                |this| this.overflow_x_hidden(),            )            .items_start()            .child(                div()                    .when(!needs_horizontal_scroll, |el| {                        el.flex_1().w_full().overflow_x_hidden()                    })                    .when_some(max_width, |el, max_width| el.max_w(max_width))                    .children(content),            )            .children(match self {                Self::Plain { content, .. } => {                    Self::render_output_controls(content.clone(), workspace, window, cx)                }                Self::Markdown { content, .. } => {                    Self::render_output_controls(content.clone(), workspace, window, cx)                }                Self::Stream { content, .. } => {                    Self::render_output_controls(content.clone(), workspace, window, cx)                }                Self::Image { content, .. } => {                    Self::render_output_controls(content.clone(), workspace, window, cx)                }                Self::Json { content, .. } => {                    Self::render_output_controls(content.clone(), workspace, window, cx)                }                Self::ErrorOutput(err) => Some(                    h_flex()                        .pl_1()                        .child({                            let ename = err.ename.clone();                            let evalue = err.evalue.clone();                            let traceback = err.traceback.clone();                            let traceback_text = traceback.read(cx).full_text();                            let full_error = format!("{}: {}\n{}", ename, evalue, traceback_text);                             CopyButton::new("copy-full-error", full_error)                                .tooltip_label("Copy Full Error")                        })                        .child(                            IconButton::new(                                ElementId::Name("open-full-error-in-buffer-traceback".into()),                                IconName::FileTextOutlined,                            )                            .style(ButtonStyle::Transparent)                            .tooltip(Tooltip::text("Open Full Error in Buffer"))                            .on_click({                                let ename = err.ename.clone();                                let evalue = err.evalue.clone();                                let traceback = err.traceback.clone();                                move |_, window, cx| {                                    if let Some(workspace) = workspace.upgrade() {                                        let traceback_text = traceback.read(cx).full_text();                                        let full_error =                                            format!("{}: {}\n{}", ename, evalue, traceback_text);                                        let buffer = cx.new(|cx| {                                            let mut buffer = Buffer::local(full_error, cx)                                                .with_language(language::PLAIN_TEXT.clone(), cx);                                            buffer                                                .set_capability(language::Capability::ReadOnly, cx);                                            buffer                                        });                                        let editor = Box::new(cx.new(|cx| {                                            let multibuffer = cx.new(|cx| {                                                let mut multi_buffer =                                                    MultiBuffer::singleton(buffer.clone(), cx);                                                multi_buffer                                                    .set_title("Full Error".to_string(), cx);                                                multi_buffer                                            });                                            Editor::for_multibuffer(multibuffer, None, window, cx)                                        }));                                        workspace.update(cx, |workspace, cx| {                                            workspace.add_item_to_active_pane(                                                editor, None, true, window, cx,                                            );                                        });                                    }                                }                            }),                        )                        .into_any_element(),                ),                Self::Message(_) => None,                Self::Table { content, .. } => {                    Self::render_output_controls(content.clone(), workspace, window, cx)                }                Self::ClearOutputWaitMarker => None,            })    }     pub fn display_id(&self) -> Option<String> {        match self {            Output::Plain { display_id, .. } => display_id.clone(),            Output::Stream { .. } => None,            Output::Image { display_id, .. } => display_id.clone(),            Output::ErrorOutput(_) => None,            Output::Message(_) => None,            Output::Table { display_id, .. } => display_id.clone(),            Output::Markdown { display_id, .. } => display_id.clone(),            Output::Json { display_id, .. } => display_id.clone(),            Output::ClearOutputWaitMarker => None,        }    }     pub fn new(        data: &MimeBundle,        display_id: Option<String>,        window: &mut Window,        cx: &mut App,    ) -> Self {        match data.richest(rank_mime_type) {            Some(MimeType::Json(json_value)) => match JsonView::from_value(json_value.clone()) {                Ok(json_view) => Output::Json {                    content: cx.new(|_| json_view),                    display_id,                },                Err(_) => Output::Message("Failed to parse JSON".to_string()),            },            Some(MimeType::Plain(text)) => Output::Plain {                content: cx.new(|cx| TerminalOutput::from(text, window, cx)),                display_id,            },            Some(MimeType::Markdown(text)) => {                let content = cx.new(|cx| MarkdownView::from(text.clone(), cx));                Output::Markdown {                    content,                    display_id,                }            }            Some(MimeType::Png(data)) | Some(MimeType::Jpeg(data)) => match ImageView::from(data) {                Ok(view) => Output::Image {                    content: cx.new(|_| view),                    display_id,                },                Err(error) => Output::Message(format!("Failed to load image: {}", error)),            },            Some(MimeType::DataTable(data)) => Output::Table {                content: cx.new(|cx| TableView::new(data, window, cx)),                display_id,            },            Some(MimeType::Html(html_content)) => match html::html_to_markdown(html_content) {                Ok(markdown_text) => {                    let content = cx.new(|cx| MarkdownView::from(markdown_text, cx));                    Output::Markdown {                        content,                        display_id,                    }                }                Err(_) => Output::Plain {                    content: cx.new(|cx| TerminalOutput::from(html_content, window, cx)),                    display_id,                },            },            // Any other media types are not supported            _ => Output::Message("Unsupported media type".to_string()),        }    }} #[derive(Default, Clone, Debug)]pub enum ExecutionStatus {    #[default]    Unknown,    ConnectingToKernel,    Queued,    Executing,    Finished,    ShuttingDown,    Shutdown,    KernelErrored(String),    Restarting,} pub struct ExecutionViewFinishedEmpty;pub struct ExecutionViewFinishedSmall(pub String); pub struct InputReplyEvent {    pub value: String,    pub parent_message: JupyterMessage,} struct PendingInput {    prompt: String,    password: bool,    editor: Entity<Editor>,    parent_message: JupyterMessage,} /// An ExecutionView shows the outputs of an execution./// It can hold zero or more outputs, which the user/// sees as "the output" for a single execution.pub struct ExecutionView {    #[allow(unused)]    workspace: WeakEntity<Workspace>,    pub outputs: Vec<Output>,    pub status: ExecutionStatus,    pending_input: Option<PendingInput>,} impl EventEmitter<ExecutionViewFinishedEmpty> for ExecutionView {}impl EventEmitter<ExecutionViewFinishedSmall> for ExecutionView {}impl EventEmitter<InputReplyEvent> for ExecutionView {} impl ExecutionView {    pub fn new(        status: ExecutionStatus,        workspace: WeakEntity<Workspace>,        _cx: &mut Context<Self>,    ) -> Self {        Self {            workspace,

Lines 1–500 of 1290.